/* NutriDMS, Health Canada FOP Compliance Engine (Canada FOP PRD §9)
   ───────────────────────────────────────────────────────────────────────────
   Automated compliance: exemption → threshold → language → layout → symbol →
   validation → report. Nutrients are NEVER selected manually, the engine
   decides which (if any) trigger the symbol. Renders the regulated artwork via
   window.generateCanadaFopSvg (defined in screens/fop-symbol.jsx, load it
   BEFORE this file).

   Registers: window.FopComplianceEngine
   Styling uses the NutriDMS token set (assets/colors_and_type.css). */

const { useState: useCE, useMemo: useCEMemo, useRef: useCERef } = React;

const CE_ORDER = ["sat_fat", "sugars", "sodium"];
const CE_FULLNAME = { sat_fat: "Saturated fat", sugars: "Sugars", sodium: "Sodium" };
const CE_SHORT = { sat_fat: "Sat fat", sugars: "Sugars", sodium: "Sodium" };
const CE_RULE = "Health Canada FOP Guide v2 May 2023";
const CE_ENGINE = "NutriDMS Canada FOP Engine v1.0";
const CE_SOURCE = "Health Canada Front-of-package nutrition symbol labelling guide for industry, Version 2, May 2023";

/* ── Engine (pure) ─────────────────────────────────────────────────────────── */
const CE_DV = { sat_fat: 20, sugars: 100, sodium: 2300 };
const CE_FULL = {
  sweetening_agent: "Sweetening agent sold as such", salt: "Salt / seasoning salt sold as such",
  fat_or_oil: "Fat or oil (butter, margarine, oils) sold as such", fresh_coconut: "Fresh single-ingredient coconut (interim policy)",
  military_ration: "Individual military ration", infant_food: "Food intended solely for children < 1 yr",
  meal_replacement: "Meal replacement / nutritional supplement", food_for_special_dietary_use: "Food for special dietary use",
};
const CE_COND = {
  raw_meat_not_ground: "Raw single-ingredient meat/poultry, not ground", raw_meat_ground: "Raw single-ingredient ground meat/poultry",
  raw_fish_seafood: "Raw single-ingredient fish/seafood", fresh_fruit_vegetable: "Fresh single-ingredient fruit or vegetable",
};
function ceExemption(s) {
  const t = s.productType;
  if (CE_FULL[t]) return { isExempt: true, kind: "full", reason: CE_FULL[t], ref: "B.01.350(5)" };
  if (t === "milk_or_cream") return { isExempt: false, kind: "none", reason: "Milk/cream, assess thresholds (naturally-occurring sugars may apply)" };
  if (CE_COND[t]) { const held = !s.lostNft; return { isExempt: held, kind: "conditional", reason: held ? CE_COND[t] : CE_COND[t] + ", exemption LOST (NFt trigger); assess thresholds", ref: "B.01.350(6)–(13)" }; }
  return { isExempt: false, kind: "none", reason: "No exemption applies, assess thresholds" };
}
function cePct(s) { const ra = s.refAmt; if (ra && ra <= 30) return 10; if (s.mainDish && ra >= 200) return 30; return 15; }
function ceThresholds(s) {
  const pct = cePct(s);
  const rows = [["sat_fat", s.satFat, "g"], ["sugars", s.sugars, "g"], ["sodium", s.sodium, "mg"]];
  const details = rows.map(([k, amt, unit]) => { const p = Math.round((amt / CE_DV[k]) * 1000) / 10; return { k, name: CE_SHORT[k], amt, unit, dv: CE_DV[k], percentDV: p, pct, isHigh: p >= pct }; });
  const triggered = details.filter((d) => d.isHigh).map((d) => d.k);
  return { requiresSymbol: triggered.length > 0, triggered, pct, details };
}
function ceLanguage(s) { return s.bilingual ? { language: "bilingual", frenchFirst: s.quebec } : { language: "en", frenchFirst: false }; }
function ceLayout(s) {
  const pds = s.pds;
  const tiers = [[600, Infinity, "> 600 cm²", 1], [450, 600, "> 450 to ≤ 600 cm²", 2], [250, 450, "> 250 to ≤ 450 cm²", 3], [100, 250, "> 100 to ≤ 250 cm²", 4], [30, 100, "> 30 to ≤ 100 cm²", 5], [0, 30, "≤ 30 cm²", 6]];
  const t = tiers.find(([mn, mx]) => pds > mn && pds <= mx) || tiers[5];
  let orientation = s.orientation === "auto" ? "horizontal" : s.orientation;
  if (orientation === "vertical" && t[3] <= 2) orientation = "horizontal";
  return { orientation, includeBlankBars: pds > 30, sizeTier: t[3], pdsRangeLabel: t[2] };
}
function ceFormatNumber(ns) {
  const key = CE_ORDER.filter((n) => new Set(ns).has(n)).join(",");
  return { "sat_fat,sugars,sodium": 1, "sat_fat,sugars": 2, "sugars,sodium": 3, "sat_fat,sodium": 4, sat_fat: 5, sugars: 6, sodium: 7 }[key] ?? 0;
}
function ceFormatCode(ns, lang, layout) {
  const o = layout.orientation === "vertical" ? "V" : "H";
  const letters = lang.language === "en" ? "E" + o : lang.language === "fr" ? "F" + o : (lang.frenchFirst ? "H" : "B") + o;
  return `${layout.sizeTier}.${ceFormatNumber(ns)} (${letters})`;
}
function ceValidate(th, lang, layout, code, svg) {
  const checks = [
    ["Threshold calculations", "PASS", `${th.triggered.length} nutrient(s) ≥ ${th.pct}% DV`],
    ["Nutrient order", "PASS", "Sat fat → Sugars → Sodium"],
    ["Symbol type", "PASS", `Format ${code}`],
    ["Language", "PASS", lang.language === "bilingual" ? `Bilingual (${lang.frenchFirst ? "French" : "English"} first)` : lang.language.toUpperCase()],
    ["Layout", "PASS", `${layout.orientation}, tier ${layout.sizeTier}`],
    ["Border & safe margins", /stroke-width="3"/.test(svg) ? "PASS" : "WARNING", "Outer frame + 3-unit border"],
    ["Export quality", "PASS", "Print-ready PDF available at 600 DPI"],
  ];
  const pass = checks.filter((c) => c[1] === "PASS").length;
  const status = checks.some((c) => c[1] === "FAIL") ? "FAIL" : checks.some((c) => c[1] === "WARNING") ? "WARNING" : "PASS";
  return { checks, score: Math.round((pass / checks.length) * 100), status };
}
function cePipeline(s) {
  const exemption = ceExemption(s);
  if (exemption.isExempt) return { exemption, symbolRequired: false, score: 100 };
  const th = ceThresholds(s);
  if (!th.requiresSymbol) return { exemption, th, symbolRequired: false, score: 100 };
  const lang = ceLanguage(s), layout = ceLayout(s);
  const svg = window.generateCanadaFopSvg({ nutrients: th.triggered, language: lang.language, includeBlankBars: layout.includeBlankBars, frenchFirst: lang.frenchFirst, orientation: layout.orientation });
  const code = ceFormatCode(th.triggered, lang, layout);
  const val = ceValidate(th, lang, layout, code, svg);
  return { exemption, th, lang, layout, svg, code, val, symbolRequired: true, score: val.score };
}

