// frontend/src/components/layout/AppShell.jsx
import { Link, useLocation, Navigate } from 'react-router-dom';
import { useAuth } from '../../context/AuthContext.jsx';
import { useT } from '../../i18n/translations.js';
import { clsx } from 'clsx';
import {
  LayoutDashboard, FileText, Zap, Settings, Target,
  CreditCard, Shield, LogOut, Globe, ChevronDown
} from 'lucide-react';
import { useState } from 'react';
import { Spinner } from '../ui/index.jsx';

export default function AppShell({ children }) {
  const { user, loading, logout, setLocale } = useAuth();
  const location = useLocation();
  const t = useT(user?.locale);
  const [langOpen, setLangOpen] = useState(false);

  if (loading) return (
    <div className="min-h-screen flex items-center justify-center bg-gray-50">
      <Spinner size={32} />
    </div>
  );

  if (!user) return <Navigate to="/login" replace />;

  const nav = [
    { to: '/dashboard', icon: LayoutDashboard, label: t('nav.dashboard') },
    { to: '/dashboard/niche', icon: Target, label: t('nav.niches') },
    { to: '/dashboard/content', icon: FileText, label: t('nav.content') },
    { to: '/dashboard/pipeline', icon: Zap, label: t('nav.pipeline') },
    { to: '/dashboard/settings', icon: Settings, label: t('nav.settings') },
    { to: '/dashboard/billing', icon: CreditCard, label: t('nav.billing') },
    ...(user.role === 'superadmin' ? [{ to: '/admin', icon: Shield, label: t('nav.admin') }] : []),
  ];

  return (
    <div className="flex h-screen bg-gray-50 overflow-hidden">
      {/* Sidebar */}
      <aside className="w-60 flex-shrink-0 bg-gray-950 text-gray-300 flex flex-col">
        {/* Logo */}
        <div className="px-6 py-5 border-b border-gray-800">
          <div className="flex items-center gap-2">
            <div className="w-7 h-7 bg-brand-500 rounded-lg flex items-center justify-center">
              <Zap size={14} className="text-white" />
            </div>
            <span className="font-semibold text-white text-sm tracking-tight">Content Machine</span>
          </div>
        </div>

        {/* Nav links */}
        <nav className="flex-1 px-3 py-4 space-y-0.5 overflow-y-auto">
          {nav.map(({ to, icon: Icon, label }) => {
            const active = location.pathname === to || (to !== '/dashboard' && location.pathname.startsWith(to));
            return (
              <Link
                key={to}
                to={to}
                className={clsx(
                  'flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium transition-all',
                  active
                    ? 'bg-brand-600/20 text-brand-400'
                    : 'text-gray-400 hover:text-white hover:bg-gray-800/60'
                )}
              >
                <Icon size={16} />
                {label}
              </Link>
            );
          })}
        </nav>

        {/* Bottom: user + locale + logout */}
        <div className="px-3 py-4 border-t border-gray-800 space-y-1">
          {/* Language switch */}
          <div className="relative">
            <button
              onClick={() => setLangOpen(o => !o)}
              className="w-full flex items-center gap-2 px-3 py-2 rounded-lg text-sm text-gray-400 hover:text-white hover:bg-gray-800/60 transition-all"
            >
              <Globe size={16} />
              <span>{user.locale === 'ro' ? 'Română' : 'English'}</span>
              <ChevronDown size={14} className="ml-auto" />
            </button>
            {langOpen && (
              <div className="absolute bottom-full left-0 w-full mb-1 bg-gray-900 border border-gray-700 rounded-lg overflow-hidden shadow-xl">
                {['en', 'ro'].map(loc => (
                  <button
                    key={loc}
                    onClick={() => { setLocale(loc); setLangOpen(false); }}
                    className={clsx(
                      'w-full text-left px-3 py-2 text-sm transition-colors',
                      user.locale === loc ? 'text-brand-400 bg-brand-600/10' : 'text-gray-300 hover:bg-gray-800'
                    )}
                  >
                    {loc === 'en' ? '🇬🇧 English' : '🇷🇴 Română'}
                  </button>
                ))}
              </div>
            )}
          </div>

          {/* User info */}
          <div className="px-3 py-2">
            <p className="text-xs font-medium text-white truncate">{user.fullName}</p>
            <p className="text-xs text-gray-500 truncate">{user.email}</p>
          </div>

          {/* Logout */}
          <button
            onClick={logout}
            className="w-full flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm text-gray-400 hover:text-red-400 hover:bg-red-500/10 transition-all"
          >
            <LogOut size={16} />
            {t('nav.logout')}
          </button>
        </div>
      </aside>

      {/* Main content */}
      <main className="flex-1 overflow-y-auto">
        {/* Trial banner */}
        {user.status === 'trial' && user.trialEndsAt && (
          <TrialBanner user={user} t={t} />
        )}
        <div className="p-8 max-w-6xl mx-auto animate-fade-in">
          {children}
        </div>
      </main>
    </div>
  );
}

function TrialBanner({ user, t }) {
  const daysLeft = Math.max(0, Math.ceil((new Date(user.trialEndsAt) - new Date()) / 86400000));
  return (
    <div className="bg-amber-50 border-b border-amber-200 px-8 py-2.5 flex items-center justify-between">
      <p className="text-sm text-amber-800">
        ⚡ {t('dashboard.trialBanner', { days: daysLeft })}
      </p>
      <Link
        to="/dashboard/billing"
        className="text-sm font-medium text-amber-700 hover:text-amber-900 transition-colors"
      >
        {t('dashboard.upgradeCta')}
      </Link>
    </div>
  );
}
