import { useEffect, useState } from "react";
import { createPortal } from "react-dom";
import {
  ArrowDownLeft,
  ArrowUpRight,
  CheckCircle2,
  ClipboardList,
  Eye,
  EyeOff,
  Gift,
  Loader2,
  LogOut,
  Receipt,
  Send,
  ShoppingBag,
  User,
  Wallet,
  X,
} from "lucide-react";
import { useAccount } from "@/hooks/useAccount";
import { useI18n } from "@/i18n";
import { formatBalance, formatBDT, formatDiamonds } from "@/data/packages";
import { cn } from "@/lib/utils";

type Tab = "profile" | "balance" | "orders" | "requests" | "money" | "bonus";

const inputClass =
  "h-12 w-full rounded-xl border border-border bg-input/40 px-3.5 text-base focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none";

function Empty({ text }: { text: string }) {
  return (
    <p className="rounded-2xl border border-dashed border-border/70 p-6 text-center text-xs text-muted-foreground">
      {text}
    </p>
  );
}

function Row({
  title,
  sub,
  value,
  positive,
}: {
  title: string;
  sub?: string;
  value: string;
  positive?: boolean;
}) {
  return (
    <div className="grid grid-cols-[minmax(0,1fr)_auto] items-center gap-3 rounded-2xl bg-secondary/50 p-3">
      <div className="min-w-0">
        <p className="truncate text-sm font-medium">{title}</p>
        {sub && <p className="truncate text-[11px] text-muted-foreground">{sub}</p>}
      </div>
      <p
        className={cn(
          "shrink-0 text-sm font-semibold tabular-nums",
          positive === undefined ? "" : positive ? "text-primary" : "text-destructive",
        )}
      >
        {value}
      </p>
    </div>
  );
}

function PasswordField({
  value,
  onChange,
  placeholder,
  autoComplete,
}: {
  value: string;
  onChange: (v: string) => void;
  placeholder: string;
  autoComplete: string;
}) {
  const { t } = useI18n();
  const [show, setShow] = useState(false);
  return (
    <div className="relative">
      <input
        type={show ? "text" : "password"}
        required
        minLength={6}
        autoComplete={autoComplete}
        placeholder={placeholder}
        aria-label={placeholder}
        value={value}
        onChange={(e) => onChange(e.target.value)}
        className={cn(inputClass, "pr-12")}
      />
      <button
        type="button"
        onClick={() => setShow(!show)}
        aria-label={t(show ? "auth.hidePass" : "auth.showPass")}
        className="absolute top-1/2 right-2 grid size-9 -translate-y-1/2 place-items-center rounded-lg text-muted-foreground hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none"
      >
        {show ? <EyeOff className="size-4" aria-hidden /> : <Eye className="size-4" aria-hidden />}
      </button>
    </div>
  );
}

function Shell({
  children,
  label,
  onClose,
}: {
  children: React.ReactNode;
  label: string;
  onClose: () => void;
}) {
  const { t } = useI18n();
  const [mounted, setMounted] = useState(false);
  useEffect(() => setMounted(true), []);
  if (!mounted) return null;
  return createPortal(
    <div className="fixed inset-0 z-50 flex items-end justify-center overflow-y-auto bg-background/70 p-0 backdrop-blur-sm sm:items-center sm:p-4">
      <div
        className="panel max-h-[92vh] w-full max-w-md overflow-y-auto rounded-t-3xl p-5 sm:rounded-3xl"
        role="dialog"
        aria-modal="true"
        aria-label={label}
      >
        <div className="mb-4 flex justify-end">
          <button
            type="button"
            onClick={onClose}
            aria-label={t("account.close")}
            className="grid size-9 place-items-center rounded-xl text-muted-foreground hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none"
          >
            <X className="size-4" aria-hidden />
          </button>
        </div>
        {children}
      </div>
    </div>,
    document.body,
  );
}