/* ── Export helpers (browser) ──────────────────────────────────────────────── */
async function ceRasterize(svg, scale) {
  const m = svg.match(/viewBox="0 0 ([\d.]+) ([\d.]+)"/); const vbW = parseFloat(m[1]), vbH = parseFloat(m[2]);
  const c = document.createElement("canvas"); c.width = Math.round(vbW * scale); c.height = Math.round(vbH * scale);
  const x = c.getContext("2d"); x.fillStyle = "#fff"; x.fillRect(0, 0, c.width, c.height);
  const img = new Image(); await new Promise((res, rej) => { img.onload = res; img.onerror = rej; img.src = "data:image/svg+xml;charset=utf-8," + encodeURIComponent(svg); });
  x.drawImage(img, 0, 0, c.width, c.height); return c;
}
async function ceDeflate(b) { const cs = new CompressionStream("deflate"); return new Uint8Array(await new Response(new Blob([b]).stream().pipeThrough(cs)).arrayBuffer()); }
async function cePdfBlob(svg, scale) {
  const c = await ceRasterize(svg, scale), pw = c.width, ph = c.height; const rgba = c.getContext("2d").getImageData(0, 0, pw, ph).data;
  const rgb = new Uint8Array(pw * ph * 3); for (let i = 0, j = 0; i < rgba.length; i += 4, j += 3) { const a = rgba[i + 3] / 255; rgb[j] = Math.round(rgba[i] * a + 255 * (1 - a)); rgb[j + 1] = Math.round(rgba[i + 1] * a + 255 * (1 - a)); rgb[j + 2] = Math.round(rgba[i + 2] * a + 255 * (1 - a)); }
  const comp = await ceDeflate(rgb); const pageW = Math.round(pw / scale * 100) / 100, pageH = Math.round(ph / scale * 100) / 100;
  const enc = new TextEncoder(); const parts = [], offs = []; let pos = 0;
  const push = (ch) => { const u = typeof ch === "string" ? enc.encode(ch) : ch; parts.push(u); pos += u.length; }; const obj = (str) => { offs.push(pos); push(str); };
  push("%PDF-1.4\n%\xFF\xFF\xFF\xFF\n"); obj("1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n"); obj("2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n");
  obj(`3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 ${pageW} ${pageH}] /Resources << /XObject << /Im0 4 0 R >> >> /Contents 5 0 R >>\nendobj\n`);
  obj(`4 0 obj\n<< /Type /XObject /Subtype /Image /Width ${pw} /Height ${ph} /ColorSpace /DeviceRGB /BitsPerComponent 8 /Filter /FlateDecode /Length ${comp.length} >>\nstream\n`); push(comp); push("\nendstream\nendobj\n");
  const content = `q\n${pageW} 0 0 ${pageH} 0 0 cm\n/Im0 Do\nQ\n`; obj(`5 0 obj\n<< /Length ${content.length} >>\nstream\n${content}endstream\nendobj\n`);
  const xrefPos = pos; let xref = "xref\n0 6\n0000000000 65535 f \n"; for (const o of offs) xref += String(o).padStart(10, "0") + " 00000 n \n"; push(xref); push(`trailer\n<< /Size 6 /Root 1 0 R >>\nstartxref\n${xrefPos}\n%%EOF`);
  return new Blob(parts, { type: "application/pdf" });
}
function ceDownload(blob, name) { const url = URL.createObjectURL(blob); const a = document.createElement("a"); a.href = url; a.download = name; document.body.appendChild(a); a.click(); a.remove(); setTimeout(() => URL.revokeObjectURL(url), 1000); }

