/* NutriDMS, Health Canada Front-of-Package nutrition symbol (Canada FOP PRD §9)
   ───────────────────────────────────────────────────────────────────────────
   DROP-IN REPLACEMENT for screens/fop-symbol.jsx.

   Same public API and window exports as before, existing callers keep working:
     <FopSymbol nutrients={["Saturated Fat","Sugars"]}
                languageMode="BILINGUAL_EN_FIRST"   // _FR_FIRST | ENGLISH_ONLY | FRENCH_ONLY
                orientation="STANDARD"               // HORIZONTAL | COMPACT | VERTICAL
                size="md"                            // sm | md | lg
                attribution />
   window: FopSymbol, FopGlass, FopVariantPicker, FopDrawer, FOP_NUTRIENT_TEXT, generateCanadaFopSvg

   What changed: the artwork is now drawn entirely as faithful, scalable SVG
   (curved bars that nest behind the lens, correct lower-left handle, bilingual
   "Sodium" shown once, horizontal + vertical, blank bars in the fixed
   Sat fat → Sugars → Sodium order). No PNG assets required. Text, border,
   typography and spacing remain regulated and non-editable. */

const { useState: useFopState } = React;

const FOP_NUTRIENT_TEXT = {
  "Saturated Fat": { en: "Sat fat", fr: "Gras sat." },
  "Sugars": { en: "Sugars", fr: "Sucres" },
  "Sodium": { en: "Sodium", fr: "Sodium" },
};

/* ── Dynamic SVG generator (faithful to Health Canada artwork) ─────────────── */
const FOP_ORDER = ["sat_fat", "sugars", "sodium"];
const FOP_LABELS = {
  en: { title: "High in", sat_fat: "Sat fat", sugars: "Sugars", sodium: "Sodium", authority: "Health Canada" },
  fr: { title: "Élevé en", sat_fat: "Gras sat.", sugars: "Sucres", sodium: "Sodium", authority: "Santé Canada" },
};
const FOP_LAYOUT = {
  color: "#231f20", font: "Arial, Helvetica, sans-serif",
  inset: 9, border: 3, barH: 44, barGap: 6, barStroke: 2.5,
  headerH: 46, footerH: 36, lensGap: 6, magLeft: 15,
  lensDiameter: 0.7, lensStroke: 0.29, handleLength: 0.42, handleThickness: 0.88,
};
const _esc = (s) => String(s).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
const _r = (n) => Math.round(n * 100) / 100;
const _tw = (t, fs, bold) => t.length * fs * (bold ? 0.6 : 0.55);

function _label(key, language, frenchFirst) {
  if (language === "en") return FOP_LABELS.en[key];
  if (language === "fr") return FOP_LABELS.fr[key];
  if (FOP_LABELS.en[key] === FOP_LABELS.fr[key]) return FOP_LABELS.en[key];
  const a = frenchFirst ? FOP_LABELS.fr[key] : FOP_LABELS.en[key];
  const b = frenchFirst ? FOP_LABELS.en[key] : FOP_LABELS.fr[key];
  return `${a} / ${b}`;
}
function _magnifier(cx, cy, lensOuterR, lensStroke) {
  const lensR = lensOuterR - lensStroke / 2;
  const a = (135 * Math.PI) / 180;
  const hLen = lensOuterR * FOP_LAYOUT.handleLength;
  const hStroke = lensStroke * FOP_LAYOUT.handleThickness;
  const hx1 = cx + lensR * Math.cos(a), hy1 = cy + lensR * Math.sin(a);
  const hx2 = cx + (lensOuterR + hLen) * Math.cos(a), hy2 = cy + (lensOuterR + hLen) * Math.sin(a);
  const C = FOP_LAYOUT.color;
  return `<path d="M ${_r(hx1)} ${_r(hy1)} L ${_r(hx2)} ${_r(hy2)}" stroke="${C}" stroke-width="${_r(hStroke)}" stroke-linecap="round" />
<circle cx="${_r(cx)}" cy="${_r(cy)}" r="${_r(lensR)}" fill="#ffffff" stroke="${C}" stroke-width="${_r(lensStroke)}" />`;
}

