'use client';

import { useState, useEffect } from 'react';
import { useRouter, usePathname } from 'next/navigation';
import Link from 'next/link';

const NAV = [
  { label: 'Dashboard', href: '/dashboard' },
  { label: 'Invoices', href: '/invoices' },
  { label: 'Payments', href: '/payments' },
  { label: 'Tickets', href: '/tickets' },
  { label: 'Profile', href: '/profile' },
];

export default function PortalLayout({ children }: { children: React.ReactNode }) {
  const router = useRouter();
  const pathname = usePathname();
  const [client, setClient] = useState<any>(null);

  useEffect(() => {
    const token = localStorage.getItem('portalToken');
    const clientData = localStorage.getItem('portalClient');
    if (!token) { router.push('/login'); return; }
    if (clientData) setClient(JSON.parse(clientData));
  }, [router]);

  function handleLogout() {
    localStorage.removeItem('portalToken');
    localStorage.removeItem('portalClient');
    router.push('/login');
  }

  return (
    <div className="min-h-screen bg-surface-50">
      {/* Header */}
      <header className="bg-white border-b border-surface-200">
        <div className="max-w-5xl mx-auto px-4 sm:px-6">
          <div className="flex items-center justify-between h-14">
            <div className="flex items-center gap-2">
              <svg width="24" height="24" viewBox="0 0 40 40" fill="none" className="text-brand-600">
                <rect width="40" height="40" rx="10" fill="currentColor" fillOpacity="0.1" />
                <path d="M12 20h16M20 12v16" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" />
              </svg>
              <span className="text-base font-bold text-surface-900 tracking-tight">FiberOps</span>
              <span className="text-xs bg-brand-50 text-brand-700 px-2 py-0.5 rounded-full font-medium ml-1">Portal</span>
            </div>
            <div className="flex items-center gap-4">
              {client && <span className="text-sm text-surface-500 hidden sm:block">{client.firstName} {client.lastName}</span>}
              <button onClick={handleLogout} className="text-sm text-surface-500 hover:text-surface-800 cursor-pointer transition-colors">Sign out</button>
            </div>
          </div>
          {/* Nav tabs */}
          <nav className="flex gap-1 -mb-px">
            {NAV.map((item) => {
              const isActive = pathname === item.href;
              return (
                <Link key={item.href} href={item.href}
                  className={`px-4 py-2.5 text-sm font-medium border-b-2 transition-colors ${
                    isActive ? 'border-brand-600 text-brand-700' : 'border-transparent text-surface-500 hover:text-surface-700 hover:border-surface-300'
                  }`}>{item.label}</Link>
              );
            })}
          </nav>
        </div>
      </header>

      <main className="max-w-5xl mx-auto px-4 sm:px-6 py-6">{children}</main>
    </div>
  );
}
