/* FORGE — ScreenComplianceVerifier · BEE Schedule 7 + IS:8034 audit
   Babel-standalone in-browser React. NO ES imports / exports.
   Globals: React, PumpPhysics, PUMP_TENANT, navigate, registerPumpRoute. */

(function () {
  'use strict';

  var R = (typeof React !== 'undefined') ? React : null;
  if (!R) return;
  var uSCV = R.useState;
  var uMCV = R.useMemo;

  // Paper palette (matches act1-2 / head-curve / motor-sizing)
  var PAPER_BG     = 'oklch(0.985 0.004 85)';
  var PAPER_BG_2   = 'oklch(0.93 0.005 85)';
  var PAPER_BG_3   = 'oklch(0.965 0.005 85)';
  var PAPER_INK    = 'oklch(0.16 0.01 85)';
  var PAPER_INK_2  = 'oklch(0.30 0.01 85)';
  var PAPER_INK_3  = 'oklch(0.46 0.01 85)';
  var PAPER_INK_4  = 'oklch(0.60 0.01 85)';
  var PAPER_LINE   = 'oklch(0.84 0.006 85)';
  var PAPER_LINE_S = 'oklch(0.90 0.005 85)';
  var ACCENT       = 'oklch(0.78 0.16 75)';
  var GREEN        = 'oklch(0.66 0.13 145)';
  var RED          = 'oklch(0.58 0.18 28)';
  var AMBER        = 'oklch(0.78 0.13 70)';
  var BLUE         = 'oklch(0.62 0.10 235)';

  var FONT_UI    = 'var(--font-ui)';
  var FONT_MONO  = 'var(--font-mono)';
  var FONT_SERIF = 'var(--font-serif)';

  function root() {
    return {
      background: PAPER_BG, color: PAPER_INK,
      minHeight: '100vh', overflowY: 'auto',
      fontFamily: FONT_UI, fontSize: 14, lineHeight: 1.5,
      width: '100%', position: 'absolute', inset: 0,
      WebkitFontSmoothing: 'antialiased'
    };
  }
  function container() { return { maxWidth: 1280, margin: '0 auto', padding: '32px 40px', width: '100%' }; }
  function mono() {
    return { fontFamily: FONT_MONO, fontSize: 12, letterSpacing: '0.08em', textTransform: 'uppercase', color: PAPER_INK_3 };
  }
  function Card(props) {
    var s = Object.assign({ background: PAPER_BG_3, border: '1px solid ' + PAPER_LINE, borderRadius: 10, padding: 20 }, props.style || {});
    return R.createElement('div', { style: s }, props.children);
  }
  function Pill(props) {
    var tones = {
      default: { bg: PAPER_BG_3, fg: PAPER_INK_2, bd: PAPER_LINE },
      accent:  { bg: PAPER_BG_3, fg: ACCENT,      bd: ACCENT      },
      green:   { bg: PAPER_BG_3, fg: GREEN,       bd: GREEN       },
      red:     { bg: PAPER_BG_3, fg: RED,         bd: RED         },
      amber:   { bg: PAPER_BG_3, fg: AMBER,       bd: AMBER       },
      blue:    { bg: PAPER_BG_3, fg: BLUE,        bd: BLUE        }
    };
    var p = tones[props.tone || 'default'];
    return (
      <span style={{
        display: 'inline-flex', alignItems: 'center', gap: 6,
        height: 22, padding: '0 10px', borderRadius: 999,
        fontFamily: FONT_MONO, fontSize: 12,
        letterSpacing: '0.08em', textTransform: 'uppercase',
        border: '1px solid ' + p.bd, color: p.fg, background: p.bg
      }}>{props.children}</span>
    );
  }
  function Header(props) {
    return (
      <div style={{ marginBottom: 28 }}>
        <div style={Object.assign({}, mono(), { marginBottom: 8 })}>{props.eyebrow}</div>
        <h1 style={{ fontFamily: FONT_SERIF, fontSize: 34, fontWeight: 600, letterSpacing: '-0.015em', margin: 0, color: PAPER_INK }}>{props.title}</h1>
        {props.subtitle && <div style={{ marginTop: 8, color: PAPER_INK_3, fontSize: 14 }}>{props.subtitle}</div>}
      </div>
    );
  }

  function getSkuList() {
    var T = (typeof window !== 'undefined') ? window.PUMP_TENANT : null;
    if (!T || !T.boms) return [];
    return T.boms.map(function (b) {
      // Look up SKU label from cost_cascade and matcher candidates if present
      return { sku: b.sku, lines: b.lines || [] };
    });
  }

  // SKU duty + efficiency defaults (matches head-curve preset table)
  var SKU_DESIGN = {
    'M-27418': { hp_class: 1.0,  rated_q_lpm: 40,  rated_h_m: 22, eff_meas_pct: 41, hydro_test_bar: 33, ir_meg_ohm: 200, hv_kv_ac_min: 1.5, impeller_clearance_mm: 0.32 },
    'M-26102': { hp_class: 0.75, rated_q_lpm: 36,  rated_h_m: 18, eff_meas_pct: 38, hydro_test_bar: 27, ir_meg_ohm: 280, hv_kv_ac_min: 1.5, impeller_clearance_mm: 0.30 },
    'M-31507': { hp_class: 5.0,  rated_q_lpm: 95,  rated_h_m: 32, eff_meas_pct: 49, hydro_test_bar: 48, ir_meg_ohm: 180, hv_kv_ac_min: 1.5, impeller_clearance_mm: 0.34 }
  };

  // IS:8034 (submersible pumpsets) check thresholds — pulled into one object so
  // the spec citations can render in the UI.
  var IS_8034 = {
    name: 'IS:8034 — Submersible Pumpsets',
    rev: '2018',
    checks: [
      { id: 'IS-CL-9.1',  label: 'Hydrostatic body test',           rule: '1.5× rated head, 5 min hold, no leak',         category: 'mechanical' },
      { id: 'IS-CL-10.2', label: 'Insulation resistance (cold)',    rule: '≥ 100 MΩ at 500 V DC',                          category: 'electrical' },
      { id: 'IS-CL-10.3', label: 'High-voltage withstand (1 min)',  rule: '1.5 kV AC, no breakdown',                       category: 'electrical' },
      { id: 'IS-CL-11.4', label: 'Earth continuity',                rule: '< 0.1 Ω between earth pin and frame',           category: 'electrical' },
      { id: 'IS-CL-12.1', label: 'Impeller axial clearance',        rule: '0.30 – 0.35 mm (typical 4″ stage)',              category: 'mechanical' },
      { id: 'IS-CL-13.5', label: 'NRV material',                    rule: 'S.G. iron / SS · CI flagged (fatigue risk)',    category: 'mechanical' },
      { id: 'IS-CL-14.2', label: 'Cable colour code',               rule: 'R-Y-B per IS:694, polarity verified',           category: 'electrical' }
    ]
  };

  var BEE_S7 = {
    name: 'BEE Schedule 7 — Agricultural Pump Sets',
    rev: '2024',
    note: 'Star band by HP class and measured efficiency (test rig)'
  };

  function evaluateBom(sku, design, parts, bom) {
    var checks = [];
    var byNum = {};
    (parts || []).forEach(function (p) { byNum[p.num] = p; });
    var lines = (bom && bom.lines) || [];

    // IS-CL-9.1 — hydro test: design.hydro_test_bar ≥ 1.5× rated head bar
    var ratedBar = design.rated_h_m / 10.2; // 1 bar ≈ 10.2 m water
    var hydroOk = design.hydro_test_bar >= 1.5 * ratedBar;
    checks.push({
      id: 'IS-CL-9.1', label: 'Hydrostatic body test',
      pass: hydroOk,
      note: 'Spec ' + design.hydro_test_bar + ' bar · required ≥ ' + (1.5 * ratedBar).toFixed(1) + ' bar',
      citation: 'IS:8034 cl. 9.1'
    });

    // IS-CL-10.2 — IR ≥ 100 MΩ
    checks.push({
      id: 'IS-CL-10.2', label: 'Insulation resistance',
      pass: design.ir_meg_ohm >= 100,
      note: design.ir_meg_ohm + ' MΩ · required ≥ 100 MΩ',
      citation: 'IS:8034 cl. 10.2'
    });

    // IS-CL-10.3 — HV withstand 1.5 kV
    checks.push({
      id: 'IS-CL-10.3', label: 'HV withstand 1.5 kV / 1 min',
      pass: design.hv_kv_ac_min >= 1.5,
      note: design.hv_kv_ac_min + ' kV · required ≥ 1.5 kV',
      citation: 'IS:8034 cl. 10.3'
    });

    // IS-CL-11.4 — earth continuity is a test-rig pass/fail, assume QG-25 enforces
    checks.push({
      id: 'IS-CL-11.4', label: 'Earth continuity',
      pass: true,
      note: 'Enforced at QG-25 (bond tester < 0.1 Ω)',
      citation: 'IS:8034 cl. 11.4'
    });

    // IS-CL-12.1 — impeller axial clearance 0.30-0.35 mm
    var clOk = design.impeller_clearance_mm >= 0.30 && design.impeller_clearance_mm <= 0.35;
    checks.push({
      id: 'IS-CL-12.1', label: 'Impeller axial clearance',
      pass: clOk,
      note: design.impeller_clearance_mm + ' mm · target 0.30–0.35 mm',
      citation: 'IS:8034 cl. 12.1'
    });

    // IS-CL-13.5 — NRV material: legacy CI fails (fatigue), S.G.-400 / SS passes.
    // Find NRV line in BOM (any part_num starting with 20.07)
    var nrvLine = lines.find(function (l) { return /^20\.07/.test(l.part_num); });
    var nrvPart = nrvLine ? byNum[nrvLine.part_num] : null;
    var nrvFail = false; var nrvNote = 'NRV not in BOM';
    if (nrvPart) {
      var isCI  = /\bCI\b|\bC\.I\.\b/i.test(nrvPart.name);
      var isSG400 = /S\.G\.?-?400|SG-?400/i.test(nrvPart.name);
      var isSS  = /\bSS\b/i.test(nrvPart.name);
      nrvFail = isCI && !isSG400;
      if (isSG400) nrvNote = nrvPart.num + ' · S.G.-400 (post ECO-0051)';
      else if (isCI) nrvNote = nrvPart.num + ' · ' + nrvPart.name + ' — CI flagged, fatigue cycle risk';
      else if (isSS) nrvNote = nrvPart.num + ' · SS body';
      else nrvNote = nrvPart.num + ' · ' + nrvPart.name;
    }
    checks.push({
      id: 'IS-CL-13.5', label: 'NRV material',
      pass: !nrvFail,
      note: nrvNote,
      citation: 'IS:8034 cl. 13.5 · ECO-0051'
    });

    // IS-CL-14.2 — cable colour: enforced at QG-24 (visual + multimeter)
    checks.push({
      id: 'IS-CL-14.2', label: 'Cable colour & polarity',
      pass: true,
      note: 'Enforced at QG-24 · R-Y-B per IS:694',
      citation: 'IS:8034 cl. 14.2'
    });

    return checks;
  }

  // ════════════════════════════════════════════════════════════════════
  function ScreenComplianceVerifier() {
    var PP = (typeof window !== 'undefined') ? window.PumpPhysics : null;
    var T  = (typeof window !== 'undefined') ? window.PUMP_TENANT : null;
    var skuList = getSkuList();
    var initial = skuList[0] ? skuList[0].sku : 'M-27418';

    var skuState = uSCV(initial);
    var sku = skuState[0]; var setSku = skuState[1];

    var design = SKU_DESIGN[sku] || SKU_DESIGN['M-27418'];

    var effState = uSCV(design.eff_meas_pct);
    var effPct = effState[0]; var setEffPct = effState[1];

    R.useEffect(function () {
      setEffPct(design.eff_meas_pct);
    }, [sku]);

    var bom = (T && T.boms) ? T.boms.find(function (b) { return b.sku === sku; }) : null;
    var parts = T ? T.parts : [];

    var isChecks = uMCV(function () {
      return evaluateBom(sku, design, parts, bom);
    }, [sku, design, parts, bom, effPct]);

    var beeResult = uMCV(function () {
      if (!PP) return { stars: 0, band_name: '—', threshold_eff_pct: 0 };
      return PP.beeStarBand({ hp_class: design.hp_class, eff_pct: effPct });
    }, [design.hp_class, effPct]);

    var beePass = beeResult.stars >= 3; // factory cert floor

    var totalChecks = isChecks.length + 1; // +1 for BEE
    var passes = isChecks.filter(function (c) { return c.pass; }).length + (beePass ? 1 : 0);
    var overall = passes === totalChecks ? 'green' : (passes >= totalChecks - 1 ? 'amber' : 'red');

    var td = { padding: '10px 12px', fontFamily: FONT_MONO, color: PAPER_INK, fontSize: 13, verticalAlign: 'top' };
    var th = {
      textAlign: 'left', padding: '10px 12px',
      fontFamily: FONT_MONO, fontSize: 12,
      letterSpacing: '0.08em', textTransform: 'uppercase',
      color: PAPER_INK_3
    };

    return (
      <div style={root()}>
        <div style={container()}>
          <Header
            eyebrow="Forge · COMPLIANCE"
            title="Compliance verifier"
            subtitle="BEE Schedule 7 + IS:8034 audit on the active BOM. Flags non-conforming parts (e.g. legacy CI NRV → fatigue cycle)."
          />

          {/* SKU chips */}
          <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', marginBottom: 20, alignItems: 'center' }}>
            {skuList.map(function (s) {
              var active = s.sku === sku;
              return (
                <button
                  key={s.sku}
                  onClick={function () { setSku(s.sku); }}
                  style={{
                    padding: '8px 14px', borderRadius: 8,
                    border: '1px solid ' + (active ? ACCENT : PAPER_LINE),
                    background: active ? ACCENT : PAPER_BG_3,
                    color: active ? 'oklch(0.14 0.02 55)' : PAPER_INK_2,
                    fontFamily: FONT_MONO, fontSize: 12, letterSpacing: '0.04em',
                    cursor: 'pointer'
                  }}>
                  {s.sku}
                </button>
              );
            })}
            <div style={{ marginLeft: 'auto' }}>
              <Pill tone={overall}>{passes}/{totalChecks} pass</Pill>
            </div>
          </div>

          <div style={{ display: 'grid', gridTemplateColumns: '1fr 320px', gap: 24 }}>
            {/* IS:8034 + BEE table */}
            <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
              <Card>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
                  <div style={mono()}>{IS_8034.name} · rev {IS_8034.rev}</div>
                  <Pill tone="blue">{isChecks.filter(function (c) { return c.pass; }).length}/{isChecks.length} pass</Pill>
                </div>
                <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                  <thead>
                    <tr style={{ background: PAPER_BG_2, borderBottom: '1px solid ' + PAPER_LINE }}>
                      <th style={th}>Clause</th>
                      <th style={th}>Check</th>
                      <th style={th}>Evidence</th>
                      <th style={th}>Result</th>
                    </tr>
                  </thead>
                  <tbody>
                    {isChecks.map(function (c) {
                      return (
                        <tr key={c.id} style={{
                          borderBottom: '1px solid ' + PAPER_LINE_S,
                          background: c.pass ? 'transparent' : 'oklch(0.97 0.04 28)'
                        }}>
                          <td style={td}>{c.id}</td>
                          <td style={Object.assign({}, td, { fontFamily: FONT_UI })}>{c.label}</td>
                          <td style={Object.assign({}, td, { fontFamily: FONT_UI, color: PAPER_INK_3 })}>{c.note}</td>
                          <td style={Object.assign({}, td, { fontFamily: FONT_UI })}>
                            {c.pass ? <Pill tone="green">PASS</Pill> : <Pill tone="red">FAIL</Pill>}
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </Card>

              <Card>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
                  <div style={mono()}>{BEE_S7.name} · rev {BEE_S7.rev}</div>
                  <Pill tone={beePass ? 'green' : 'red'}>{beeResult.stars}-star</Pill>
                </div>
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 16, marginBottom: 14 }}>
                  <div>
                    <div style={mono()}>HP class</div>
                    <div style={{ fontFamily: FONT_MONO, fontSize: 20, color: PAPER_INK }}>{design.hp_class} HP</div>
                  </div>
                  <div>
                    <div style={mono()}>Measured η</div>
                    <div style={{ fontFamily: FONT_MONO, fontSize: 20, color: PAPER_INK }}>{effPct} %</div>
                  </div>
                  <div>
                    <div style={mono()}>Band threshold</div>
                    <div style={{ fontFamily: FONT_MONO, fontSize: 20, color: PAPER_INK }}>{beeResult.threshold_eff_pct} %</div>
                  </div>
                </div>
                <div style={{ marginBottom: 12 }}>
                  <div style={Object.assign({}, mono(), { fontSize: 11, marginBottom: 4 })}>Slide to test efficiency vs band</div>
                  <input
                    type="range" min="20" max="60" step="0.5" value={effPct}
                    id="compliance-efficiency-test" name="compliance-efficiency-test"
                    aria-label="Slide to test efficiency vs band (%)"
                    onChange={function (e) { setEffPct(Number(e.target.value)); }}
                    style={{ width: '100%' }} />
                </div>
                <div style={{ fontSize: 12, color: PAPER_INK_3, lineHeight: 1.5 }}>
                  {BEE_S7.note}. Star bands sourced from <span style={{ fontFamily: FONT_MONO }}>compliance.star_rating_decision_tree</span>.
                </div>
              </Card>
            </div>

            {/* Sidebar — summary + cross-links */}
            <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
              <Card style={{ background: PAPER_BG_2 }}>
                <div style={Object.assign({}, mono(), { marginBottom: 10 })}>Verification summary</div>
                <div style={{ fontFamily: FONT_SERIF, fontSize: 28, color: PAPER_INK }}>
                  {passes}/{totalChecks}
                </div>
                <div style={{ fontSize: 12, color: PAPER_INK_3, marginBottom: 12 }}>
                  clauses pass for {sku}
                </div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                    <span style={{ color: PAPER_INK_3 }}>BEE star</span>
                    <span style={{ fontFamily: FONT_MONO }}>{beeResult.stars}-star</span>
                  </div>
                  <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                    <span style={{ color: PAPER_INK_3 }}>IS:8034</span>
                    <span style={{ fontFamily: FONT_MONO, color: isChecks.every(function (c) { return c.pass; }) ? GREEN : RED }}>
                      {isChecks.every(function (c) { return c.pass; }) ? 'compliant' : 'non-conforming'}
                    </span>
                  </div>
                  <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                    <span style={{ color: PAPER_INK_3 }}>BOM lines</span>
                    <span style={{ fontFamily: FONT_MONO }}>{bom ? bom.lines.length : 0}</span>
                  </div>
                </div>
              </Card>

              <Card>
                <div style={Object.assign({}, mono(), { marginBottom: 10 })}>Standards referenced</div>
                <ul style={{ margin: 0, paddingLeft: 18, fontSize: 12, color: PAPER_INK_3, lineHeight: 1.7 }}>
                  <li>IS:8034 — Submersible Pumpsets (cl. 9.1, 10.2, 10.3, 11.4, 12.1, 13.5, 14.2)</li>
                  <li>IS:9079 — Single-phase Induction Motors (SF margin)</li>
                  <li>BEE Schedule 7 — Agricultural Pump Sets (star bands)</li>
                  <li>IS:694 — Cable colour code</li>
                </ul>
              </Card>

              <Card>
                <div style={Object.assign({}, mono(), { marginBottom: 10 })}>Cross-links</div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 6, fontSize: 13 }}>
                  <a onClick={function () { if (typeof navigate === 'function') navigate('/forge/head-curve'); }} style={{ color: BLUE, cursor: 'pointer' }}>→ Head curve</a>
                  <a onClick={function () { if (typeof navigate === 'function') navigate('/forge/motor-sizing'); }} style={{ color: BLUE, cursor: 'pointer' }}>→ Motor sizing</a>
                  <a onClick={function () { if (typeof navigate === 'function') navigate('/forge/ebom'); }} style={{ color: BLUE, cursor: 'pointer' }}>→ E-BOM</a>
                </div>
              </Card>
            </div>
          </div>
        </div>
      </div>
    );
  }

  if (typeof window !== 'undefined') {
    window.ScreenComplianceVerifier = ScreenComplianceVerifier;
    if (typeof window.registerPumpRoute === 'function') {
      window.registerPumpRoute({
        path: '/forge/compliance', mode: 'forge', title: 'Compliance verifier',
        renderer: function () { return R.createElement(ScreenComplianceVerifier); }
      });
    }
  }
})();
