"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;
};

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

const FAV_KEY = "bp_favorites_v1";

/**
 * Visitor identity dropdown that lives in the **top bar** of a business
 * portal. Replaces the in-flow "Prijava" link with a richer experience
 * once the user has signed in:
 *
 *   • Avatar (initial gradient or Google picture)
 *   • First name visible to the right
 *   • Tiny pulse dot indicates "you have unread messages"
 *   • Click → premium dropdown with: Moj nalog · Poruke (count) · Favoriti
 *     (count) · Uporedi · Odjavi se
 *
 * Why in the top bar and not the main bar?
 *   • This is a **business portal** — visitor accounts are secondary to the
 *     "Dodaj firmu" CTA. Hiding consumer features in the utility row keeps
 *     the main bar laser-focused.
 *   • Pattern matches Booking, Crunchbase, LinkedIn (utility row owns
 *     account, locale, help; main bar owns search + categories + CTA).
 */
export function TopBarUserMenu({ prefix, locale }: Props) {
  const en = locale === "en";
  const [account, setAccount] = useState<Account | null>(null);
  const [hydrated, setHydrated] = useState(false);
  const [open, setOpen] = useState(false);
  const [unreadMessages, setUnreadMessages] = useState(0);
  const [favCount, setFavCount] = useState(0);
  const [busy, setBusy] = useState(false);
  const wrapperRef = useRef<HTMLDivElement | null>(null);

  // Hydrate identity.
  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;
    };
  }, []);

  // Hydrate counters (favorites from localStorage, messages from API).
  useEffect(() => {
    function readFav() {
      try {
        const raw = window.localStorage.getItem(FAV_KEY);
        if (!raw) {
          setFavCount(0);
          return;
        }
        const parsed = JSON.parse(raw);
        setFavCount(Array.isArray(parsed) ? parsed.length : 0);
      } catch {
        setFavCount(0);
      }
    }
    readFav();
    window.addEventListener("bp:favorites:change", readFav);
    window.addEventListener("storage", readFav);
    return () => {
      window.removeEventListener("bp:favorites:change", readFav);
      window.removeEventListener("storage", readFav);
    };
  }, []);

  // Poll unread message count when authed (every 30s).
  useEffect(() => {
    if (!account) {
      return;
    }
    let cancelled = false;
    let timer: ReturnType<typeof setTimeout>;

    async function load() {
      try {
        const res = await fetch("/api/messages/unread-count", { cache: "no-store" });
        if (!res.ok) return;
        const data = (await res.json()) as { count?: number };
        if (cancelled) return;
        setUnreadMessages(typeof data.count === "number" ? data.count : 0);
      } catch {
        /* noop */
      }
    }
    void load();
    function schedule() {
      timer = setTimeout(async () => {
        if (cancelled) return;
        await load();
        schedule();
      }, 30_000);
    }
    schedule();

    return () => {
      cancelled = true;
      if (timer) clearTimeout(timer);
    };
  }, [account]);

  // Close on outside click + Esc.
  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) {
    return <div className="h-5 w-20" aria-hidden="true" />;
  }

  // Anonymous → discreet "Prijavi se" link.
  if (!account) {
    return (
      <Link
        href={`${prefix}/prijavi-se`}
        className="inline-flex items-center gap-1 transition hover:text-white"
      >
        <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
          <path d="M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4" />
          <polyline points="10 17 15 12 10 7" />
          <line x1="15" y1="12" x2="3" y2="12" />
        </svg>
        {en ? "Sign in" : "Prijavi se"}
      </Link>
    );
  }

  const initial = (account.name?.[0] || account.email[0] || "?").toUpperCase();
  const displayName = account.name?.split(" ")[0] || account.email.split("@")[0];

  return (
    <div ref={wrapperRef} className="relative">
      <button
        type="button"
        onClick={() => setOpen((v) => !v)}
        aria-expanded={open}
        aria-haspopup="menu"
        title={account.email}
        className="group inline-flex items-center gap-2 rounded-full px-1 py-0.5 text-[0.71rem] font-semibold transition hover:text-white"
      >
        <span className="relative inline-flex">
          {account.avatarUrl ? (
            // eslint-disable-next-line @next/next/no-img-element
            <img
              src={account.avatarUrl}
              alt=""
              width={20}
              height={20}
              className="h-5 w-5 rounded-full object-cover ring-1 ring-white/25"
            />
          ) : (
            <span className="flex h-5 w-5 items-center justify-center rounded-full bg-gradient-to-br from-[#c2410c] to-[#d94e22] text-[0.6rem] font-black text-white ring-1 ring-white/15">
              {initial}
            </span>
          )}
          {/* Unread dot — tiny but unmistakable */}
          {unreadMessages > 0 && (
            <span
              aria-hidden="true"
              className="absolute -right-0.5 -top-0.5 inline-flex h-2 w-2"
            >
              <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-[#c2410c] opacity-75" />
              <span className="relative inline-flex h-2 w-2 rounded-full bg-[#c2410c] ring-1 ring-[#0c1828]" />
            </span>
          )}
        </span>

        <span className="max-w-[110px] truncate text-white/85 group-hover:text-white">
          {displayName}
        </span>

        <svg
          width="9"
          height="9"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          strokeWidth="2.6"
          strokeLinecap="round"
          strokeLinejoin="round"
          aria-hidden="true"
          className={`text-white/45 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-72 origin-top-right overflow-hidden rounded-2xl border border-[#ede8e3] bg-white text-[#0c1828] shadow-[0_24px_60px_rgba(12,24,40,0.20)]"
          style={{ animation: "page-fade-in 220ms ease both" }}
        >
          {/* Profile header */}
          <div className="border-b border-[#ede8e3] bg-gradient-to-br from-[#fff4f0] via-white 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={44}
                  height={44}
                  className="h-11 w-11 rounded-full object-cover ring-2 ring-white shadow-[0_4px_12px_rgba(12,24,40,0.10)]"
                />
              ) : (
                <span className="flex h-11 w-11 items-center justify-center rounded-full bg-gradient-to-br from-[#c2410c] to-[#d94e22] text-base font-black text-white shadow-[0_4px_14px_rgba(194,65,12,0.40)] ring-2 ring-white">
                  {initial}
                </span>
              )}
              <div className="min-w-0 flex-1">
                <p className="truncate text-sm font-bold leading-tight">
                  {account.name || account.email.split("@")[0]}
                </p>
                <p className="mt-0.5 truncate text-xs text-[#6b7280]">{account.email}</p>
              </div>
            </div>
          </div>

          {/* Menu items with counter badges */}
          <div className="p-2">
            <MenuItem
              href={`${prefix}/nalog`}
              onClose={() => setOpen(false)}
              icon={
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z" />
                  <polyline points="9 22 9 12 15 12 15 22" />
                </svg>
              }
              label={en ? "My account" : "Moj nalog"}
            />
            <MenuItem
              href={`${prefix}/nalog/poruke`}
              onClose={() => setOpen(false)}
              icon={
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" />
                </svg>
              }
              label={en ? "Messages" : "Poruke"}
              badge={unreadMessages > 0 ? unreadMessages : undefined}
              accent={unreadMessages > 0}
            />
            <MenuItem
              href={`${prefix}/favoriti`}
              onClose={() => setOpen(false)}
              icon={
                <svg width="16" height="16" viewBox="0 0 24 24" fill={favCount > 0 ? "currentColor" : "none"} stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78L12 21.23l8.84-8.84a5.5 5.5 0 0 0 0-7.78z" />
                </svg>
              }
              label={en ? "Favorites" : "Favoriti"}
              badge={favCount > 0 ? favCount : undefined}
            />
            <MenuItem
              href={`${prefix}/uporedi`}
              onClose={() => setOpen(false)}
              icon={
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
                  <line x1="6" y1="3" x2="6" y2="15" />
                  <line x1="18" y1="9" x2="18" y2="21" />
                  <line x1="3" y1="9" x2="9" y2="9" />
                  <line x1="15" y1="15" x2="21" y2="15" />
                </svg>
              }
              label={en ? "Compare" : "Uporedi"}
            />
          </div>

          {/* 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="16" height="16" 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
                ? en
                  ? "Signing out…"
                  : "Odjavljujem…"
                : en
                  ? "Sign out"
                  : "Odjavi se"}
            </button>
          </div>
        </div>
      )}
    </div>
  );
}

function MenuItem({
  href,
  icon,
  label,
  badge,
  onClose,
  accent,
}: {
  href: string;
  icon: React.ReactNode;
  label: string;
  badge?: number;
  onClose: () => void;
  accent?: boolean;
}) {
  return (
    <Link
      href={href}
      role="menuitem"
      onClick={onClose}
      className="flex items-center gap-3 rounded-xl px-3 py-2 text-sm font-semibold transition hover:bg-[#fff4f0] hover:text-[#c2410c]"
    >
      <span className={`flex h-7 w-7 items-center justify-center rounded-lg ${accent ? "bg-[#fff4f0] text-[#c2410c]" : "bg-[#faf9f7] text-[#0c1828]"}`}>
        {icon}
      </span>
      <span className="flex-1 truncate">{label}</span>
      {typeof badge === "number" && badge > 0 && (
        <span
          className="inline-flex h-5 min-w-[20px] items-center justify-center rounded-full px-1.5 text-[10px] font-black"
          style={{
            background: accent ? "#c2410c" : "#0c1828",
            color: "white",
          }}
        >
          {badge > 99 ? "99+" : badge}
        </span>
      )}
    </Link>
  );
}
