import { Link, useLocation } from "@tanstack/react-router";
import { useState, type ReactNode } from "react";
import { useLang, type T } from "@/lib/i18n";
import { useAuth } from "@/lib/auth-context";
import logoAsset from "@/assets/logo.png.asset.json";

const LOGO_URL = logoAsset.url;

export const NAV: { to: string; label: T; children?: { to: string; label: T }[] }[] = [
  { to: "/", label: { si: "මුල් පිටුව", en: "Home" } },
  { to: "/categories", label: { si: "සම්මාන ක්ෂේත්‍ර", en: "Award fields" } },
  {
    to: "/about",
    label: { si: "අපි ගැන", en: "About us" },
    children: [{ to: "/news", label: { si: "නිවේදන", en: "News" } }],
  },
  { to: "/gallery", label: { si: "ඡායාරූප", en: "Gallery" } },
  {
    to: "/contact",
    label: { si: "සම්බන්ධ වන්න", en: "Contact" },
    children: [{ to: "/nominate", label: { si: "නාමයෝජනා ඉදිරිපත් කරන්න", en: "Submit a nomination" } }],
  },
];

export function Lamp({ className = "" }: { className?: string }) {
  return (
    <svg viewBox="0 0 64 64" className={className} aria-hidden fill="none">
      <path className="flicker" d="M32 6c5 8 6 13 0 20-6-7-5-12 0-20z" fill="currentColor" />
      <path d="M12 34h40c-2 9-10 14-20 14S14 43 12 34z" stroke="currentColor" strokeWidth="2" />
      <path d="M26 48v6h12v-6M20 58h24" stroke="currentColor" strokeWidth="2" />
    </svg>
  );
}

/** The official emblem: two hands holding an illuminated oil lamp. */
export function LogoSlot({ size = "sm" }: { size?: "sm" | "lg" | "xl" | "hero" | "showcase" }) {
  const { t } = useLang();
  const dim =
    size === "showcase"
      ? "h-60 w-60 md:h-72 md:w-72"
      : size === "hero"
        ? "h-32 w-32 sm:h-48 sm:w-48 lg:h-72 lg:w-72"
        : size === "xl"
          ? "h-40 w-40"
          : size === "lg"
            ? "h-28 w-28"
            : "h-14 w-14";

  return (
    <img
      src={LOGO_URL}
      alt={t({ si: "තිනුලක උත්තමාචාරයේ නිල ලාංඡනය", en: "Official emblem of Thinulaka Uttamachara" })}
      width={512}
      height={479}
      className={`${dim} logo-mark object-contain`}
    />
  );
}

export function LangSwitch() {
  const { lang, setLang } = useLang();
  return (
    <div className="flex rounded-sm border border-gold/50 text-sm" role="group" aria-label="Language">
      {(["si", "en"] as const).map((l) => (
        <button
          key={l}
          onClick={() => setLang(l)}
          aria-pressed={lang === l}
          className={`px-3 py-1.5 transition-colors ${lang === l ? "bg-gold text-ink" : "text-gold hover:bg-gold/10"}`}
        >
          {l === "si" ? "සිංහල" : "English"}
        </button>
      ))}
    </div>
  );
}

/** Gold-shining, sliding banner leading to the Chairman's message — shown on the home page. */
function ChairmanBanner() {
  const { t } = useLang();
  const text = t({ si: "ජාතියේ හෘදයාංගම උත්තමාචාරය ළඟදීම...", en: "A heartfelt national tribute — coming soon" });
  return (
    <Link to="/chairman-message" className="group block overflow-hidden bg-ink">
      <div className="flex items-center gap-4 px-5 py-3.5">
        <Lamp className="h-5 w-5 shrink-0 text-gold" />
        <div className="min-w-0 flex-1 overflow-hidden">
          <div className="marquee-track">
            {[0, 1].map((i) => (
              <div key={i} className="flex shrink-0 items-center" aria-hidden={i === 1}>
                <span className="text-shine-gold px-6 text-base font-medium">{text}</span>
                <span aria-hidden className="px-2 text-gold">✦</span>
              </div>
            ))}
          </div>
        </div>
        <span aria-hidden className="shrink-0 text-gold transition-transform group-hover:translate-x-1">→</span>
      </div>
    </Link>
  );
}