function _genHorizontal(o) {
  const L = FOP_LAYOUT, language = o.language, frenchFirst = o.frenchFirst, blanks = o.includeBlankBars;
  const C = L.color, FONT = L.font, I = L.inset;
  const present = new Set(o.nutrients);
  const bars = blanks
    ? FOP_ORDER.map((k) => ({ label: present.has(k) ? _label(k, language, frenchFirst) : "", filled: present.has(k) }))
    : FOP_ORDER.filter((k) => present.has(k)).map((k) => ({ label: _label(k, language, frenchFirst), filled: true }));
  const n = Math.max(bars.length, 1);
  const stackH = n * L.barH + (n - 1) * L.barGap;
  const barsTop = I + L.headerH, footerTop = barsTop + stackH, height = footerTop + L.footerH + I;
  const lensOuterR = stackH * (L.lensDiameter / 2), lensStroke = lensOuterR * L.lensStroke;
  const cx = I + lensOuterR + L.magLeft, cy = barsTop + stackH / 2, rClip = lensOuterR + L.lensGap;
  const barFs = Math.min(30, L.barH * 0.6), headFs = Math.min(34, L.headerH * 0.74), footFs = Math.min(28, L.footerH * 0.66);
  const textX = cx + rClip + 16;
  const widest = Math.max(0, ...bars.map((b) => _tw(b.label, barFs, true)), _tw(_label("title", language, frenchFirst), headFs, true));
  const BAR_RIGHT_MARGIN = 16;
  const contentRight = Math.max(cx + lensOuterR + 160, textX + widest + 14 + BAR_RIGHT_MARGIN);
  const footW = _tw(_label("authority", language, frenchFirst), footFs, false);
  const width = Math.max(contentRight, I + 4 + footW + I) + I;
  const barRight = width - I - BAR_RIGHT_MARGIN;
  const clipX = (y) => { const dy = y - cy, ins = rClip * rClip - dy * dy; return ins > 0 ? cx + Math.sqrt(ins) : cx; };
  const barEls = bars.map((bar, i) => {
    const yt = barsTop + i * (L.barH + L.barGap), yb = yt + L.barH, xt = clipX(yt), xb = clipX(yb);
    const d = `M ${_r(xt)} ${_r(yt)} L ${_r(barRight)} ${_r(yt)} L ${_r(barRight)} ${_r(yb)} L ${_r(xb)} ${_r(yb)} A ${_r(rClip)} ${_r(rClip)} 0 0 0 ${_r(xt)} ${_r(yt)} Z`;
    const p = `<path d="${d}" fill="${bar.filled ? C : "#ffffff"}" stroke="${C}" stroke-width="${L.barStroke}" stroke-linejoin="round" />`;
    return bar.label ? p + `<text x="${_r(textX)}" y="${_r(yt + L.barH / 2)}" font-family="${FONT}" font-size="${_r(barFs)}" font-weight="700" fill="${bar.filled ? "#ffffff" : C}" dominant-baseline="central">${_esc(bar.label)}</text>` : p;
  }).join("");
  return `<svg xmlns="http://www.w3.org/2000/svg" width="${_r(width)}" height="${_r(height)}" viewBox="0 0 ${_r(width)} ${_r(height)}" role="img">
<rect x="${I}" y="${I}" width="${_r(width - I * 2)}" height="${_r(height - I * 2)}" fill="#ffffff" stroke="${C}" stroke-width="${L.border}" />
<text x="${_r(textX - 2)}" y="${_r(I + L.headerH / 2 + 2)}" font-family="${FONT}" font-size="${_r(headFs)}" font-weight="700" fill="${C}" dominant-baseline="central">${_esc(_label("title", language, frenchFirst))}</text>
${barEls}
<text x="${I + 4}" y="${_r(footerTop + L.footerH / 2 + 2)}" font-family="${FONT}" font-size="${_r(footFs)}" font-weight="500" fill="${C}" dominant-baseline="central">${_esc(_label("authority", language, frenchFirst))}</text>
${_magnifier(cx, cy, lensOuterR, lensStroke)}
</svg>`;
}