function AuthPanel({
  onClose,
  onSignedIn,
}: {
  onClose: () => void;
  onSignedIn: () => void;
}) {
  const { t } = useI18n();
  const { signIn, signUp, profile } = useAccount();
  const [mode, setMode] = useState<"in" | "up">("in");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [confirm, setConfirm] = useState("");
  const [fullName, setFullName] = useState("");
  const [referral, setReferral] = useState("FF90");
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [notice, setNotice] = useState<string | null>(null);
  const [created, setCreated] = useState(false);

  function reset() {
    setError(null);
    setNotice(null);
  }

  async function submit(event: React.FormEvent) {
    event.preventDefault();
    if (busy) return;
    reset();
    if (!email.trim()) return setError(t("auth.err.email"));
    if (password.length < 6) return setError(t("auth.err.password"));
    if (mode === "up") {
      if (!fullName.trim()) return setError(t("auth.err.name"));
      if (password !== confirm) return setError(t("auth.err.match"));
    }
    setBusy(true);
    const result =
      mode === "in"
        ? await signIn(email.trim(), password)
        : await signUp(email.trim(), password, fullName, referral);
    setBusy(false);
    if (result === "CONFIRM_EMAIL") {
      setNotice(t("auth.confirm"));
      return;
    }
    if (result) {
      setError(result);
      return;
    }
    if (mode === "up") setCreated(true);
    else onSignedIn();
  }

  if (created) {
    return (
      <Shell label={t("auth.created.title")} onClose={onClose}>
        <div className="space-y-4 text-center">
          <CheckCircle2 className="mx-auto size-12 text-primary" aria-hidden />
          <p className="neon-text font-display text-lg font-bold">{t("auth.created.title")}</p>
          <div className="space-y-2 rounded-2xl bg-secondary/60 p-4 text-left">
            <div className="flex items-center justify-between gap-3">
              <span className="text-xs text-muted-foreground">{t("account.id")}</span>
              <span className="font-display text-sm font-bold">
                {profile?.account_code ?? "—"}
              </span>
            </div>
            <div className="flex items-center justify-between gap-3">
              <span className="text-xs text-muted-foreground">{t("auth.referral")}</span>
              <span className="font-display text-sm font-bold">
                {profile?.referral_code ?? referral}
              </span>
            </div>
            <div className="flex items-center justify-between gap-3">
              <span className="text-xs text-muted-foreground">{t("account.balance")}</span>
              <span className="font-display text-sm font-bold text-primary">
                {formatBalance(Number(profile?.balance ?? 0))}
              </span>
            </div>
          </div>
          <button
            type="button"
            onClick={onClose}
            className="h-12 w-full rounded-xl bg-primary font-display font-semibold text-primary-foreground hover:opacity-90 focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none"
          >
            {t("auth.continue")}
          </button>
        </div>
      </Shell>
    );
  }

  return (
    <Shell label={t(mode === "in" ? "auth.signIn" : "auth.register")} onClose={onClose}>
      <div className="grid grid-cols-2 gap-1 rounded-2xl bg-secondary/60 p-1">
        {(["in", "up"] as const).map((m) => (
          <button
            key={m}
            type="button"
            onClick={() => {
              setMode(m);
              reset();
            }}
            className={cn(
              "h-10 rounded-xl text-xs font-bold tracking-wide uppercase transition-colors",
              mode === m ? "bg-primary/20 text-primary" : "text-muted-foreground",
            )}
          >
            {t(m === "in" ? "auth.signIn" : "auth.register")}
          </button>
        ))}
      </div>

      <div className="mt-4 mb-3">
        <p className="font-display text-lg font-bold">
          {t(mode === "in" ? "auth.welcome" : "auth.register")}
        </p>
        <p className="text-xs text-muted-foreground">
          {t(mode === "in" ? "auth.welcomeSub" : "auth.registerSub")}
        </p>
      </div>

      <form onSubmit={submit} className="space-y-3" noValidate>
        {mode === "up" && (
          <input
            value={fullName}
            onChange={(e) => setFullName(e.target.value)}
            placeholder={t("auth.name")}
            aria-label={t("auth.name")}
            autoComplete="name"
            className={inputClass}
          />
        )}
        <input
          type="email"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          placeholder={t("auth.identifier")}
          aria-label={t("auth.identifier")}
          autoComplete="email"
          className={inputClass}
        />
        <PasswordField
          value={password}
          onChange={setPassword}
          placeholder={t(mode === "in" ? "auth.password" : "auth.newPassword")}
          autoComplete={mode === "in" ? "current-password" : "new-password"}
        />
        {mode === "up" && (
          <>
            <PasswordField
              value={confirm}
              onChange={setConfirm}
              placeholder={t("auth.confirmPassword")}
              autoComplete="new-password"
            />
            <input
              value={referral}
              onChange={(e) => setReferral(e.target.value)}
              placeholder={t("auth.referral")}
              aria-label={t("auth.referral")}
              className={inputClass}
            />
          </>
        )}
        {error && <p className="text-xs text-destructive">{error}</p>}
        {notice && <p className="text-xs text-primary">{notice}</p>}
        <button
          type="submit"
          disabled={busy}
          className="flex h-12 w-full items-center justify-center gap-2 rounded-xl bg-primary font-display font-semibold tracking-wide text-primary-foreground uppercase hover:opacity-90 focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none disabled:opacity-60"
        >
          {busy && <Loader2 className="size-4 animate-spin" aria-hidden />}
          {t(mode === "in" ? "auth.signIn" : "auth.register")}
        </button>
      </form>

      <button
        type="button"
        onClick={() => {
          setMode(mode === "in" ? "up" : "in");
          reset();
        }}
        className="mt-3 w-full text-center text-xs text-primary underline-offset-4 hover:underline"
      >
        {t(mode === "in" ? "auth.toSignUp" : "auth.toSignIn")}
      </button>
      <p className="mt-3 text-center text-[11px] text-muted-foreground">{t("account.tg.hint")}</p>
    </Shell>
  );
}

