import { base64UrlDecodeStr } from '@/lib/encoding';
import { captureCaught } from '@/lib/observability';

/**
 * Re-parses the `mh` cookie and applies it to `window.__MH__` and
 * `document.documentElement.dataset`. Used by CrossTabRefresher so other
 * tabs pick up the new auth state without a full page reload.
 *
 * Mirrors the inline script in MhBootstrap.astro — keep in sync.
 */

export interface MhPayload {
  n?: string;
  i?: string;
  a?: 0 | 1;
  v?: 0 | 1;
  af?: 0 | 1;
  c?: number;
  e?: number;
  t?: string;
  ph?: string;
}

declare global {
  interface Window {
    __MH__?: MhPayload;
  }
}

/**
 * Parse a raw base64url `mh` cookie value into MhPayload.
 * Returns null if the value is absent, invalid, or expired.
 *
 * Canonical implementation. Consumed by: useAuthHint, lib/csrf.ts,
 * lib/hooks/usePersonalization.ts, CrossTabRefresher, AuthGateModal.
 *
 * MhBootstrap.astro keeps an intentional copy (inline <script> cannot import modules).
 */
export function parseMhCookieRaw(raw: string): MhPayload | null {
  if (!raw) return null;
  try {
    const p = JSON.parse(base64UrlDecodeStr(raw)) as MhPayload;
    if (p.e && p.e * 1000 < Date.now()) return null;
    return p;
  } catch (err) {
    captureCaught(err, {
      scope: 'lib.mh-cookie.parseMhCookieRaw',
      severity: 'info',
    });
    return null;
  }
}

export function applyMhCookie(): void {
  if (typeof document === 'undefined') return;
  try {
    const m = document.cookie.match(/(?:^|;\s*)mh=([^;]+)/);
    const raw = m?.[1];
    if (!raw) {
      document.documentElement.dataset.auth = 'guest';
      document.documentElement.dataset.affiliate = '0';
      window.__MH__ = undefined;
      return;
    }
    const p = JSON.parse(base64UrlDecodeStr(raw)) as MhPayload;
    if (p.e && p.e * 1000 < Date.now()) {
      document.documentElement.dataset.auth = 'guest';
      document.documentElement.dataset.affiliate = '0';
      window.__MH__ = undefined;
      return;
    }
    const d = document.documentElement.dataset;
    d.auth = 'user';
    d.name = p.n ?? '';
    d.initials = p.i ?? '';
    d.admin = p.a ? '1' : '0';
    d.vendor = p.v ? '1' : '0';
    d.affiliate = p.af ? '1' : '0';
    d.cart = String(p.c ?? 0);
    window.__MH__ = p;
  } catch (err) {
    captureCaught(err, {
      scope: 'lib.mh-cookie.applyMhCookie',
      severity: 'info',
    });
    document.documentElement.dataset.auth = 'guest';
    document.documentElement.dataset.affiliate = '0';
    window.__MH__ = undefined;
  }
}