function _genVertical(o) {
  const L = FOP_LAYOUT, language = o.language, frenchFirst = o.frenchFirst, blanks = o.includeBlankBars;
  const C = L.color, FONT = L.font, I = L.inset;
  const present = new Set(o.nutrients);
  const linesFor = (k) => {
    if (language === "en") return [FOP_LABELS.en[k]];
    if (language === "fr") return [FOP_LABELS.fr[k]];
    if (FOP_LABELS.en[k] === FOP_LABELS.fr[k]) return [FOP_LABELS.en[k]];
    return frenchFirst ? [FOP_LABELS.fr[k], FOP_LABELS.en[k]] : [FOP_LABELS.en[k], FOP_LABELS.fr[k]];
  };
  const slots = blanks ? FOP_ORDER : FOP_ORDER.filter((k) => present.has(k));
  const bars = slots.map((k) => ({ lines: present.has(k) ? linesFor(k) : [], filled: present.has(k) }));
  const titleLines = linesFor("title"), authLines = linesFor("authority");
  const barFs = 28, titleFs = 30, footFs = 23, lh = (fs) => fs * 1.2;
  const barLines = Math.max(1, ...bars.filter((b) => b.filled).map((b) => b.lines.length));
  const barH = barLines * lh(barFs) + 14, nB = Math.max(bars.length, 1), stackH = nB * barH + (nB - 1) * L.barGap;
  const titleBlockH = titleLines.length * lh(titleFs);
  const lensOuterR = Math.max(26, titleBlockH / 2 + 4), lensStroke = lensOuterR * L.lensStroke;
  const headerH = Math.max(2 * lensOuterR, titleBlockH) + 10, headerGap = 8, footerH = authLines.length * lh(footFs) + 14;
  const height = I + headerH + headerGap + stackH + 8 + footerH + I;
  const maxTitleW = Math.max(...titleLines.map((t) => _tw(t, titleFs, true)));
  const filled = bars.filter((b) => b.filled).flatMap((b) => b.lines);
  const maxBarW = Math.max(0, ...filled.map((t) => _tw(t, barFs, true)));
  const maxFootW = Math.max(...authLines.map((t) => _tw(t, footFs, false)));
  const magW = 2 * lensOuterR + 4, headerTextX = I + magW + 14, barInset = 6, barPad = 14;
  const width = Math.max(headerTextX + maxTitleW + I, I + barInset + barPad + maxBarW + barPad + I + barInset, maxFootW + 2 * (I + 10), 170);
  const cyHeader = I + headerH / 2, cx = I + lensOuterR + 12;
  const barFullW = width - 2 * (I + barInset), minBarW = maxBarW + 2 * barPad, barW = Math.max(barFullW * 0.82, minBarW);
  const barLeft = (width - barW) / 2, barRight = barLeft + barW, barsTop = I + headerH + headerGap, footerTop = barsTop + stackH + 8;
  const block = (lines, x, cyc, fs, w, fill, anchor) => { const LH = lh(fs), sy = cyc - ((lines.length - 1) * LH) / 2; return lines.map((t, i) => `<text x="${_r(x)}" y="${_r(sy + i * LH)}" font-family="${FONT}" font-size="${fs}" font-weight="${w}" fill="${fill}" text-anchor="${anchor}" dominant-baseline="central">${_esc(t)}</text>`).join(""); };
  const barEls = bars.map((bar, i) => {
    const yt = barsTop + i * (barH + L.barGap), cyB = yt + barH / 2;
    const rect = `<rect x="${_r(barLeft)}" y="${_r(yt)}" width="${_r(barRight - barLeft)}" height="${_r(barH)}" rx="2" fill="${bar.filled ? C : "#ffffff"}" stroke="${C}" stroke-width="${L.barStroke}" />`;
    return rect + (bar.filled ? block(bar.lines, barLeft + barPad, cyB, barFs, 700, "#ffffff", "start") : "");
  }).join("");
  return `<svg xmlns="http://www.w3.org/2000/svg" width="${_r(width)}" height="${_r(height)}" viewBox="0 0 ${_r(width)} ${_r(height)}" role="img">
<rect x="${I}" y="${I}" width="${_r(width - I * 2)}" height="${_r(height - I * 2)}" fill="#ffffff" stroke="${C}" stroke-width="${L.border}" />
${block(titleLines, headerTextX, cyHeader, titleFs, 700, C, "start")}
${_magnifier(cx, cyHeader, lensOuterR, lensStroke)}
${barEls}
${block(authLines, width / 2, footerTop + footerH / 2, footFs, 500, C, "middle")}
</svg>`;
}

/* Public generator. nutrients = array of engine keys (sat_fat|sugars|sodium). */
function generateCanadaFopSvg(o) {
  return (o.orientation === "vertical" ? _genVertical : _genHorizontal)({
    nutrients: o.nutrients || [], language: o.language || "bilingual",
    frenchFirst: !!o.frenchFirst, includeBlankBars: o.includeBlankBars !== false,
  });
}

/* Standalone magnifying-glass mark (kept for compatibility). */
function FopGlass({ size = 46 }) {
  const svg = _magnifier(size / 2, size * 0.42, size * 0.34, size * 0.34 * FOP_LAYOUT.lensStroke);
  return <span style={{ display: "inline-flex", flexShrink: 0 }} dangerouslySetInnerHTML={{ __html: `<svg width="${size}" height="${size}" viewBox="0 0 ${size} ${size}">${svg}</svg>` }} />;
}

