/* WPSiteBeam — Site content classification (lane BUILD-1016-S2E-R1, PLAN-1016-AG slice S2, OL-4868)
   v1.0.0.0.0 — 2026-10-17

   Authority, verbatim: R25 and the S2E reissue rulings — "Jordan's ruling, 2026-10-16 (on Chat's
   recommendation)". Jordan: "Yes to all three." (1) the Site settings control and the Sites badge
   ship with the api in one visit; (2) clearing shows the attestation text `clear-not-regulated-v1`
   verbatim with an unchecked checkbox; (3) setters are the site's own agency roles: owner any value,
   dev any value except "not regulated", member read-only.

   ONE module, registered as window.WPSB.siteClassification (module-per-capability):
     VALUES, labelFor, consequenceFor, badgeFor   — pure; the harness runs them from this file
     Badge                                         — the Sites list/grid badge
     Control                                       — the Site settings control (Sites panel)
     useAll                                        — one GET /site-classifications for the Sites page

   ⛔ It never says "compliant" or "verified": the classification is a declaration (R-CONFORMPROOF).
   ⛔ Fail closed in the UI too: while the role or the classification is unknown, the control is
      read-only and the badge reads "Not classified — review required". The server is the boundary
      (PUT /sites/:id/classification re-checks role, attestation and note); this file mirrors it.

   Standards: React.createElement (no JSX); ASCII source; CSS variables only; logical properties
   (RTL); 44px targets; every string through tx() with keys in design/i18n/_build.py. Built to target
   WCAG 2.2 Level AA: labelled select/textarea/checkbox, visible focus (browser default kept), an
   aria-live region for save results, role="alert" for errors, and the attestation text tied to its
   checkbox with aria-describedby. */
