import { useSyncExternalStore } from 'react';
import { parseMhCookieRaw } from '@/lib/mh-cookie';
import { formatPhoneHintLabel } from '@/lib/phone.js';

export interface AuthHint {
  loggedIn: boolean;
  displayName?: string;
  initials?: string;
  isAdmin?: boolean;
  isVendor?: boolean;
  isAffiliate?: boolean;
  cartCount?: number;
  csrf?: string;
  /** Last 3 digits of phone — display hint only. Use phoneHintLabel for chrome display. */
  phoneHint?: string;
  /** Canonical masked phone label (XXX-XXXX-{hint}) via formatPhoneHintLabel. */
  phoneHintLabel?: string;
}

// Memoized by raw cookie value — same raw string = same object reference = no spurious re-renders.
let _lastRaw = '';
let _cache: AuthHint = { loggedIn: false };

function parseMhCookie(): AuthHint {
  if (typeof document === 'undefined') return _cache;
  const raw = document.cookie.match(/(?:^|;\s*)mh=([^;]+)/)?.[1] ?? '';
  if (raw === _lastRaw) return _cache;
  _lastRaw = raw;
  if (!raw) {
    _cache = { loggedIn: false };
    return _cache;
  }
  const p = parseMhCookieRaw(raw);
  if (!p) {
    _cache = { loggedIn: false };
    return _cache;
  }
  _cache = {
    loggedIn: true,
    displayName: p.n || undefined,
    initials: p.i,
    isAdmin: p.a === 1,
    isVendor: p.v === 1,
    isAffiliate: p.af === 1,
    cartCount: p.c,
    csrf: p.t,
    phoneHint: p.ph ?? undefined,
    phoneHintLabel: p.ph ? formatPhoneHintLabel(p.ph) : undefined,
  };
  return _cache;
}

function subscribe(cb: () => void): () => void {
  if (typeof window === 'undefined') return () => {};
  window.addEventListener('mh:changed', cb);
  return () => window.removeEventListener('mh:changed', cb);
}

const SERVER_SNAPSHOT: AuthHint = { loggedIn: false };

export function useAuthHint(): AuthHint {
  return useSyncExternalStore(subscribe, parseMhCookie, () => SERVER_SNAPSHOT);
}