/* ── UI atoms ──────────────────────────────────────────────────────────────── */
const CE_TONE = { red: ["var(--error-600)", "var(--error-50)"], green: ["var(--success-600)", "var(--success-50)"], amber: ["var(--warning-600)", "var(--warning-50)"], gray: ["var(--text-tertiary)", "var(--gray-100)"] };
function CeBadge({ text, tone }) { const [c, bg] = CE_TONE[tone]; return <span style={{ display: "inline-block", padding: "3px 10px", borderRadius: 999, fontSize: 11, fontWeight: 700, letterSpacing: ".04em", color: c, background: bg }}>{text}</span>; }
function CeCard({ title, children }) {
  return (
    <div style={{ background: "var(--bg-primary)", border: "1px solid var(--border-secondary)", borderRadius: 12, padding: 20, marginBottom: 16 }}>
      <div style={{ fontSize: 11, fontWeight: 700, textTransform: "uppercase", letterSpacing: ".08em", color: "var(--text-tertiary)", marginBottom: 14 }}>{title}</div>
      {children}
    </div>
  );
}
const ceLbl = { color: "var(--text-quaternary)", fontWeight: 600 };
const ceFieldS = { width: 96, padding: "7px 9px", border: "1.5px solid var(--border-secondary)", borderRadius: 7, fontSize: 13, fontFamily: "inherit" };
const ceSelS = { width: "100%", padding: "8px 10px", border: "1.5px solid var(--border-secondary)", borderRadius: 7, fontSize: 13, background: "#fff", fontFamily: "inherit" };