/* The full regulated symbol, same props as before. */
function FopSymbol({ nutrients, languageMode = "BILINGUAL_EN_FIRST", orientation = "STANDARD", size = "md", attribution = true }) {
  if (!nutrients || !nutrients.length) return null;
  const NKEY = { "Saturated Fat": "sat_fat", "Sugars": "sugars", "Sodium": "sodium" };
  const keys = FOP_ORDER.filter((k) => nutrients.some((n) => NKEY[n] === k || n === k));

  const language = languageMode === "ENGLISH_ONLY" ? "en" : languageMode === "FRENCH_ONLY" ? "fr" : "bilingual";
  const frenchFirst = languageMode === "BILINGUAL_FR_FIRST";
  const vertical = orientation === "VERTICAL";
  // STANDARD/HORIZONTAL → official 3-bar (blanks); COMPACT → only applicable bars.
  const includeBlankBars = orientation !== "COMPACT";

  const svg = generateCanadaFopSvg({ nutrients: keys, language, frenchFirst, orientation: vertical ? "vertical" : "horizontal", includeBlankBars });
  const w = vertical ? (size === "lg" ? 260 : size === "sm" ? 150 : 200) : (size === "lg" ? 380 : size === "sm" ? 210 : 280);
  const sized = svg.replace("<svg ", '<svg style="display:block;width:100%;height:auto;" ');

  return (
    <span className={`fop-symbol fop-${orientation.toLowerCase()} fop-${size}`} role="img"
      aria-label={`Health Canada front-of-package symbol: high in ${nutrients.join(", ")}`}
      style={{ display: "inline-block", width: w, maxWidth: "100%" }}
      dangerouslySetInnerHTML={{ __html: attribution ? sized : sized }} />
  );
}

/* Picker for the regulated language/orientation variants (unchanged). */
function FopVariantPicker({ languageMode, orientation, onLanguage, onOrientation }) {
  const LANGS = [
    { id: "BILINGUAL_EN_FIRST", t: "Bilingual · EN first" },
    { id: "BILINGUAL_FR_FIRST", t: "Bilingual · FR first" },
    { id: "ENGLISH_ONLY", t: "English only" },
    { id: "FRENCH_ONLY", t: "French only" },
  ];
  const ORIENT = [
    { id: "STANDARD", t: "Standard" },
    { id: "HORIZONTAL", t: "Horizontal" },
    { id: "VERTICAL", t: "Vertical" },
    { id: "COMPACT", t: "Compact" },
  ];
  return (
    <div className="fop-variants">
      <div className="fop-variant-row">
        <span className="fop-variant-lbl">Language format</span>
        <div className="fop-seg">
          {LANGS.map((l) => <button key={l.id} className={`fop-seg-btn ${languageMode === l.id ? "on" : ""}`} onClick={() => onLanguage(l.id)}>{l.t}</button>)}
        </div>
      </div>
      <div className="fop-variant-row">
        <span className="fop-variant-lbl">Orientation</span>
        <div className="fop-seg">
          {ORIENT.map((o) => <button key={o.id} className={`fop-seg-btn ${orientation === o.id ? "on" : ""}`} onClick={() => onOrientation(o.id)}>{o.t}</button>)}
        </div>
      </div>
      <div className="fop-locked-note"><Icon name="lock" size={11} /> Symbol artwork is regulated, text, border, typography and spacing can't be edited.</div>
    </div>
  );
}

/* Reusable right-slide drawer shell (unchanged). */
function FopDrawer({ open, onClose, title, subtitle, icon, children }) {
  useFopState;
  if (!open) return null;
  return (
    <div className="fop-drawer-scrim" onClick={onClose}>
      <div className="fop-drawer" onClick={(e) => e.stopPropagation()} role="dialog" aria-modal="true">
        <div className="fop-drawer-head">
          <div className="fop-drawer-title"><Icon name={icon || "shield-alert"} size={18} /> <div><b>{title}</b>{subtitle && <span>{subtitle}</span>}</div></div>
          <button className="fop-drawer-close" onClick={onClose} aria-label="Close"><Icon name="x" size={20} /></button>
        </div>
        <div className="fop-drawer-body">{children}</div>
      </div>
    </div>
  );
}

if (typeof window !== "undefined") Object.assign(window, { FopSymbol, FopGlass, FopVariantPicker, FopDrawer, FOP_NUTRIENT_TEXT, generateCanadaFopSvg });
