"use client";

/**
 * Client portal layout — applies agency branding from session.
 * Simplified sidebar with only allowed pages. Redirects to login if
 * no valid session.
 */

import { useEffect, useState, type ReactNode } from "react";
import { usePathname, useRouter, useParams } from "next/navigation";
import Link from "next/link";
import { LayoutDashboard, BarChart3, TrendingUp, Crosshair, ShieldCheck, Rocket, Search, Sparkles, Lightbulb, LogOut } from "lucide-react";
import type { PortalConfig } from "@/lib/portal-config";

interface Session {
  brandId: string; email: string; agencyName: string | null;
  agencyLogo: string | null; primaryColor: string | null;
  portalConfig: PortalConfig | null; hideSourceBranding: boolean;
}

const NAV: Array<{ id: string; label: string; href: string; icon: React.ComponentType<{ className?: string }> }> = [
  { id: "dashboard", label: "Dashboard", href: "dashboard", icon: LayoutDashboard },
  { id: "report", label: "Report", href: "report", icon: BarChart3 },
  { id: "rankings", label: "Rankings", href: "rankings", icon: Crosshair },
  { id: "conversions", label: "Conversions", href: "conversions", icon: TrendingUp },
  { id: "audit", label: "Audit", href: "audit", icon: ShieldCheck },
  { id: "launcher", label: "Page Launches", href: "launcher", icon: Rocket },
  { id: "search_performance", label: "Search", href: "search", icon: Search },
  { id: "ai_summary", label: "AI Summary", href: "ai-summary", icon: Sparkles },
  { id: "recommendations", label: "Recommendations", href: "recommendations", icon: Lightbulb },
];

export default function ClientLayout({ children }: { children: ReactNode }) {
  const params = useParams();
  const brandId = params.brandId as string;
  const pathname = usePathname();
  const router = useRouter();
  const [session, setSession] = useState<Session | null>(null);
  const [checked, setChecked] = useState(false);

  useEffect(() => {
    // Read session from a lightweight API call
    fetch(`/api/client-portal/dashboard?brandId=${brandId}`)
      .then((r) => r.ok ? r.json() : null)
      .then((data) => {
        if (data?.portal) {
          setSession({
            brandId, email: "", agencyName: data.portal.agencyName,
            agencyLogo: data.portal.agencyLogo, primaryColor: data.portal.primaryColor,
            portalConfig: data.portal.portalConfig ?? null,
            hideSourceBranding: true,
          });
        } else {
          router.replace(`/client/${brandId}/login`);
        }
      })
      .catch(() => router.replace(`/client/${brandId}/login`))
      .finally(() => setChecked(true));
  }, [brandId, router]);

  // Don't render anything until session is checked (prevent flash)
  if (!checked) return <div className="flex items-center justify-center h-screen"><div className="w-8 h-8 border-4 border-slate-200 border-t-slate-600 rounded-full animate-spin" /></div>;

  // Login page doesn't use this layout chrome
  if (pathname.endsWith("/login")) return <>{children}</>;

  if (!session) return null;

  const primary = session.primaryColor || "#EF4444";
  const agency = session.agencyName || "Your Agency";
  const navItems = NAV.filter((n) => {
    if (!session.portalConfig) return ["dashboard", "report", "rankings", "conversions", "audit"].includes(n.id);
    return session.portalConfig.pages?.[n.id]?.enabled ?? false;
  });

  return (
    <div className="flex h-screen bg-slate-100">
      {/* Sidebar */}
      <aside className="w-56 bg-white border-r border-slate-200 flex flex-col shrink-0">
        <div className="px-5 py-5 border-b border-slate-100">
          {session.agencyLogo ? (
            /* eslint-disable-next-line @next/next/no-img-element */
            <img src={session.agencyLogo} alt={agency} className="h-8 object-contain" />
          ) : (
            <span className="text-lg font-bold" style={{ color: primary }}>{agency}</span>
          )}
        </div>
        <nav className="flex-1 px-3 py-4 space-y-1">
          {navItems.map((item) => {
            const active = pathname.includes(`/${item.href}`);
            return (
              <Link
                key={item.id}
                href={`/client/${brandId}/${item.href}`}
                className={`flex items-center gap-2.5 px-3 py-2 rounded-lg text-sm font-medium transition-colors ${
                  active ? "text-white" : "text-slate-600 hover:bg-slate-50"
                }`}
                style={active ? { backgroundColor: primary } : undefined}
              >
                <item.icon className="w-4 h-4" />
                {item.label}
              </Link>
            );
          })}
        </nav>
        {!session.hideSourceBranding && (
          <div className="px-5 py-3 border-t border-slate-100">
            <p className="text-[10px] text-slate-400">Powered by <span className="font-bold text-brand-600">meSEO</span></p>
          </div>
        )}
      </aside>

      {/* Main */}
      <div className="flex-1 flex flex-col overflow-hidden">
        <header className="h-14 border-b border-slate-200 bg-white flex items-center justify-between px-6">
          <span className="text-sm font-semibold text-slate-900">{agency}</span>
          <div className="flex items-center gap-3">
            <span className="text-xs text-slate-500">{session.email}</span>
            <button onClick={() => { document.cookie = "meseo_client_session=; path=/; max-age=0"; router.replace(`/client/${brandId}/login`); }} className="flex items-center gap-1 text-xs text-slate-500 hover:text-slate-800">
              <LogOut className="w-3.5 h-3.5" /> Sign out
            </button>
          </div>
        </header>
        <main className="flex-1 overflow-auto p-6">{children}</main>
      </div>
    </div>
  );
}
