"use client";

import Link from "next/link";
import { useEffect, useRef, useState } from "react";

type Account = {
  id: string;
  email: string;
  name: string | null;
  avatarUrl: string | null;
  status: string;
};

type Props = {
  prefix: string;
  locale: "sr" | "en";
};

/**
 * Header user menu. When anonymous → "Prijava" pill. When authenticated →
 * avatar trigger that opens a rich dropdown with profile, inbox, favorites,
 * saved searches, and logout.
 *
 * Why a custom popover and not a generic library?
 *   • Zero new deps — keeps bundle lean.
 *   • Full control over animation + brand styling.
 *   • Outside-click and Esc handled with native primitives.
 */
export function HeaderUserMenu({ prefix, locale }: Props) {
  const [account, setAccount] = useState<Account | null>(null);
  const [hydrated, setHydrated] = useState(false);
  const [open, setOpen] = useState(false);
  const [busy, setBusy] = useState(false);
  const wrapperRef = useRef<HTMLDivElement | null>(null);

  useEffect(() => {
    let cancelled = false;
    fetch("/api/visitor-auth/me", { credentials: "same-origin" })
      .then((r) => r.json())
      .then((data: { account: Account | null }) => {
        if (cancelled) return;
        setAccount(data.account ?? null);
        setHydrated(true);
      })
      .catch(() => {
        if (!cancelled) setHydrated(true);
      });
    return () => {
      cancelled = true;
    };
  }, []);

  // Outside-click + Esc to close.
  useEffect(() => {
    if (!open) return;
    function onClick(e: MouseEvent) {
      if (!wrapperRef.current) return;
      if (!wrapperRef.current.contains(e.target as Node)) setOpen(false);
    }
    function onKey(e: KeyboardEvent) {
      if (e.key === "Escape") setOpen(false);
    }
    window.addEventListener("mousedown", onClick);
    window.addEventListener("keydown", onKey);
    return () => {
      window.removeEventListener("mousedown", onClick);
      window.removeEventListener("keydown", onKey);
    };
  }, [open]);

  async function logout() {
    setBusy(true);
    try {
      await fetch("/api/visitor-auth/logout", { method: "POST" });
    } catch {
      /* noop */
    }
    window.location.assign(prefix || "/");
  }

  if (!hydrated) {
    // Reserve space so the header doesn't jump.
    return <div className="h-10 w-10 shrink-0" aria-hidden="true" />;
  }

  // Anonymous: simple "Prijava" pill.
  if (!account) {
    return (
      <Link
        href={`${prefix}/prijavi-se`}
        className="hidden h-10 items-center gap-1.5 rounded-full border border-[#ede8e3] bg-white px-3.5 text-sm font-bold text-[#0c1828] transition hover:border-[#c2410c]/30 hover:bg-[#fff4f0] hover:text-[#c2410c] md:inline-flex"
      >
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
          <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2" />
          <circle cx="12" cy="7" r="4" />
        </svg>
        {locale === "en" ? "Sign in" : "Prijava"}
      </Link>
    );
  }

  const initial = (account.name?.[0] || account.email[0] || "?").toUpperCase();
  const displayName = account.name?.split(" ")[0] || locale === "en" ? "Account" : "Nalog";
  const isPending = account.status === "PENDING_EMAIL_VERIFY";

  return (
    <div ref={wrapperRef} className="relative">
      <button
        type="button"
        onClick={() => setOpen((v) => !v)}
        aria-expanded={open}
        aria-haspopup="menu"
        title={account.email}
        className="hidden h-10 items-center gap-2 rounded-full border border-[#ede8e3] bg-white pl-1.5 pr-3 text-sm font-bold text-[#0c1828] transition hover:border-[#c2410c]/30 hover:bg-[#fff4f0] hover:text-[#c2410c] md:inline-flex"
      >
        {account.avatarUrl ? (
          // eslint-disable-next-line @next/next/no-img-element
          <img
            src={account.avatarUrl}
            alt=""
            width={28}
            height={28}
            className="h-7 w-7 rounded-full object-cover"
          />
        ) : (
          <span className="flex h-7 w-7 items-center justify-center rounded-full bg-gradient-to-br from-[#c2410c] to-[#d94e22] text-xs font-black text-white shadow-[0_2px_8px_rgba(194,65,12,0.3)]">
            {initial}
          </span>
        )}
        <span className="max-w-[80px] truncate text-xs">{displayName}</span>
        <svg
          width="11"
          height="11"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          strokeWidth="2.4"
          strokeLinecap="round"
          strokeLinejoin="round"
          aria-hidden="true"
          className={`transition ${open ? "rotate-180" : ""}`}
        >
          <polyline points="6 9 12 15 18 9" />
        </svg>
      </button>

      {open && (
        <div
          role="menu"
          className="absolute right-0 top-full z-50 mt-2 w-64 origin-top-right overflow-hidden rounded-2xl border border-[#ede8e3] bg-white shadow-[0_24px_60px_rgba(12,24,40,0.18)]"
          style={{ animation: "page-fade-in 200ms ease both" }}
        >
          {/* Profile header */}
          <div className="border-b border-[#ede8e3] bg-gradient-to-br from-[#fff4f0] to-white p-4">
            <div className="flex items-center gap-3">
              {account.avatarUrl ? (
                // eslint-disable-next-line @next/next/no-img-element
                <img
                  src={account.avatarUrl}
                  alt=""
                  width={40}
                  height={40}
                  className="h-10 w-10 rounded-full object-cover"
                />
              ) : (
                <span className="flex h-10 w-10 items-center justify-center rounded-full bg-gradient-to-br from-[#c2410c] to-[#d94e22] text-base font-black text-white shadow-[0_4px_12px_rgba(194,65,12,0.35)]">
                  {initial}
                </span>
              )}
              <div className="min-w-0 flex-1">
                <p className="truncate text-sm font-bold text-[#0c1828]">
                  {account.name || account.email.split("@")[0]}
                </p>
                <p className="truncate text-xs text-[#6b7280]">{account.email}</p>
              </div>
            </div>
            {isPending && (
              <p className="mt-2 inline-flex items-center gap-1 rounded-full border border-amber-300 bg-amber-50 px-2 py-0.5 text-[0.62rem] font-bold text-amber-800">
                ⚠️ E-mail nije potvrđen
              </p>
            )}
          </div>

          {/* Menu items */}
          <div className="p-2">
            {[
              { href: `${prefix}/nalog`, icon: "🏠", label: locale === "en" ? "My account" : "Moj nalog" },
              { href: `${prefix}/nalog/poruke`, icon: "💬", label: locale === "en" ? "Messages" : "Poruke" },
              { href: `${prefix}/favoriti`, icon: "❤️", label: locale === "en" ? "Favorites" : "Favoriti" },
              { href: `${prefix}/uporedi`, icon: "⚖️", label: locale === "en" ? "Compare" : "Uporedi" },
            ].map((item) => (
              <Link
                key={item.href}
                href={item.href}
                onClick={() => setOpen(false)}
                role="menuitem"
                className="flex items-center gap-3 rounded-xl px-3 py-2 text-sm font-semibold text-[#0c1828] transition hover:bg-[#fff4f0] hover:text-[#c2410c]"
              >
                <span className="text-base">{item.icon}</span>
                {item.label}
              </Link>
            ))}
          </div>

          {/* Footer: logout */}
          <div className="border-t border-[#ede8e3] bg-[#faf9f7] p-2">
            <button
              type="button"
              disabled={busy}
              onClick={logout}
              className="flex w-full items-center gap-3 rounded-xl px-3 py-2 text-sm font-semibold text-[#6b7280] transition hover:bg-red-50 hover:text-red-700 disabled:opacity-60"
            >
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
                <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4" />
                <polyline points="16 17 21 12 16 7" />
                <line x1="21" y1="12" x2="9" y2="12" />
              </svg>
              {busy
                ? locale === "en" ? "Signing out…" : "Odjavljujem…"
                : locale === "en" ? "Sign out" : "Odjavi se"}
            </button>
          </div>
        </div>
      )}
    </div>
  );
}