/** Glossy royal-purple slide with larger sliding text. */
function TopBar() {
  const { t } = useLang();
  const phrases = [
    t({ si: "නිහඬ සේවයට ජාතියේ ගෞරවය", en: "A national tribute to quiet service" }),
    t({ si: "තිනුලක උත්තමාචාරය", en: "Thinulaka Uttamachara" }),
    "2026 | Colombo, Sri Lanka",
  ];
  return (
    <div className="my-6 overflow-hidden bg-royal-shine">
      <div className="flex items-center gap-4 px-5 py-5">
        <Lamp className="h-5 w-5 shrink-0 text-gold" />
        <div className="min-w-0 flex-1 overflow-hidden">
          <div className="marquee-track">
            {[0, 1].map((i) => (
              <div key={i} className="flex shrink-0 items-center" aria-hidden={i === 1}>
                {phrases.map((p, idx) => (
                  <span key={idx} className="flex items-center">
                    <span className="bar-text px-7 text-base md:text-lg">{p}</span>
                    <span aria-hidden className="text-gold">✦</span>
                  </span>
                ))}
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

function Header() {
  const { t } = useLang();
  const [open, setOpen] = useState(false);
  const { signedIn } = useAuth();
  return (
    <header className="sticky top-0 z-40 border-b border-border bg-background/90 backdrop-blur">
      <div className="mx-auto flex max-w-7xl items-center justify-between gap-2 px-3 sm:gap-4 sm:px-5 xl:px-4 py-3">
        <Link to="/" className="flex shrink-0 min-w-0 items-center gap-2 sm:gap-3">
          <LogoSlot />
          <div className="hidden min-w-0 leading-tight min-[420px]:block">
            <div className="font-display text-base text-gold sm:text-lg whitespace-nowrap">තිනුලක උත්තමාචාරය</div>
            <div className="hidden text-[0.65rem] tracking-[0.3em] sm:block text-muted-foreground">THINULAKA UTTAMACHARA 2026</div>
          </div>
        </Link>
        <nav className="hidden items-center gap-4 xl:flex">
          {NAV.map((n) => (
            <div key={n.to} className="group relative">
              <Link to={n.to} className="nav-emboss inline-block whitespace-nowrap rounded-sm px-3 py-2.5 text-sm text-white transition-all hover:text-gold" activeProps={{ className: "nav-emboss-active" }}>
                {t(n.label)}
                {n.children && <span aria-hidden className="ml-1.5 text-[0.6rem] text-gold/70">▾</span>}
              </Link>
              {n.children && (
                <div className="invisible absolute left-1/2 top-full z-50 -translate-x-1/2 pt-3 opacity-0 transition-all group-focus-within:visible group-focus-within:opacity-100 group-hover:visible group-hover:opacity-100">
                  <div className="gold-frame min-w-60 bg-background p-2 shadow-lg">
                    {n.children.map((c) => (
                      <Link key={c.to} to={c.to} className="block rounded-sm px-4 py-2.5 text-sm text-muted-foreground hover:bg-gold/5 hover:text-gold">
                        {t(c.label)}
                      </Link>
                    ))}
                  </div>
                </div>
              )}
            </div>
          ))}
        </nav>
        <div className="flex items-center gap-3">
          {signedIn ? (
            <Link to="/tribute" className="hidden text-sm text-muted-foreground hover:text-gold lg:inline-block">
              {t({ si: "සංවිධායක මෙවලම", en: "Organizer tool" })}
            </Link>
          ) : (
            <Link to="/auth" className="hidden text-sm text-muted-foreground hover:text-gold lg:inline-block">
              {t({ si: "සංවිධායක ඇතුළුවීම", en: "Organizer sign-in" })}
            </Link>
          )}
          <LangSwitch />
          <button className="text-gold xl:hidden" onClick={() => setOpen(!open)} aria-label="Menu" aria-expanded={open}>
            <svg width="26" height="26" viewBox="0 0 24 24" stroke="currentColor" strokeWidth="1.5"><path d="M4 7h16M4 12h16M4 17h16" /></svg>
          </button>
        </div>
      </div>
      {open && (
        <nav className="border-t border-border px-5 py-4 xl:hidden">
          {NAV.map((n) => (
            <div key={n.to}>
              <Link to={n.to} onClick={() => setOpen(false)} className="nav-emboss my-1 block rounded-sm px-4 py-2.5 text-lg text-white hover:text-gold">
                {t(n.label)}
              </Link>
              {n.children?.map((c) => (
                <Link key={c.to} to={c.to} onClick={() => setOpen(false)} className="nav-emboss my-1 block rounded-sm px-4 py-2.5 pl-6 text-base text-white hover:text-gold">
                  {t(c.label)}
                </Link>
              ))}
            </div>
          ))}
          {signedIn ? (
            <Link to="/tribute" onClick={() => setOpen(false)} className="block py-2.5 text-lg text-gold">
              {t({ si: "සංවිධායක මෙවලම", en: "Organizer tool" })}
            </Link>
          ) : (
            <Link to="/auth" onClick={() => setOpen(false)} className="block py-2.5 text-lg text-gold">
              {t({ si: "සංවිධායක ඇතුළුවීම", en: "Organizer sign-in" })}
            </Link>
          )}
        </nav>
      )}
    </header>
  );
}

function Footer() {
  const { t } = useLang();
  return (
    <footer className="bg-footer mt-24 border-t border-border">
      <div className="mx-auto grid max-w-7xl gap-10 px-5 py-14 md:grid-cols-3">
        <div>
          <LogoSlot size="lg" />
          <p className="mt-5 font-sinhala-display text-gold">ඔබ නිහඬව කළ සියල්ල — අපි හදවතින්ම දැක්කෙමු.</p>
          <p className="mt-2 text-sm text-muted-foreground">2026 | Colombo, Sri Lanka</p>
        </div>
        <div className="grid grid-cols-2 gap-2 text-sm">
          {NAV.flatMap((n) => [n, ...(n.children ?? [])]).map((n) => (
            <Link key={n.to} to={n.to} className="text-muted-foreground hover:text-gold">{t(n.label)}</Link>
          ))}
        </div>
        <div className="text-sm text-muted-foreground">
          <p>{t({ si: "මෙය තරඟයක් නොවේ — සෑම උත්තමයෙකුටම සමාන ගෞරවයකි.", en: "This is not a competition — every honoree receives equal dignity." })}</p>
          <p className="mt-6">© 2026 Thinulaka Uttamachara</p>
        </div>
      </div>
    </footer>
  );
}

export function SiteLayout({ children }: { children: ReactNode }) {
  const { pathname } = useLocation();
  return (
    <div className="flex min-h-screen flex-col">
      <a href="#main" className="sr-only focus:not-sr-only">Skip to content</a>
      <Header />
      {pathname === "/" && <ChairmanBanner />}
      <TopBar />
      <main id="main" className="flex-1">{children}</main>
      <Footer />
    </div>
  );
}

export function PageHeader({ eyebrow, title, intro }: { eyebrow: T; title: T; intro?: T }) {
  const { t } = useLang();
  return (
    <section className="bg-section border-b border-border">
      <div className="mx-auto max-w-4xl px-5 py-20 text-center fade-up">
        <div className="eyebrow">{t(eyebrow)}</div>
        <h1 className="mt-4 text-4xl text-foreground md:text-6xl">{t(title)}</h1>
        <div className="gold-rule mx-auto mt-8 w-40" />
        {intro && <p className="mx-auto mt-8 max-w-2xl text-lg text-muted-foreground">{t(intro)}</p>}
      </div>
    </section>
  );
}

export function Notice({ children }: { children: ReactNode }) {
  return <div className="rounded-sm border border-gold/40 bg-gold/5 px-5 py-4 text-sm text-gold">{children}</div>;
}

export function EmptyState({ text }: { text: T }) {
  const { t } = useLang();
  return (
    <div className="gold-frame mx-auto max-w-2xl px-8 py-16 text-center">
      <Lamp className="mx-auto h-12 w-12 text-gold" />
      <p className="mt-6 text-lg text-muted-foreground">{t(text)}</p>
    </div>
  );
}