function TelegramCard() {
  const { t } = useI18n();
  const { profile, saveTelegram } = useAccount();
  const [value, setValue] = useState(profile?.telegram_username ?? "");
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [saved, setSaved] = useState(false);

  async function save() {
    if (busy || value.trim().length < 3) return;
    setBusy(true);
    setError(null);
    const result = await saveTelegram(value);
    if (result) setError(t("account.tg.taken"));
    else setSaved(true);
    setBusy(false);
  }

  return (
    <div className="space-y-2">
      <p className="text-xs text-muted-foreground">{t("account.tg.hint")}</p>
      <div className="grid grid-cols-[minmax(0,1fr)_auto] gap-2">
        <input
          value={value}
          onChange={(e) => {
            setValue(e.target.value);
            setSaved(false);
          }}
          placeholder="@username"
          aria-label={t("account.tg.label")}
          className="h-11 w-full rounded-xl border border-border bg-input/40 px-3 text-sm focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none"
        />
        <button
          type="button"
          onClick={save}
          disabled={busy}
          className="flex h-11 shrink-0 items-center gap-1.5 rounded-xl bg-primary px-3 text-sm font-semibold text-primary-foreground hover:opacity-90 disabled:opacity-60"
        >
          {busy ? (
            <Loader2 className="size-4 animate-spin" aria-hidden />
          ) : (
            <Send className="size-4" aria-hidden />
          )}
          {t("account.tg.save")}
        </button>
      </div>
      {error && <p className="text-xs text-destructive">{error}</p>}
      {saved && <p className="text-xs text-primary">{t("account.tg.saved")}</p>}
      <p className="text-[11px] text-muted-foreground">
        {profile?.telegram_username
          ? `${t("account.tg.connected")} @${profile.telegram_username}`
          : t("account.tg.notConnected")}
      </p>
    </div>
  );
}

function OrderCard({
  order,
  dateFmt,
}: {
  order: {
    id: string;
    order_code: string;
    diamond_amount: number;
    price: number;
    free_fire_uid: string;
    payment_method: string;
    transaction_id: string;
    status: string;
    created_at: string;
  };
  dateFmt: (iso: string) => string;
}) {
  const { t } = useI18n();
  return (
    <div className="rounded-2xl bg-secondary/50 p-3">
      <div className="flex items-center justify-between gap-3">
        <p className="truncate font-display text-sm font-bold">{order.order_code}</p>
        <span className="shrink-0 rounded-full border border-primary/40 px-2 py-0.5 text-[10px] font-semibold text-primary">
          {t(`account.status.${order.status}`)}
        </span>
      </div>
      <p className="mt-1 text-xs text-muted-foreground">
        {formatDiamonds(order.diamond_amount)} {t("packs.diamonds")} ·{" "}
        {formatBDT(Number(order.price))} · {order.payment_method}
      </p>
      <p className="text-xs break-words text-muted-foreground">
        {t("summary.uid")}: <span className="tabular-nums">{order.free_fire_uid}</span> ·{" "}
        {t("field.trx")}: {order.transaction_id}
      </p>
      <p className="text-[11px] text-muted-foreground">{dateFmt(order.created_at)}</p>
    </div>
  );
}

