"use client";

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

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

/**
 * Header pill that shows either:
 *   • a "Prijava" link when the visitor is anonymous, or
 *   • the visitor's avatar/initials linked to /nalog when signed in.
 *
 * Hydrated client-side via `/api/visitor-auth/me` so we don't have to
 * convert the entire `Header.tsx` (a client component) into a server
 * shell. The `me` endpoint is cheap (single indexed lookup).
 */
export function VisitorAccountBadge({ prefix }: { prefix: string }) {
  const [account, setAccount] = useState<Account | null>(null);
  const [hydrated, setHydrated] = useState(false);

  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) return;
        setHydrated(true);
      });
    return () => {
      cancelled = true;
    };
  }, []);

  if (!hydrated) {
    // Reserve space — avoids layout shift when account loads.
    return <div className="h-10 w-10 shrink-0" aria-hidden="true" />;
  }

  if (!account) {
    return (
      <Link
        href={`${prefix}/prijavi-se`}
        className="hidden h-10 items-center gap-1.5 rounded-full border border-border bg-white px-3.5 text-sm font-semibold text-foreground transition hover:border-primary/30 hover:bg-[#fff4f0] hover:text-primary md:inline-flex"
      >
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
          <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>
        Prijava
      </Link>
    );
  }

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

  return (
    <Link
      href={`${prefix}/nalog`}
      title={`Moj nalog (${account.email})`}
      className="hidden h-10 items-center gap-2 rounded-full border border-border bg-white pl-1.5 pr-3.5 text-sm font-semibold text-foreground transition hover:border-primary/30 hover:bg-[#fff4f0] hover:text-primary 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-[#c2410c] text-xs font-black text-white">
          {initial}
        </span>
      )}
      <span className="max-w-[100px] truncate text-xs">
        {account.name?.split(" ")[0] || "Nalog"}
      </span>
    </Link>
  );
}
