"use client";

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

import { safeNextUrl } from "@/lib/auth-navigation";
import { getAccessToken, getMe, logoutLocal, type MeUser } from "@/lib/web-auth-client";

export function SiteHeaderSession() {
  const pathname = usePathname() || "/";
  const router = useRouter();
  /** `undefined` = chưa đọc token sau mount (tránh đọc localStorage trong render — không gây lệch hydration). */
  const [me, setMe] = useState<MeUser | null | undefined>(undefined);

  useEffect(() => {
    let alive = true;
    (async () => {
      const t = getAccessToken();
      if (!t) {
        if (alive) setMe(null);
        return;
      }
      try {
        const { user } = await getMe();
        if (alive) setMe(user);
      } catch {
        if (alive) setMe(null);
      }
    })();
    return () => {
      alive = false;
    };
  }, [pathname]);

  if (me === undefined) {
    return <span className="hidden w-16 shrink-0 sm:inline-block" aria-hidden />;
  }

  if (!me) {
    const next = encodeURIComponent(safeNextUrl(pathname));
    return (
      <Link
        href={`/login?next=${next}`}
        className="ctkp-nav-item shrink-0 text-[12px] sm:text-[13px]"
      >
        Đăng nhập
      </Link>
    );
  }

  const label = me.name?.trim() || me.email;
  const needPhone = me.requiresPhoneVerification;
  const next = encodeURIComponent(safeNextUrl(pathname));

  function onLogoutLocal() {
    logoutLocal();
    setMe(null);
    router.replace("/login");
  }

  return (
    <div className="flex max-w-[min(100%,22rem)] shrink-0 flex-col items-end gap-1 text-right sm:flex-row sm:items-center sm:gap-2">
      <span className="max-w-[10rem] truncate text-[11px] text-stone-400 sm:max-w-[12rem] sm:text-xs" title={me.email}>
        {label}
      </span>
      {!needPhone ? (
        <Link href="/account" className="ctkp-nav-item shrink-0 whitespace-nowrap text-[12px] sm:text-[13px]">
          Tài khoản
        </Link>
      ) : null}
      {needPhone ? (
        <Link
          href={`/verify-phone?next=${next}`}
          className="whitespace-nowrap rounded-md border border-amber-800/35 bg-amber-950/25 px-2 py-0.5 text-[10px] text-amber-200/90 transition hover:border-amber-600/40 hover:bg-amber-950/40 sm:text-[11px]"
        >
          Xác minh SĐT
        </Link>
      ) : null}
      <button
        type="button"
        onClick={onLogoutLocal}
        className="whitespace-nowrap text-[10px] text-stone-500 underline-offset-2 hover:text-stone-400 hover:underline sm:text-[11px]"
      >
        Đăng xuất
      </button>
    </div>
  );
}