function Stat({ label, value }: { label: string; value: string }) {
  return (
    <div className="rounded-2xl bg-secondary/50 p-3">
      <p className="text-[10px] tracking-wide text-muted-foreground uppercase">{label}</p>
      <p className="font-display text-base font-bold tabular-nums">{value}</p>
    </div>
  );
}

export function AccountPanel({ onClose }: { onClose: () => void }) {
  const { t, lang } = useI18n();
  const { session, profile, transactions, orders, bonuses, signOut } = useAccount();
  const [tab, setTab] = useState<Tab>("profile");

  const dateFmt = (iso: string) =>
    new Date(iso).toLocaleDateString(lang === "bn" ? "bn-BD" : "en-GB", {
      day: "2-digit",
      month: "short",
      year: "numeric",
    });

  const tabs: Array<{ id: Tab; label: string; icon: typeof User }> = [
    { id: "profile", label: t("account.tab.profile"), icon: User },
    { id: "balance", label: t("account.tab.balance"), icon: Wallet },
    { id: "orders", label: t("account.tab.orders"), icon: ShoppingBag },
    { id: "requests", label: t("account.tab.requests"), icon: ClipboardList },
    { id: "money", label: t("account.tab.money"), icon: ArrowUpRight },
    { id: "bonus", label: t("account.tab.bonus"), icon: Gift },
  ];

  const deposits = transactions.filter((x) => Number(x.amount) >= 0);
  const spends = transactions.filter((x) => Number(x.amount) < 0);
  const requests = orders.filter((o) => o.status === "PENDING" || o.status === "PROCESSING");
  const completed = orders.filter((o) => o.status === "COMPLETED");
  const totalSpending = orders.reduce((sum, o) => sum + Number(o.price), 0);
  const totalDeposits = deposits.reduce((sum, x) => sum + Number(x.amount), 0);
  const bonusTotal = bonuses.reduce((sum, b) => sum + Number(b.reward_amount), 0);

  return (
    <Shell label={t("account.title")} onClose={onClose}>
      <div className="grid grid-cols-[auto_minmax(0,1fr)] items-center gap-3">
        <span className="grid size-12 place-items-center rounded-full border border-primary/40 bg-secondary/60 text-primary">
          <User className="size-6" aria-hidden />
        </span>
        <div className="min-w-0">
          <p className="truncate font-display text-base font-bold">
            {profile?.display_name ?? session?.user.email ?? t("account.guest")}
          </p>
          <p className="truncate text-[11px] text-muted-foreground">
            {profile?.account_code ?? "—"} ·{" "}
            {profile?.telegram_username
              ? `@${profile.telegram_username}`
              : t("account.tg.notConnected")}
          </p>
        </div>
      </div>

      <div className="mt-4 rounded-2xl bg-secondary/60 p-4">
        <p className="text-[11px] tracking-wide text-muted-foreground uppercase">
          {t("account.balance")}
        </p>
        <p className="neon-text font-display text-3xl font-bold">
          {formatBalance(Number(profile?.balance ?? 0))}
        </p>
      </div>

      <div className="mt-3 grid grid-cols-2 gap-2 sm:grid-cols-3">
        <Stat label={t("account.stat.orders")} value={String(orders.length)} />
        <Stat label={t("account.stat.pending")} value={String(requests.length)} />
        <Stat label={t("account.stat.completed")} value={String(completed.length)} />
        <Stat label={t("account.stat.spending")} value={formatBDT(totalSpending)} />
        <Stat label={t("account.stat.deposits")} value={formatBDT(totalDeposits)} />
        <Stat label={t("account.stat.bonus")} value={formatBDT(bonusTotal)} />
        <Stat label={t("account.stat.transactions")} value={String(transactions.length)} />
      </div>

      <div className="mt-4 flex gap-1.5 overflow-x-auto pb-1">
        {tabs.map(({ id, label, icon: Icon }) => (
          <button
            key={id}
            type="button"
            onClick={() => setTab(id)}
            className={cn(
              "flex shrink-0 items-center gap-1.5 rounded-full border px-3 py-1.5 text-xs font-semibold transition-colors",
              tab === id
                ? "border-primary/60 bg-primary/15 text-primary"
                : "border-border/70 text-muted-foreground hover:text-foreground",
            )}
          >
            <Icon className="size-3.5" aria-hidden /> {label}
          </button>
        ))}
      </div>

      <div className="mt-4 space-y-2">
        {tab === "profile" && (
          <div className="space-y-4">
            <div className="space-y-1 rounded-2xl bg-secondary/40 p-3 text-xs">
              <p className="mb-1 text-[10px] tracking-wide text-muted-foreground uppercase">
                {t("account.details")}
              </p>
              <div className="flex justify-between gap-3">
                <span className="text-muted-foreground">{t("account.fullName")}</span>
                <span className="truncate">{profile?.display_name ?? t("account.guest")}</span>
              </div>
              <div className="flex justify-between gap-3">
                <span className="text-muted-foreground">{t("account.id")}</span>
                <span className="truncate">{profile?.account_code ?? "—"}</span>
              </div>
              <div className="flex justify-between gap-3">
                <span className="text-muted-foreground">{t("auth.identifier")}</span>
                <span className="truncate">{session?.user.email ?? t("account.guest")}</span>
              </div>
              <div className="flex justify-between gap-3">
                <span className="text-muted-foreground">{t("account.regDate")}</span>
                <span>{session?.user.created_at ? dateFmt(session.user.created_at) : "—"}</span>
              </div>
              <div className="flex justify-between gap-3">
                <span className="text-muted-foreground">{t("account.lastLogin")}</span>
                <span>
                  {session?.user.last_sign_in_at ? dateFmt(session.user.last_sign_in_at) : "—"}
                </span>
              </div>
              <div className="flex justify-between gap-3">
                <span className="text-muted-foreground">{t("auth.referral")}</span>
                <span>{profile?.referral_code ?? "FF90"}</span>
              </div>
              <div className="flex justify-between gap-3">
                <span className="text-muted-foreground">{t("account.tg.label")}</span>
                <span className="truncate">
                  {profile?.telegram_username
                    ? `@${profile.telegram_username}`
                    : t("account.tg.notConnected")}
                </span>
              </div>
            </div>
            <TelegramCard />
          </div>
        )}

        {tab === "balance" &&
          (transactions.length === 0 ? (
            <Empty text={t("account.empty.tx")} />
          ) : (
            transactions.map((x) => (
              <Row
                key={x.id}
                title={t(`account.type.${x.type}`)}
                sub={`${dateFmt(x.created_at)} · ${t("account.ledger.before")} ${formatBDT(
                  Number(x.balance_before),
                )} → ${t("account.ledger.after")} ${formatBDT(Number(x.balance_after))}`}
                value={`${Number(x.amount) >= 0 ? "+" : "−"}${formatBDT(Math.abs(Number(x.amount)))}`}
                positive={Number(x.amount) >= 0}
              />
            ))
          ))}

        {tab === "orders" &&
          (orders.length === 0 ? (
            <Empty text={t("account.empty.orders")} />
          ) : (
            orders.map((o) => <OrderCard key={o.id} order={o} dateFmt={dateFmt} />)
          ))}

        {tab === "requests" &&
          (requests.length === 0 ? (
            <Empty text={t("account.empty.requests")} />
          ) : (
            requests.map((o) => <OrderCard key={o.id} order={o} dateFmt={dateFmt} />)
          ))}

        {tab === "money" && (
          <div className="space-y-4">
            <div className="space-y-2">
              <p className="flex items-center gap-1.5 text-xs font-semibold text-muted-foreground">
                <ArrowDownLeft className="size-3.5 text-primary" aria-hidden />{" "}
                {t("account.deposits")}
              </p>
              {deposits.length === 0 ? (
                <Empty text={t("account.empty.deposits")} />
              ) : (
                deposits.map((x) => (
                  <Row
                    key={x.id}
                    title={t(`account.type.${x.type}`)}
                    sub={dateFmt(x.created_at)}
                    value={`+${formatBDT(Number(x.amount))}`}
                    positive
                  />
                ))
              )}
            </div>
            <div className="space-y-2">
              <p className="flex items-center gap-1.5 text-xs font-semibold text-muted-foreground">
                <ArrowUpRight className="size-3.5" aria-hidden /> {t("account.spending")}
              </p>
              {spends.length === 0 ? (
                <Empty text={t("account.empty.spending")} />
              ) : (
                spends.map((x) => (
                  <Row
                    key={x.id}
                    title={t(`account.type.${x.type}`)}
                    sub={dateFmt(x.created_at)}
                    value={`−${formatBDT(Math.abs(Number(x.amount)))}`}
                    positive={false}
                  />
                ))
              )}
            </div>
            <div className="space-y-2">
              <p className="flex items-center gap-1.5 text-xs font-semibold text-muted-foreground">
                <Receipt className="size-3.5" aria-hidden /> {t("account.tab.orders")}
              </p>
              {orders.length === 0 ? (
                <Empty text={t("account.empty.orders")} />
              ) : (
                orders.map((o) => (
                  <Row
                    key={o.id}
                    title={o.order_code}
                    sub={`${dateFmt(o.created_at)} · ${t(`account.status.${o.status}`)}`}
                    value={`−${formatBDT(Number(o.price))}`}
                    positive={false}
                  />
                ))
              )}
            </div>
          </div>
        )}

        {tab === "bonus" &&
          (bonuses.length === 0 ? (
            <Empty text={t("account.empty.bonus")} />
          ) : (
            bonuses.map((b) => (
              <Row
                key={b.id}
                title={`${t("account.type.DAILY_BONUS")} · ${t("account.status.CREDITED")}`}
                sub={`${dateFmt(b.created_at)} · ${t("account.bonus.txid")}: ${b.id.slice(0, 8).toUpperCase()}`}
                value={`+${formatBDT(Number(b.reward_amount))}`}
                positive
              />
            ))
          ))}
      </div>

      <button
        type="button"
        onClick={async () => {
          await signOut();
          onClose();
        }}
        className="mt-5 flex h-11 w-full items-center justify-center gap-2 rounded-xl border border-border/70 text-sm font-semibold tracking-wide text-muted-foreground uppercase hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none"
      >
        <LogOut className="size-4" aria-hidden /> {t("auth.signOut")}
      </button>
    </Shell>
  );
}

