"use client";

import { useEffect, useState } from "react";
import { usePathname } from "next/navigation";
import Link from "next/link";
import { api, auth, currentShopParam } from "@/lib/api";
import { readBrand, writeBrand, applyBrandVars, DEFAULT_BRAND, type Brand } from "@/lib/brand";

/** Routes that belong to a specific merchant's program, so they wear that
 *  merchant's branding. Everything else is our own marketing site. */
const MERCHANT_SCOPED = ["/signup", "/login", "/dashboard", "/store"];

export function PublicHeader() {
  const pathname = usePathname() || "/";
  const merchantScoped = MERCHANT_SCOPED.some((p) => pathname.startsWith(p));
  const [brand, setBrand] = useState<Brand>(DEFAULT_BRAND);
  const [affiliate, setAffiliate] = useState<{ id: string; name: string } | null>(null);
  const [shopQ, setShopQ] = useState("");

  // Is an affiliate logged in? If so, show their name + Log out instead of the
  // login / sign-up CTAs (those are for logged-out visitors only). Also capture
  // the store so the affiliate links stay scoped to it (…?shop=store).
  useEffect(() => {
    const a = auth.get();
    setAffiliate(a?.id ? { id: a.id, name: a.name } : null);
    const s = currentShopParam();
    setShopQ(s ? `?shop=${encodeURIComponent(s)}` : "");
  }, [pathname]);

  const logout = () => {
    auth.clear();
    window.location.href = "/login";
  };

  useEffect(() => {
    // Marketing pages are ours — never show a merchant's name or colours here.
    if (!merchantScoped) {
      setBrand(DEFAULT_BRAND);
      applyBrandVars(DEFAULT_BRAND);
      return;
    }
    const cached = readBrand();
    if (cached.name || cached.logoUrl) setBrand(cached);
    applyBrandVars(cached);
    // Public endpoint — /admin/* needs a Shopify session token and 401s here.
    api
      .get("/affiliates/signup-config")
      .then((c) => {
        const b = c?.branding ?? {};
        const next: Brand = {
          logoUrl: b.logoUrl ?? DEFAULT_BRAND.logoUrl,
          name: c?.programName || DEFAULT_BRAND.name,
          brandColor: b.brandColor ?? DEFAULT_BRAND.brandColor,
          brandSecondaryColor: b.brandSecondaryColor ?? DEFAULT_BRAND.brandSecondaryColor,
        };
        setBrand(next);
        writeBrand(next);
        applyBrandVars(next);
      })
      .catch(() => {
        /* keep whatever we have */
      });
  }, [merchantScoped]);

  return (
    <header className="sticky top-0 z-40 border-b border-white/10 bg-[var(--brand)] text-white">
      <nav className="mx-auto flex max-w-6xl items-center gap-6 px-6 py-3 text-sm">
        <Link href="/" className="flex shrink-0 items-center gap-2.5">
          {merchantScoped ? (
            <>
              {brand.logoUrl ? (
                // eslint-disable-next-line @next/next/no-img-element
                <img src={brand.logoUrl} alt={brand.name} className="h-8 w-8 rounded-md bg-white object-contain p-1" />
              ) : null}
              <span className="text-base font-semibold">{brand.name}</span>
            </>
          ) : (
            <>
              {/* eslint-disable-next-line @next/next/no-img-element */}
              <img src="/trackopia-icon.svg" alt="" aria-hidden className="h-8 w-8 rounded-md bg-white object-contain p-1" />
              {/* eslint-disable-next-line @next/next/no-img-element */}
              <img src="/trackopia-wordmark-light.svg" alt="Trackopia" className="hidden h-7 w-auto sm:block" />
              <span className="text-base font-semibold sm:hidden">Trackopia</span>
            </>
          )}
        </Link>

        <div className="ml-auto flex items-center gap-5">
          {!merchantScoped && (
            <>
              <a href="#features" className="hidden opacity-90 hover:opacity-100 md:inline">Features</a>
              <a href="#pricing" className="hidden opacity-90 hover:opacity-100 md:inline">Pricing</a>
              <a href="#faq" className="hidden opacity-90 hover:opacity-100 md:inline">FAQ</a>
              <Link href="/demo" className="opacity-90 hover:opacity-100">Demo</Link>
            </>
          )}
          {affiliate ? (
            <>
              <Link href="/dashboard" className="font-medium opacity-90 hover:opacity-100">{affiliate.name}</Link>
              <button
                onClick={logout}
                className="rounded-lg bg-white/15 px-3.5 py-1.5 font-semibold ring-1 ring-inset ring-white/25 transition hover:bg-white/25"
              >
                Log out
              </button>
            </>
          ) : merchantScoped ? (
            // Affiliate CTAs only on a store-scoped page — keep the ?shop so they
            // land on that store's program, never a store-less signup.
            <>
              <Link href={`/login${shopQ}`} className="opacity-90 hover:opacity-100">Affiliate login</Link>
              <Link
                href={`/signup${shopQ}`}
                className="rounded-lg bg-white/15 px-3.5 py-1.5 font-semibold ring-1 ring-inset ring-white/25 transition hover:bg-white/25"
              >
                Become an affiliate
              </Link>
            </>
          ) : null}
        </div>
      </nav>
    </header>
  );
}