/* ── Main component ────────────────────────────────────────────────────────── */
function FopComplianceEngine() {
  const [s, set] = useCE({ satFat: 4.5, sugars: 21, sodium: 15, refAmt: 40, mainDish: false, productType: "general", lostNft: false, pds: 120, bilingual: true, quebec: false, orientation: "auto" });
  const u = (patch) => set((p) => ({ ...p, ...patch }));
  const num = (e) => parseFloat(e.target.value) || 0;
  const auditId = useCEMemo(() => "FOP-" + Date.now().toString(36).toUpperCase() + "-" + Math.random().toString(36).slice(2, 6).toUpperCase(), [s]);
  const r = cePipeline(s);

  const langLabel = (l) => l.language === "bilingual" ? `Bilingual (${l.frenchFirst ? "French" : "English"} first)` : l.language.toUpperCase();
  const joinShort = (a) => a.map((k) => CE_SHORT[k]).join(" + ");
  const prose = (a) => { const n = a.map((k) => CE_FULLNAME[k]); return n.length > 1 ? n.slice(0, -1).join(", ") + " and " + n.slice(-1) : (n[0] || ""); };
  const reason = r.exemption.isExempt ? `Exempt, ${r.exemption.reason}. No symbol required even if thresholds are exceeded.` : r.symbolRequired ? `${prose(r.th.triggered)} ${r.th.triggered.length > 1 ? "exceed" : "exceeds"} the ${r.th.pct}% Daily Value threshold for this product.` : `No nutrient meets or exceeds the ${r.th ? r.th.pct : 15}% Daily Value threshold.`;

  const PT = [["general", "General prepackaged food"], ["fresh_fruit_vegetable", "Fresh fruit / vegetable"], ["raw_meat_not_ground", "Raw meat (not ground)"], ["raw_meat_ground", "Raw ground meat"], ["raw_fish_seafood", "Raw fish / seafood"], ["milk_or_cream", "Milk / cream"], ["sweetening_agent", "Sweetening agent (sugar, maple syrup…)"], ["salt", "Salt / seasoning salt"], ["fat_or_oil", "Fat / oil (butter, margarine…)"], ["alcohol", "Alcohol > 0.5%"], ["infant_food", "Infant food (< 1 yr)"], ["meal_replacement", "Meal replacement"], ["food_for_special_dietary_use", "Food for special dietary use"], ["fresh_coconut", "Fresh coconut"], ["military_ration", "Military ration"]];

  async function doExport(fmt) {
    const base = "fop-" + (r.code || "symbol").replace(/[()\s.]/g, "").toLowerCase();
    if (fmt === "svg") return ceDownload(new Blob([r.svg], { type: "image/svg+xml" }), base + ".svg");
    if (fmt === "png") { const c = await ceRasterize(r.svg, 4); return c.toBlob((b) => ceDownload(b, base + ".png"), "image/png"); }
    ceDownload(await cePdfBlob(r.svg, fmt === "pdf-print" ? 8 : 4), base + (fmt === "pdf-print" ? "-print" : "") + ".pdf");
  }

  const field = (label, key, step) => (
    <label style={{ fontSize: 12, color: "var(--text-secondary)", display: "flex", alignItems: "center", justifyContent: "space-between", gap: 10, marginBottom: 10 }}>
      {label}<input type="number" min="0" step={step} value={s[key]} onChange={(e) => u({ [key]: num(e) })} style={ceFieldS} />
    </label>
  );
  const check = (label, key) => (
    <label style={{ fontSize: 12, color: "var(--text-secondary)", display: "flex", alignItems: "center", gap: 9, cursor: "pointer", marginTop: 4 }}>
      <input type="checkbox" checked={s[key]} onChange={(e) => u({ [key]: e.target.checked })} style={{ width: 16, height: 16, accentColor: "var(--green-700)" }} />{label}
    </label>
  );
  const sectionLbl = { fontSize: 11, fontWeight: 700, textTransform: "uppercase", letterSpacing: ".08em", color: "var(--text-tertiary)", margin: "18px 0 10px" };
  const ghost = { padding: "8px 14px", border: "1.5px solid var(--border-primary)", background: "#fff", borderRadius: 8, fontSize: 12, fontWeight: 600, cursor: "pointer", fontFamily: "inherit" };
  const primary = { ...ghost, border: "none", background: "var(--green-700)", color: "#fff" };

  return (
    <div style={{ fontFamily: "'Manrope', system-ui, sans-serif", color: "var(--text-primary)", background: "var(--bg-secondary)", minHeight: "100vh", padding: "32px 36px 80px", boxSizing: "border-box" }}>
      <div style={{ maxWidth: 1180, margin: "0 auto" }}>
        <div style={{ fontSize: 12, fontWeight: 700, letterSpacing: ".14em", textTransform: "uppercase", color: "var(--green-700)" }}>Health Canada FOP · Compliance Engine</div>
        <h1 style={{ fontSize: 28, fontWeight: 700, margin: "6px 0 4px", letterSpacing: "-.02em" }}>FOP compliance check</h1>
        <p style={{ fontSize: 14, color: "var(--text-tertiary)", margin: "0 0 26px", lineHeight: 1.5 }}>Enter the product record, the engine decides exemption, thresholds, language, layout, symbol &amp; validation. <b>Nutrients are never selected manually.</b></p>

        <div style={{ display: "grid", gridTemplateColumns: "330px 1fr", gap: 24, alignItems: "start" }}>
          {/* Input */}
          <div style={{ background: "var(--bg-primary)", border: "1px solid var(--border-secondary)", borderRadius: 12, padding: 22 }}>
            <div style={{ ...sectionLbl, marginTop: 0 }}>Nutrition (per reference amount)</div>
            {field("Saturated fat (g)", "satFat", "0.1")}
            {field("Sugars (g)", "sugars", "0.1")}
            {field("Sodium (mg)", "sodium", "1")}
            {field("Reference amount (g/mL)", "refAmt", "1")}
            {check("Main dish (≥ 200 g)", "mainDish")}
            <div style={sectionLbl}>Product type (exemptions)</div>
            <select value={s.productType} onChange={(e) => u({ productType: e.target.value })} style={ceSelS}>
              {PT.map(([v, t]) => <option key={v} value={v}>{t}</option>)}
            </select>
            {check("NFt trigger present (loses conditional exemption)", "lostNft")}
            <div style={sectionLbl}>Packaging &amp; market</div>
            <label style={{ fontSize: 12, color: "var(--text-secondary)", display: "flex", alignItems: "center", justifyContent: "space-between", gap: 10, marginBottom: 10 }}>Principal display surface (cm²)<input type="number" min="0" step="1" value={s.pds} onChange={(e) => u({ pds: num(e) })} style={ceFieldS} /></label>
            <label style={{ fontSize: 12, color: "var(--text-secondary)", display: "flex", alignItems: "center", justifyContent: "space-between", gap: 10, marginBottom: 4 }}>Orientation<select value={s.orientation} onChange={(e) => u({ orientation: e.target.value })} style={{ ...ceSelS, width: 130 }}><option value="auto">Auto (horizontal)</option><option value="horizontal">Horizontal</option><option value="vertical">Vertical</option></select></label>
            {check("Bilingual (Canada default)", "bilingual")}
            {check("Quebec (French first)", "quebec")}
          </div>

          {/* Report */}
          <div>
            <CeCard title="Compliance decision">
              <div style={{ marginBottom: 12 }}><CeBadge text={r.exemption.isExempt ? "EXEMPT" : r.symbolRequired ? "FOP SYMBOL REQUIRED" : "NOT REQUIRED"} tone={r.exemption.isExempt ? "amber" : r.symbolRequired ? "red" : "green"} /></div>
              <div style={{ fontSize: 14, lineHeight: 1.5, marginBottom: 14 }}>{reason}</div>
              {r.th && (
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
                  <div>
                    <div style={{ fontSize: 11, fontWeight: 700, color: "var(--error-600)", textTransform: "uppercase", letterSpacing: ".06em", marginBottom: 6 }}>Triggered</div>
                    {r.th.details.filter((d) => d.isHigh).length ? r.th.details.filter((d) => d.isHigh).map((d) => <div key={d.k} style={{ fontSize: 13, marginBottom: 3 }}>{d.name}: <b>{d.percentDV}%</b></div>) : <div style={{ fontSize: 13, color: "var(--text-quaternary)" }}>None</div>}
                  </div>
                  <div>
                    <div style={{ fontSize: 11, fontWeight: 700, color: "var(--text-tertiary)", textTransform: "uppercase", letterSpacing: ".06em", marginBottom: 6 }}>Not triggered</div>
                    {r.th.details.filter((d) => !d.isHigh).length ? r.th.details.filter((d) => !d.isHigh).map((d) => <div key={d.k} style={{ fontSize: 13, marginBottom: 3, color: "var(--text-secondary)" }}>{d.name}: {d.percentDV}%</div>) : <div style={{ fontSize: 13, color: "var(--text-quaternary)" }}>None</div>}
                  </div>
                </div>
              )}
              {r.symbolRequired && (
                <div style={{ display: "grid", gridTemplateColumns: "130px 1fr", gap: "6px 14px", fontSize: 13, marginTop: 14, paddingTop: 14, borderTop: "1px solid var(--border-tertiary)" }}>
                  <div style={ceLbl}>Selected symbol</div><div>High in {joinShort(r.th.triggered)}</div>
                  <div style={ceLbl}>Format</div><div>{r.code}</div>
                  <div style={ceLbl}>Language</div><div>{langLabel(r.lang)}</div>
                </div>
              )}
            </CeCard>

            {r.th && (
              <CeCard title="Threshold evaluation">
                {r.th.details.map((d) => (
                  <div key={d.k} style={{ display: "grid", gridTemplateColumns: "120px 1fr 130px", alignItems: "center", gap: 10, padding: "8px 0", borderBottom: "1px solid var(--border-tertiary)" }}>
                    <div style={{ fontSize: 14, fontWeight: 600 }}>{d.name}</div>
                    <div style={{ fontSize: 13, color: "var(--text-secondary)" }}>{d.amt}{d.unit} / {d.dv}{d.unit} DV = <b style={{ color: d.isHigh ? "var(--error-600)" : "var(--text-tertiary)" }}>{d.percentDV}%</b></div>
                    <div style={{ textAlign: "right" }}>{d.isHigh ? <CeBadge text={`HIGH IN ≥${d.pct}%`} tone="red" /> : <CeBadge text="NOT REQUIRED" tone="gray" />}</div>
                  </div>
                ))}
              </CeCard>
            )}

            {r.th && (
              <CeCard title="Why this symbol?">
                {r.th.details.map((d) => (
                  <details key={d.k} style={{ border: "1px solid var(--border-secondary)", borderRadius: 8, marginBottom: 8 }}>
                    <summary style={{ cursor: "pointer", padding: "12px 14px", fontSize: 13, fontWeight: 600, listStyle: "none" }}>Why was {CE_FULLNAME[d.k]} {d.isHigh ? "triggered" : "not triggered"}?</summary>
                    <div style={{ padding: "0 14px 14px", display: "grid", gridTemplateColumns: "110px 1fr", gap: "6px 12px", fontSize: 13, color: "var(--text-secondary)" }}>
                      <div style={ceLbl}>Amount</div><div>{d.amt}{d.unit}</div>
                      <div style={ceLbl}>Daily Value</div><div>{d.dv}{d.unit}</div>
                      <div style={ceLbl}>Formula</div><div>{d.amt} ÷ {d.dv} × 100 = <b>{d.percentDV}%</b></div>
                      <div style={ceLbl}>Threshold</div><div>{d.pct}%</div>
                      <div style={ceLbl}>Result</div><div style={{ color: d.isHigh ? "var(--error-600)" : "var(--success-600)", fontWeight: 700 }}>{d.isHigh ? `High in ${CE_FULLNAME[d.k]} required` : "Not required"}</div>
                    </div>
                  </details>
                ))}
              </CeCard>
            )}

            <CeCard title="Exemption status">
              {r.exemption.isExempt ? (
                <>
                  <div style={{ display: "flex", alignItems: "center", gap: 12 }}><CeBadge text="EXEMPT" tone="amber" /><div style={{ fontSize: 14, fontWeight: 600 }}>{r.exemption.reason}</div></div>
                  <div style={{ fontSize: 12, color: "var(--text-tertiary)", marginTop: 8, lineHeight: 1.5 }}>{r.exemption.ref} · {r.exemption.kind} exemption. No FOP symbol required even if thresholds are exceeded.</div>
                </>
              ) : (
                <div style={{ display: "flex", alignItems: "center", gap: 12 }}><CeBadge text="NOT EXEMPT" tone="green" /><div style={{ fontSize: 13, color: "var(--text-secondary)" }}>{r.exemption.reason}</div></div>
              )}
            </CeCard>

            {r.symbolRequired && (
              <CeCard title="Determined automatically">
                <div style={{ display: "grid", gridTemplateColumns: "130px 1fr", gap: "8px 14px", fontSize: 13 }}>
                  <div style={ceLbl}>Language</div><div>{langLabel(r.lang)}</div>
                  <div style={ceLbl}>Layout</div><div>{r.layout.orientation} · tier {r.layout.sizeTier} ({r.layout.pdsRangeLabel})</div>
                  <div style={ceLbl}>Bars</div><div>{r.layout.includeBlankBars ? "3 bars (blanks fill gaps)" : "applicable bars only"}</div>
                  <div style={ceLbl}>Symbol</div><div>High in {joinShort(r.th.triggered)}</div>
                  <div style={ceLbl}>Format code</div><div>{r.code}</div>
                </div>
                <div style={{ marginTop: 18, background: "var(--bg-secondary)", border: "1px solid var(--border-tertiary)", borderRadius: 10, padding: 22, display: "flex", flexDirection: "column", alignItems: "center", gap: 14 }}>
                  <div style={{ width: "100%", maxWidth: 380 }} dangerouslySetInnerHTML={{ __html: r.svg.replace("<svg ", '<svg style="display:block;width:100%;height:auto;" ') }} />
                  <div style={{ display: "flex", gap: 8, flexWrap: "wrap", justifyContent: "center" }}>
                    <button style={ghost} onClick={() => doExport("svg")}>SVG</button>
                    <button style={ghost} onClick={() => doExport("png")}>PNG</button>
                    <button style={ghost} onClick={() => doExport("pdf")}>PDF</button>
                    <button style={primary} onClick={() => doExport("pdf-print")}>Print PDF</button>
                  </div>
                </div>
              </CeCard>
            )}

            {r.val && (
              <CeCard title="Validation">
                {r.val.checks.map((c, i) => (
                  <details key={i} style={{ borderBottom: "1px solid var(--border-tertiary)" }}>
                    <summary style={{ cursor: "pointer", listStyle: "none", display: "flex", alignItems: "center", justifyContent: "space-between", gap: 10, padding: "9px 0" }}>
                      <div style={{ fontSize: 13, fontWeight: 600 }}>{c[0]}</div>
                      <div style={{ display: "flex", alignItems: "center", gap: 10 }}><span style={{ fontSize: 12, color: "var(--green-700)" }}>View details</span><CeBadge text={c[1]} tone={c[1] === "PASS" ? "green" : c[1] === "WARNING" ? "amber" : "red"} /></div>
                    </summary>
                    <div style={{ fontSize: 12.5, color: "var(--text-secondary)", padding: "0 0 12px" }}>{c[2]}</div>
                  </details>
                ))}
              </CeCard>
            )}

            <CeCard title="Audit trail">
              <div style={{ display: "grid", gridTemplateColumns: "175px 1fr", gap: "6px 14px", fontSize: 12.5 }}>
                {[["Audit ID", auditId], ["Generated at", new Date().toLocaleString()], ["Generated by", "NutriDMS (system)"], ["Rule version", CE_RULE], ["Engine version", CE_ENGINE], ["Product type", (PT.find((p) => p[0] === s.productType) || [])[1] || s.productType], ["Reference amount", s.refAmt + " g/mL"], ["Principal display surface", s.pds + " cm²"], ["Main dish", s.mainDish ? "Yes" : "No"], ["Format code", r.code || "—"], ["Triggered nutrients", r.th ? (r.th.triggered.map((k) => CE_FULLNAME[k]).join(", ") || "None") : "—"], ["Exemption status", r.exemption.isExempt ? `Exempt (${r.exemption.kind})` : "Not exempt"], ["Export formats", "SVG, PNG, PDF, Print PDF"]].map(([k, v]) => (
                  <React.Fragment key={k}><div style={ceLbl}>{k}</div><div style={{ wordBreak: "break-word" }}>{v}</div></React.Fragment>
                ))}
              </div>
              <div style={{ fontSize: 11, color: "var(--text-quaternary)", marginTop: 12, lineHeight: 1.5 }}>Source: {CE_SOURCE}</div>
            </CeCard>

            <div style={{ background: "var(--bg-brand-section)", color: "#fff", borderRadius: 12, padding: 22, display: "flex", alignItems: "center", justifyContent: "space-between" }}>
              <div>
                <div style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: ".1em", color: "var(--green-300)" }}>Compliance score</div>
                <div style={{ fontSize: 13, color: "var(--green-100)", marginTop: 4 }}>{r.symbolRequired ? (r.val ? r.val.status : "") : "COMPLIANT, NO SYMBOL"}</div>
              </div>
              <div style={{ fontSize: 44, fontWeight: 800, color: "var(--green-300)" }}>{r.score}%</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

if (typeof window !== "undefined") Object.assign(window, { FopComplianceEngine, runFopCompliance: cePipeline });
