"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 { Icon, IconName } from "./icons";
import { LoginScreen } from "./LoginScreen";
import { useSession } from "@/session/SessionProvider";
import { clearSession, getInvestorName, login } from "@/lib/api";

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

const NAV: NavItem[] = [
  { href: "/", labelKey: "nav.overview", icon: "overview" },
  { href: "/vehicles", labelKey: "nav.vehicles", icon: "overview" },
  { href: "/earnings", labelKey: "nav.earnings", icon: "earnings" },
  { href: "/wallet", labelKey: "nav.wallet", icon: "wallet" },
  { href: "/profile", labelKey: "nav.profile", icon: "profile" },
];

export function AppShell({ children }: { children: React.ReactNode }) {
  const { t, toggleLocale } = useLocale();
  const pathname = usePathname();
  const { investorId, hasToken, ready, apply, clear } = useSession();

  if (!ready) {
    return <div className="min-h-screen bg-background" />;
  }
  // No session, the dashboard never renders, so a deep link can't reach investor data.
  // (investor-service also rejects a mismatched token, so this is the door, not the lock.)
  if (!investorId || !hasToken) {
    return (
      <LoginScreen
        onSignedIn={(id, token) => apply(id, token)}
      />
    );
  }

  return (
    <div className="flex min-h-screen">
      <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>

      <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">{getInvestorName()}</span>
            <button
              className="btn-ghost"
              onClick={() => {
                clearSession();
                clear();
              }}
            >
              {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-5xl flex-1 p-5 md:p-8">{children}</main>
      </div>
    </div>
  );
}