(function () {
  'use strict';
  var h = React.createElement;
  var tx = function (k, v, f) { return (window.WPSB && window.WPSB.t) ? window.WPSB.t(k, v, f) : (f != null ? f : k); };

  var VALUES = ['unclassified', 'municipal_public_sector', 'firearms', 'pharmacy', 'cannabis', 'legal_sensitive', 'other_regulated', 'not_regulated'];
  var CLEARED = 'not_regulated';
  var ATTESTATION_VERSION = 'clear-not-regulated-v1';
  var NOTE_MAX = 1000;
  var LABEL_FALLBACK = {
    unclassified: 'Not classified',
    municipal_public_sector: 'Municipal / public sector',
    firearms: 'Firearms',
    pharmacy: 'Pharmacy',
    cannabis: 'Cannabis',
    legal_sensitive: 'Legal-sensitive',
    other_regulated: 'Other regulated',
    not_regulated: 'Not regulated'
  };
  var CONSEQUENCE_FALLBACK = {
    unclassified: 'Not classified yet. Approved content still goes through the review step before it is published to this site.',
    municipal_public_sector: 'Municipal or public-sector content. Approved content goes through the review step before it is published to this site.',
    firearms: 'Regulated content. Approved content goes through the review step before it is published to this site.',
    pharmacy: 'Regulated content. Approved content goes through the review step before it is published to this site.',
    cannabis: 'Regulated content. Approved content goes through the review step before it is published to this site.',
    legal_sensitive: 'Legal-sensitive content. Approved content goes through the review step before it is published to this site.',
    other_regulated: 'Other regulated content (describe it in the note). Approved content goes through the review step before it is published to this site.',
    not_regulated: 'Cleared. Approved content is published to this site without the extra review step.'
  };
  var ATTESTATION_FALLBACK = 'I confirm that this site does not publish regulated or public-sector content, such as municipal or government information, firearms, pharmacy, cannabis, or legal-sensitive content. Clearing this removes the review step before approved content is published to this site. I am responsible for this declaration, and I can change it back at any time.';

  function norm(v) { return VALUES.indexOf(v) >= 0 ? v : 'unclassified'; }
  function labelFor(v) { v = norm(v); return tx('page.sites.cls.value.' + v, null, LABEL_FALLBACK[v]); }
  function consequenceFor(v) { v = norm(v); return tx('page.sites.cls.consequence.' + v, null, CONSEQUENCE_FALLBACK[v]); }
  function attestationText() { return tx('page.sites.cls.attestation.' + ATTESTATION_VERSION.replace(/-/g, '_'), null, ATTESTATION_FALLBACK); }
  /* tone: 'warn' (review required) | 'ok' (cleared). Unknown input reads review-gated. */
  function badgeFor(v) {
    v = norm(v);
    if (v === CLEARED) return { tone: 'ok', text: tx('page.sites.cls.badge.cleared', null, 'Cleared: not regulated') };
    if (v === 'unclassified') return { tone: 'warn', text: tx('page.sites.cls.badge.unclassified', null, 'Not classified — review required') };
    return { tone: 'warn', text: tx('page.sites.cls.badge.review', { value: labelFor(v) }, 'Review required — ' + labelFor(v)) };
  }
  /* What the caller's agency role may pick (mirror of the api; the api is the boundary). */
  function optionsFor(role) {
    if (role === 'owner') return VALUES.slice();
    if (role === 'dev') return VALUES.filter(function (v) { return v !== CLEARED; });
    return [];
  }

  var RAILWAY_URL = (window.WPSB_CONFIG && window.WPSB_CONFIG.RAILWAY_URL) || 'https://wpsitebeam-railway-api-production.up.railway.app';
  async function api(path, opts) {
    opts = opts || {};
    var init = { method: opts.method || 'GET', headers: {} };
    if (opts.body !== undefined) { init.headers['Content-Type'] = 'application/json'; init.body = JSON.stringify(opts.body); }
    var resp;
    try {
      if (window.WPSB_Auth && typeof window.WPSB_Auth.authedFetch === 'function') resp = await window.WPSB_Auth.authedFetch(RAILWAY_URL + path, init);
      else {
        var t = (window.WPSB && window.WPSB.getToken && window.WPSB.getToken()) || null;
        if (t) init.headers['Authorization'] = 'Bearer ' + t;
        resp = await fetch(RAILWAY_URL + path, init);
      }
    } catch (_) { return { ok: false, status: 0, code: 'NETWORK', error: tx('page.sites.cls.err.network', null, 'Could not reach the server.') }; }
    var data = null; try { data = await resp.json(); } catch (_) { data = null; }
    if (!resp.ok) return { ok: false, status: resp.status, code: (data && data.code) || 'ERROR', error: (data && data.error) || ('Request failed (' + resp.status + ')') };
    return { ok: true, status: resp.status, data: data || {} };
  }

  function Badge(props) {
    var b = badgeFor(props.value);
    var ok = b.tone === 'ok';
    return h('span', {
      className: 'wiz-tag', 'data-classification': norm(props.value),
      style: { background: ok ? 'var(--green-dim)' : 'var(--warn-dim)', color: ok ? 'var(--green)' : 'var(--warn)', borderColor: ok ? 'var(--green)' : 'var(--warn)' }
    }, b.text);
  }

  /* One read for the whole Sites page: map keyed by sites.id and by site_identities.id. */
  function useAll() {
    var s = React.useState({ loading: true, error: null, byId: {} }); var st = s[0], set = s[1];
    React.useEffect(function () {
      var live = true;
      api('/site-classifications').then(function (r) {
        if (!live) return;
        if (!r.ok) { set({ loading: false, error: r, byId: {} }); return; }
        var byId = {};
        (r.data.sites || []).forEach(function (row) { if (row.site_id) byId[row.site_id] = row; if (row.site_identity_id) byId[row.site_identity_id] = row; });
        set({ loading: false, error: null, byId: byId, truncated: !!r.data.truncated });
      });
      return function () { live = false; };
    }, []);
    return st;
  }

  function errorText(r) {
    var map = {
      AGENCY_ROLE_FORBIDDEN: tx('page.sites.cls.err.role', null, 'Your team role cannot change this. Ask the account owner or a developer on your team.'),
      CLEAR_REQUIRES_OWNER: tx('page.sites.cls.err.clear_owner', null, 'Only the account owner can clear a site to not regulated.'),
      ATTESTATION_REQUIRED: tx('page.sites.cls.err.attestation', null, 'Tick the declaration to clear this site.'),
      NOTE_REQUIRED: tx('page.sites.cls.err.note_required', null, 'Describe the regulated content in the note.'),
      CLASSIFICATION_CHANGES_PAUSED: tx('page.sites.cls.err.paused', null, 'Classification changes are paused by WPSiteBeam staff. The current classification still applies.'),
      SITE_IDENTITY_MISSING: tx('page.sites.cls.err.identity', null, 'This site has not been scanned yet, so it cannot be classified. It stays review-gated.'),
      CLASSIFICATION_WRITE_FAILED: tx('page.sites.cls.err.write', null, 'The classification could not be saved. Nothing was changed.')
    };
    return map[r && r.code] || (r && r.error) || tx('page.sites.cls.err.generic', null, 'Something went wrong. Nothing was changed.');
  }

  /* The Site settings control. props: { siteId, initial?, onSaved? }. __api / __role are test seams. */
  function Control(props) {
    var call = props.__api || api;
    var s0 = React.useState(props.initial || null); var cur = s0[0], setCur = s0[1];
    var s1 = React.useState(props.initial ? null : 'loading'); var phase = s1[0], setPhase = s1[1];
    var s2 = React.useState(props.__role !== undefined ? props.__role : undefined); var role = s2[0], setRole = s2[1];
    var s3 = React.useState(props.initial ? norm(props.initial.classification) : 'unclassified'); var pick = s3[0], setPick = s3[1];
    var s4 = React.useState(props.initial && props.initial.note || ''); var note = s4[0], setNote = s4[1];
    var s5 = React.useState(false); var attested = s5[0], setAttested = s5[1];
    var s6 = React.useState(null); var result = s6[0], setResult = s6[1];
    var s7 = React.useState(false); var busy = s7[0], setBusy = s7[1];
    var uid = 'wpsb-cls-' + String(props.siteId || 'x').slice(0, 8);

    React.useEffect(function () {
      if (props.initial) return;
      var live = true;
      call('/sites/' + encodeURIComponent(props.siteId) + '/classification').then(function (r) {
        if (!live) return;
        if (!r.ok) { setPhase('error'); setResult({ ok: false, text: errorText(r) }); return; }
        setCur(r.data); setPick(norm(r.data.classification)); setNote(r.data.note || ''); setPhase(null);
      });
      return function () { live = false; };
    }, [props.siteId]);
    React.useEffect(function () {
      if (role !== undefined) return;
      call('/agency/config').then(function (r) { setRole(r.ok ? (r.data.agency_role || null) : null); });
    }, []);

    var heading = h('h3', { id: uid + '-h', style: { fontSize: '.85rem', fontWeight: 700, marginBlock: '0 6px' } }, tx('page.sites.cls.title', null, 'Content review'));
    if (phase === 'loading') return h('section', { 'aria-labelledby': uid + '-h' }, heading, h('p', { className: 'muted' }, tx('common.loading', null, 'Loading…')));
    if (phase === 'error' || !cur) {
      return h('section', { 'aria-labelledby': uid + '-h' }, heading,
        h(Badge, { value: 'unclassified' }),
        h('p', { role: 'alert', style: { color: 'var(--red)', fontSize: '.78rem', marginBlockStart: 6 } }, (result && result.text) || errorText(null)));
    }

    var allowed = optionsFor(role);
    var canWrite = allowed.length > 0 && !cur.identity_missing;
    var clearing = pick === CLEARED && norm(cur.classification) !== CLEARED;
    var noteNeeded = pick === 'other_regulated';
    var changed = pick !== norm(cur.classification) || (note.trim() !== (cur.note || ''));
    var blocked = !changed || busy || (clearing && !attested) || (noteNeeded && !note.trim()) || note.length > NOTE_MAX;

    async function save(e) {
      if (e && e.preventDefault) e.preventDefault();
      if (blocked) return;
      setBusy(true); setResult(null);
      var body = { classification: pick };
      if (note.trim()) body.note = note.trim();
      if (pick === CLEARED) body.attestation = { version: ATTESTATION_VERSION, accepted: attested === true };
      var r = await call('/sites/' + encodeURIComponent(props.siteId) + '/classification', { method: 'PUT', body: body });
      setBusy(false);
      if (!r.ok) { setResult({ ok: false, text: errorText(r) }); return; }
      setCur(r.data); setAttested(false);
      setResult({ ok: true, text: tx('page.sites.cls.saved', { value: labelFor(r.data.classification) }, 'Saved: ' + labelFor(r.data.classification)) });
      if (props.onSaved) props.onSaved(r.data);
    }

    var current = h('div', { style: { display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' } },
      h(Badge, { value: cur.classification }),
      h('span', { className: 'muted', style: { fontSize: '.74rem' } }, consequenceFor(cur.classification)));

    if (!canWrite) {
      return h('section', { 'aria-labelledby': uid + '-h' }, heading, current,
        h('p', { className: 'muted', style: { fontSize: '.74rem', marginBlockStart: 6 } },
          cur.identity_missing
            ? tx('page.sites.cls.identity_missing', null, 'This site has not been scanned yet, so it cannot be classified. It stays review-gated.')
            : (role === undefined
              ? tx('common.loading', null, 'Loading…')
              : tx('page.sites.cls.read_only', null, 'Only the account owner or a developer on your team can change this.'))));
    }

    return h('form', { 'aria-labelledby': uid + '-h', onSubmit: save, style: { display: 'flex', flexDirection: 'column', gap: 8 } },
      heading, current,
      h('label', { htmlFor: uid + '-sel', style: { fontSize: '.74rem', fontWeight: 600 } }, tx('page.sites.cls.select_label', null, 'Classification')),
      h('select', { id: uid + '-sel', value: pick, disabled: busy, 'aria-describedby': uid + '-cons',
          onChange: function (e) { setPick(e.target.value); setAttested(false); setResult(null); },
          style: { minBlockSize: 44, paddingInline: 10, background: 'var(--surface)', color: 'var(--text)', border: '1px solid var(--border)', borderRadius: 6 } },
        VALUES.map(function (v) { return h('option', { key: v, value: v, disabled: allowed.indexOf(v) < 0 }, labelFor(v)); })),
      h('p', { id: uid + '-cons', className: 'muted', style: { fontSize: '.74rem', margin: 0 } }, consequenceFor(pick)),
      (role === 'dev') ? h('p', { className: 'muted', style: { fontSize: '.72rem', margin: 0 } }, tx('page.sites.cls.dev_hint', null, 'Only the account owner can clear a site to not regulated.')) : null,
      h('label', { htmlFor: uid + '-note', style: { fontSize: '.74rem', fontWeight: 600 } },
        noteNeeded ? tx('page.sites.cls.note_label_required', null, 'Note (required)') : tx('page.sites.cls.note_label', null, 'Note (optional)')),
      h('textarea', { id: uid + '-note', value: note, maxLength: NOTE_MAX, rows: 2, required: noteNeeded, disabled: busy,
          onChange: function (e) { setNote(e.target.value); },
          style: { minBlockSize: 44, padding: 8, background: 'var(--surface)', color: 'var(--text)', border: '1px solid var(--border)', borderRadius: 6 } }),
      clearing ? h('div', { style: { padding: 10, border: '1px solid var(--warn)', background: 'var(--warn-dim)', borderRadius: 6 } },
        h('p', { id: uid + '-att', style: { fontSize: '.78rem', marginBlock: '0 8px' } }, attestationText()),
        h('label', { style: { display: 'flex', gap: 8, alignItems: 'center', minBlockSize: 44, fontSize: '.78rem' } },
          h('input', { type: 'checkbox', checked: attested, 'aria-describedby': uid + '-att', 'data-attest': '1',
              onChange: function (e) { setAttested(!!e.target.checked); }, style: { inlineSize: 20, blockSize: 20 } }),
          tx('page.sites.cls.attest_label', null, 'I agree to this declaration'))) : null,
      h('div', null,
        h('button', { type: 'submit', className: 'wiz-btn wiz-btn-primary', disabled: blocked, 'data-save': '1', style: { minBlockSize: 44 } },
          busy ? tx('page.sites.cls.saving', null, 'Saving…') : tx('page.sites.cls.save', null, 'Save classification'))),
      h('div', { role: 'status', 'aria-live': 'polite', style: { fontSize: '.78rem' } },
        result && result.ok ? h('span', { style: { color: 'var(--green)' } }, result.text) : null),
      result && !result.ok ? h('p', { role: 'alert', style: { color: 'var(--red)', fontSize: '.78rem', margin: 0 } }, result.text) : null
    );
  }

  window.WPSB = window.WPSB || {};
  window.WPSB.siteClassification = {
    VALUES: VALUES, CLEARED: CLEARED, ATTESTATION_VERSION: ATTESTATION_VERSION,
    labelFor: labelFor, consequenceFor: consequenceFor, badgeFor: badgeFor, optionsFor: optionsFor, attestationText: attestationText,
    Badge: Badge, Control: Control, useAll: useAll
  };
})();