export function AccountButton() {
  const { t } = useI18n();
  const { isAuthed, ready, profile } = useAccount();
  const [view, setView] = useState<"auth" | "account" | null>(null);

  return (
    <>
      {ready && isAuthed && (
        <button
          type="button"
          onClick={() => setView("account")}
          aria-label={t("account.balanceAria")}
          className="flex h-9 shrink-0 items-center gap-1.5 rounded-full border border-primary/40 bg-secondary/50 px-2.5 text-xs font-semibold tabular-nums text-primary shadow-[0_0_12px_-4px_hsl(var(--primary)/0.6)] backdrop-blur-md transition-all hover:bg-primary/10 focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none"
        >
          <Wallet className="size-3.5" aria-hidden />
          {formatBalance(Number(profile?.balance ?? 0))}
        </button>
      )}
      <button
        type="button"
        onClick={() => setView(isAuthed ? "account" : "auth")}
        aria-label={t("account.aria")}
        className="relative grid size-10 shrink-0 place-items-center rounded-full border border-primary/40 bg-secondary/50 text-primary shadow-[0_0_12px_-4px_hsl(var(--primary)/0.6)] backdrop-blur-md transition-all hover:bg-primary/10 hover:shadow-[0_0_18px_-2px_hsl(var(--primary)/0.8)] focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none"
      >
        <User className="size-5" aria-hidden />
        {ready && isAuthed && (
          <span
            className="absolute -top-0.5 -right-0.5 size-2.5 rounded-full border border-background bg-primary"
            aria-hidden
          />
        )}
      </button>
      {view === "account" && <AccountPanel onClose={() => setView(null)} />}
      {view === "auth" && (
        <AuthPanel onClose={() => setView(null)} onSignedIn={() => setView("account")} />
      )}
    </>
  );
}
