/* AuditData.jsx — SSOT constants + helpers for the Audit & Verification surface.
   Loaded BEFORE AuditSurface.jsx. Exposes window.WPSBAudit.

   READ-ONLY consumer of the LIVE audit engine (api v1.100.x):
     GET  /audit/reports          → this account's reports (account-scoped server-side)
     GET  /audit/reports/:id       → one report { report, sections[], attestation,
                                      score_label, disclaimer }
     POST /audit/migration-crosscheck → enqueue a READ-ONLY migration cross-check
                                      (spine-routed; never a write to a customer site)

   INVARIANT (master §6 #34 / Build-C guardrail 9): the app NEVER computes RAG
   status. Every status (report.status, section.rollup.status, finding.status) is
   the API rollup, rendered VERBATIM. This file maps a status string to a COLOR +
   LABEL only — it does not derive status from severity or counts. No parallel
   findings model.

   Light-mode tokens only — semantic CSS variables, never hardcoded hex (master §3 #5). */
(function () {
  'use strict';

  /* Base URL + token resolver — match the CANONICAL pattern the core authed
     surfaces (BillingInfo/FileManager/GeoVisibility/ScanHistory) use: a HARDCODED
     'https://api.wpsitebeam.io' fallback (neither window.WPSB_CONFIG.RAILWAY_URL
     nor window.WPSBD.apiBase is reliably set at runtime — the prior ''/null
     fallback sent the fetch to the app's OWN origin → Vercel 404). */
  function apiBase() {
    return (window.WPSBD && window.WPSBD.apiBase)
      || (window.WPSB_CONFIG && window.WPSB_CONFIG.RAILWAY_URL)
      || window.RAILWAY_URL
      || 'https://api.wpsitebeam.io';
  }
  /* Both bridges resolve window.currentToken; prefer WPSBD.getToken (the core-
     surface canonical) and fall back to WPSB.getToken. Null only when the token
     genuinely has not hydrated yet (the surface retries — see AuditSurface). */
  function authToken() {
    if (typeof window === 'undefined') return null;
    if (window.WPSBD && window.WPSBD.getToken) { var t = window.WPSBD.getToken(); if (t) return t; }
    if (window.WPSB && window.WPSB.getToken)   { var u = window.WPSB.getToken();   if (u) return u; }
    return null;
  }
  function switchTab(tab) {
    if (window.WPSBD && window.WPSBD.switchTab) window.WPSBD.switchTab(tab);
  }
  function fmtDateTime(iso) {
    if (!iso) return null;
    try { return new Date(iso).toLocaleString(undefined, { year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }); }
    catch (_) { return null; }
  }
  function prettyHost(u) {
    var raw = String(u || '');
    try { return new URL(/^https?:\/\//.test(raw) ? raw : 'https://' + raw).hostname.replace(/^www\./, ''); }
    catch (_) { return raw.replace(/^https?:\/\//, '').replace(/^www\./, '').replace(/[\/?#].*$/, ''); }
  }

  /* RAG status meta — COLORS + LABELS ONLY (the status itself always comes from the
     API). All v2 tokens (theme-flip for free): colored states use the semantic
     `--*-dim` tints; Gray uses a NEUTRAL surface (`--surface-3`) so it stays
     visually distinct from green/yellow/red AND from an empty card, and reads
     correctly in BOTH light and dark (the prior rgba(0,0,0,.15) was a black overlay
     that broke light mode). Borders use the matching `--*-dim` token (not a raw rgba). */
  var RAG_META = {
    green:  { color: 'var(--green)', bg: 'var(--green-dim)', border: 'var(--green-dim)', label: 'Pass' },
    yellow: { color: 'var(--warn)',  bg: 'var(--warn-dim)',  border: 'var(--warn-dim)',  label: 'Attention' },
    red:    { color: 'var(--red)',   bg: 'var(--red-dim)',   border: 'var(--red-dim)',   label: 'Issue' },
    gray:   { color: 'var(--dim)',   bg: 'var(--surface-3)', border: 'var(--border)',    label: 'Not measured' },
  };
  function ragMeta(s) { return RAG_META[String(s || '').toLowerCase()] || RAG_META.gray; }

  /* Section display labels + canonical order (the 8 §4 migration-crosscheck
     sections). An unknown section key falls through to a humanized label so a
     future server-side section can't blank the accordion. */
  var SECTION_META = {
    url_parity:            { label: 'URL parity & redirect map',     order: 1 },
    redirect_verification: { label: 'Redirect verification',         order: 2 },
    seo_parity:            { label: 'On-page SEO parity',            order: 3 },
    schema_parity:         { label: 'Schema parity',                 order: 4 },
    indexability:          { label: 'Indexability & launch-blockers', order: 5 },
    links_assets:          { label: 'Links & assets',               order: 6 },
    migration_preflight:   { label: 'Migration preflight',           order: 7 },
    manual_augment:        { label: 'Manual augment',                order: 8 },
  };
  function sectionLabel(k) { return (SECTION_META[k] && SECTION_META[k].label) || String(k || '').replace(/_/g, ' ').replace(/\b\w/g, function (c) { return c.toUpperCase(); }); }
  function sectionOrder(k) { return (SECTION_META[k] && SECTION_META[k].order) || 99; }

  /* Mode display label. */
  function modeLabel(m) {
    if (m === 'migration_crosscheck') return 'Migration Cross-Check';
    return String(m || '').replace(/_/g, ' ');
  }

  window.WPSBAudit = {
    apiBase: apiBase, authToken: authToken, switchTab: switchTab,
    fmtDateTime: fmtDateTime, prettyHost: prettyHost,
    RAG_META: RAG_META, ragMeta: ragMeta,
    SECTION_META: SECTION_META, sectionLabel: sectionLabel, sectionOrder: sectionOrder,
    modeLabel: modeLabel,
  };
})();
