"use client";

import Image from "next/image";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { useLocale } from "@/i18n/LocaleProvider";
import { TranslationKey } from "@/i18n/dictionaries";
import { useEffect, useState } from "react";
import { Icon, IconName } from "./icons";
import { LoginScreen } from "./LoginScreen";
import { getSession, logout, StaffSession } from "@/lib/api";

interface NavItem {
  href: string;
  labelKey: TranslationKey;
  icon: IconName;
}

const NAV: NavItem[] = [
  { href: "/", labelKey: "nav.dashboard", icon: "dashboard" },
  { href: "/analytics", labelKey: "nav.analytics", icon: "analytics" },
  { href: "/fleet", labelKey: "nav.fleet", icon: "fleet" },
  { href: "/trips", labelKey: "nav.trips", icon: "trips" },
  { href: "/zones", labelKey: "nav.zones", icon: "zones" },
  { href: "/pricing", labelKey: "nav.pricing", icon: "pricing" },
  { href: "/customers", labelKey: "nav.customers", icon: "customers" },
  { href: "/investors", labelKey: "nav.investors", icon: "investors" },
  { href: "/maintenance", labelKey: "nav.maintenance", icon: "maintenance" },
  { href: "/staff", labelKey: "nav.staff", icon: "staff" },
  { href: "/audit", labelKey: "nav.audit", icon: "audit" },
  { href: "/api-keys", labelKey: "nav.apiKeys", icon: "apiKeys" },
];

export function AppShell({ children }: { children: React.ReactNode }) {
  const { t, toggleLocale } = useLocale();
  const pathname = usePathname();

  // `undefined` = not yet read from localStorage. Distinguishing it from `null` avoids
  // flashing the login screen for an already-signed-in user on every refresh.
  const [session, setSession] = useState<StaffSession | null | undefined>(undefined);
  useEffect(() => setSession(getSession()), []);

  if (session === undefined) {
    return <div className="min-h-screen bg-background" />;
  }
  if (session === null) {
    // No session, the dashboard is never rendered, so deep links can't bypass sign-in.
    return <LoginScreen onSignedIn={() => setSession(getSession())} />;
  }

  const signOut = () => {
    logout();
    setSession(null);
  };

  return (
    <div className="flex min-h-screen">
      {/* Sidebar, flips to the right automatically under RTL */}
      <aside className="hidden w-64 shrink-0 flex-col border-e border-line bg-surface md:flex">
        <div className="flex items-center gap-3 px-5 py-5">
          <Image
            src="/beeb-logo.png"
            alt="BeebBeeb"
            width={40}
            height={40}
            className="rounded-full"
            priority
          />
          <div>
            <div className="text-sm font-bold leading-tight">{t("app.title")}</div>
            <div className="text-xs text-muted">{t("app.subtitle")}</div>
          </div>
        </div>

        <nav className="flex-1 space-y-1 px-3 py-2">
          {NAV.map((item) => {
            const active =
              item.href === "/"
                ? pathname === "/"
                : pathname.startsWith(item.href);
            return (
              <Link
                key={item.href}
                href={item.href}
                // Nav pills are a sanctioned brand-yellow surface (design-system.md
                // §2.1). Solid brand + ink reads 13.1:1 in BOTH themes, the previous
                // `brand-soft/40` turned olive over the dark canvas and left near-black
                // text sitting on it.
                className={`flex items-center gap-3 rounded-full px-3 py-2 text-sm font-medium transition ${
                  active
                    ? "bg-brand text-brand-ink"
                    : "text-foreground/80 hover:bg-background"
                }`}
              >
                <Icon name={item.icon} />
                {t(item.labelKey)}
              </Link>
            );
          })}
        </nav>
      </aside>

      {/* Main column */}
      <div className="flex min-w-0 flex-1 flex-col">
        <header className="flex items-center justify-between gap-3 border-b border-line bg-surface px-5 py-3">
          <div className="flex items-center gap-2 md:hidden">
            <Image
              src="/beeb-logo.png"
              alt="BeebBeeb"
              width={32}
              height={32}
              className="rounded-full"
            />
            <span className="text-sm font-bold">{t("app.title")}</span>
          </div>
          <div className="flex flex-1 items-center justify-end gap-2">
            <div className="flex items-center gap-3">
            <span className="hidden text-sm text-muted sm:inline">{session.name}</span>
            <button className="btn-ghost" onClick={signOut}>
              {t("session.signOut")}
            </button>
          </div>
            <button className="btn-ghost" onClick={toggleLocale}>
              {t("lang.toggle")}
            </button>
          </div>
        </header>

        <main className="mx-auto w-full max-w-6xl flex-1 p-5 md:p-8">{children}</main>
      </div>
    </div>
  );
}
