/* NutriDMS, FDA Label Studio (FDA 2016 Nutrition Facts + full PRD modules)
   Tabs: Nutrition Facts · Kids Labels · Supplement Facts · Menu Labeling ·
   Validation Center · Export (multi-format + e-signatures).
   Reuses lblNutrientProfile for raw nutrients. */

const { useState: useFdaState, useMemo: useFdaMemo, useEffect: useFdaEffect, useRef: useFdaRef } = React;

/* ───────── Authentic FDA Nutrition Facts panel (standard / dual / tabular / linear / simplified) ───────── */
function FdaNutritionFacts({ recipe, profile, servings, rounded, zoom, format, ageGroup }) {
  const data = fdaNftRows(profile, recipe, rounded, ageGroup);
  const dvCell = (v) => v == null ? "" : `${v}%`;
  const amt = (r) => r.amount == null ? "—" : `${r.amount}${r.unit || ""}`;
  const z = { transform: `scale(${zoom})` };

  if (format === "linear") {
    const parts = [`Calories ${data.calories}`];
    data.rows.forEach((r) => parts.push(`${r.label} ${amt(r)}${r.dv != null ? ` (${r.dv}%)` : ""}`));
    data.micros.forEach((r) => parts.push(`${r.label} ${amt(r)} (${r.dv}%)`));
    return (
      <div className="fda-nft fda-linear" style={z}>
        <b>Nutrition Facts</b> Serving size {Math.round(profile.servingG)}g · about {servings} servings per container. {parts.join("; ")}. <span className="fda-foot-inline">{fdaFootnote(ageGroup)}</span>
      </div>
    );
  }

  // Dual column: per-serving + per-container values
  if (format === "dual") {
    const per = fdaNftRows(profile, recipe, rounded, ageGroup);
    const contProfile = {}; Object.keys(profile).forEach((k) => contProfile[k] = (k === "servingG") ? profile[k] : (profile[k] || 0) * servings);
    const cont = fdaNftRows(contProfile, recipe, rounded, ageGroup);
    return (
      <div className="fda-nft fda-dual" style={z}>
        <div className="fda-title">Nutrition Facts</div>
        <div className="fda-serv-line"><span>{servings} servings per container</span></div>
        <div className="fda-serv-size"><strong>Serving size</strong><strong>{Math.round(profile.servingG)}g</strong></div>
        <div className="fda-rule-lg" />
        <div className="fda-dual-head"><span></span><span>Per serving</span><span>Per container</span></div>
        <div className="fda-dual-cal"><strong>Calories</strong><strong>{per.calories}</strong><strong>{cont.calories}</strong></div>
        <div className="fda-rule-md" />
        <div className="fda-dual-dvh"><span></span><span>% DV*</span><span>% DV*</span></div>
        {per.rows.map((r, i) => (
          <div key={r.k} className={`fda-drow ind-${r.indent || 0} ${r.bold ? "b" : ""}`}>
            <span>{r.bold ? <strong>{r.label}</strong> : r.label} {amt(r)}</span>
            <span>{dvCell(r.dv)}</span>
            <span>{dvCell(cont.rows[i].dv)}</span>
          </div>
        ))}
        <div className="fda-foot">{fdaFootnote(ageGroup)}</div>
      </div>
    );
  }

  const dvKeyMap = { fat: "fat_g", saturated: "fat_saturated_g", cholesterol: "cholesterol_mg", sodium: "sodium_mg", carbohydrate: "carbohydrate_g", fibre: "fibre_g", added: "added_sugars_g", protein: "protein_g" };
  const tipFor = (r) => {
    const dk = dvKeyMap[r.k]; if (!dk || r.dv == null) return undefined;
    const b = fdaCalcBreakdown(r.amount, dk, ageGroup); if (!b) return undefined;
    return `${r.label}: ${b.formula} = ${b.raw}% → ${b.rounded}% DV`;
  };
  const Row = (r) => (
    <div key={r.k} className={`fda-row ind-${r.indent || 0} ${r.bold ? "b" : ""}`}>
      <span className="fda-row-l">{r.bold ? <strong>{r.label}</strong> : r.label} {amt(r)}{r.k === "cholesterol" && data.cholLessThan5 ? " (Less than 5mg)" : ""}</span>
      <span className="fda-row-dv" title={tipFor(r)}>{dvCell(r.dv)}</span>
    </div>
  );

  return (
    <div className={`fda-nft ${format === "tabular" ? "fda-tabular" : ""}`} style={z}>
      <div className="fda-title">Nutrition Facts</div>
      <div className="fda-serv-line"><span>{servings} servings per container</span></div>
      <div className="fda-serv-size"><strong>Serving size</strong><strong>{Math.round(profile.servingG)}g</strong></div>
      <div className="fda-rule-lg" />
      <div className="fda-cal-row">
        <div className="fda-cal-l">Amount per serving</div>
        <div className="fda-cal-main"><strong>Calories</strong><strong className="fda-cal-v">{data.calories}</strong></div>
      </div>
      <div className="fda-rule-md" />
      <div className="fda-dv-head">% Daily Value*</div>
      <div className="fda-rows">{data.rows.map(Row)}</div>
      <div className="fda-rule-md" />
      <div className="fda-rows fda-micros">
        {data.micros.map((r) => (
          <div key={r.k} className="fda-row ind-0">
            <span className="fda-row-l">{r.label} {amt(r)}</span>
            <span className="fda-row-dv">{dvCell(r.dv)}</span>
          </div>
        ))}
      </div>
      <div className="fda-rule-sm" />
      <div className="fda-foot">{fdaFootnote(ageGroup)}</div>
    </div>
  );
}

function FdaLabelStudio() {
  const { role, toast } = useApp();
  const recipes = useFdaMemo(() => (typeof RECIPES !== "undefined") ? RECIPES.filter((r) => r.status === "published" || r.status === "approved") : [], []);
  const [recipeId, setRecipeId] = useFdaState(recipes[0] ? recipes[0].id : null);
  const recipe = recipes.find((r) => r.id === recipeId) || recipes[0];
  const baseProfile = useFdaMemo(() => recipe ? lblNutrientProfile(recipe) : null, [recipe]);
  const defServing = baseProfile ? Math.round(baseProfile.servingG) : 100;
  const [servingG, setServingG] = useFdaState(defServing);
  useFdaEffect(() => { setServingG(baseProfile ? Math.round(baseProfile.servingG) : 100); }, [recipeId]);
  const [rounded, setRounded] = useFdaState(true);
  const [zoom, setZoom] = useFdaState(1);
  const [format, setFormat] = useFdaState("standard");
  const [allergensReviewed, setAllergensReviewed] = useFdaState(false);
  const [tab, setTab] = useFdaState("nft");
  const [ageGroup, setAgeGroup] = useFdaState("adult");
  const [source, setSource] = useFdaState("recipe");
  const [sigs, setSigs] = useFdaState([]);
  const ofAll = useFdaMemo(() => (typeof ofLoad === "function") ? ofLoad() : [], []);
  const SOURCES = [
    { id: "recipe", label: "Recipe", icon: "chef-hat" },
    { id: "menu", label: "Food Menu", icon: "utensils" },
    { id: "product", label: "Products", icon: "package" },
    { id: "package", label: "Packages", icon: "boxes" },
  ];
  const sourceOpts = useFdaMemo(() => {
    if (source === "recipe") return recipes.map((r) => ({ key: r.id, recipeId: r.id, name: r.name }));
    const types = source === "menu" ? ["menu-item"] : source === "product" ? ["product"] : ["combo", "catering"];
    const list = (ofAll || []).filter((o) => types.includes(o.type)).map((o) => ({ key: o.id, recipeId: (o.single && o.single.recipeId) || (recipes[0] && recipes[0].id), name: o.name }));
    return list.length ? list : recipes.map((r) => ({ key: r.id, recipeId: r.id, name: r.name }));
  }, [source, ofAll]);

  if (!recipe) return <div className="rp-empty"><div className="icon"><Icon name="flag" size={24} /></div><h3>No published recipes</h3><p>Publish a recipe to generate an FDA Nutrition Facts label.</p></div>;

  const profile = lblScaleProfile(baseProfile, baseProfile.servingG, servingG);
  profile.servingG = servingG;
  const servingsPer = Math.max(1, Math.round((baseProfile.servingG * (recipe.servings || 4)) / servingG));
  const validation = fdaValidate({ profile, recipe, servingG, allergensReviewed, format, ageGroup });

  const TABS = [
    { id: "nft", label: "Nutrition Facts", icon: "table-2" },
    { id: "supplement", label: "Supplement Facts", icon: "pill" },
    { id: "menu", label: "Menu Labeling", icon: "utensils-crossed" },
    { id: "claims", label: "Claims", icon: "badge-check" },
    { id: "validation", label: "Validation Center", icon: "shield-check", badge: validation.fail || validation.warn || null },
    { id: "versions", label: "Versions", icon: "history" },
    { id: "export", label: "Export", icon: "download" },
  ];

  return (
    <div className="ls fda-ls">
      <div className="page-head">
        <div>
          <h1 className="page-title">FDA Label Studio</h1>
          <p className="page-sub">FDA 2016 labeling (21 CFR 101.9), legally compliant Nutrition Facts &amp; Supplement Facts panels only.</p>
        </div>
        <div className="ls-head-pills">
          <span className={`pill ${validation.status === "pass" ? "success" : validation.status === "warning" ? "warning" : "danger"}`}>
            <Icon name={validation.status === "pass" ? "shield-check" : "shield-alert"} size={13} /> {validation.status === "pass" ? "Validated" : validation.status === "warning" ? "Review needed" : "Errors"}
          </span>
        </div>
      </div>

      <div className="fda-tabs">
        {TABS.map((t) => (
          <button key={t.id} className={`fda-tab ${tab === t.id ? "on" : ""}`} onClick={() => setTab(t.id)}>
            <Icon name={t.icon} size={14} /> {t.label}
            {t.badge ? <span className="fda-tab-badge">{t.badge}</span> : null}
          </button>
        ))}
      </div>

      <div className="fda-legal-note"><Icon name="shield-check" size={13} /> This generator produces only legally compliant FDA Nutrition Facts &amp; Supplement Facts panels. Consumer summaries (parent-friendly, teen, QR, Loraa insights) live in the separate <b>Nutrition Insight Engine</b> and are never labeled as Nutrition Facts.</div>

      <div className="ls-grid">
        <aside className="ls-left">
          <section className="ls-card">
            <div className="ls-card-h"><Icon name="layers" size={14} /> Source</div>
            <div className="fda-source-seg">
              {SOURCES.map((s) => (
                <button key={s.id} className={`fda-source-btn ${source === s.id ? "on" : ""}`} onClick={() => { setSource(s.id); }}>
                  <Icon name={s.icon} size={13} /> {s.label}
                </button>
              ))}
            </div>
            <label className="ls-field" style={{ marginTop: 12 }}><span>{(SOURCES.find((s) => s.id === source) || {}).label}</span>
              <select value={recipeId} onChange={(e) => setRecipeId(e.target.value)}>
                {sourceOpts.map((o) => <option key={o.key} value={o.recipeId}>{o.name}</option>)}
              </select>
            </label>
          </section>
          <section className="ls-card">
            <div className="ls-card-h"><Icon name="scale" size={14} /> Serving setup</div>
            <div className="fda-serv-ctrl">
              <button onClick={() => setServingG((g) => Math.max(5, g - 5))}>−</button>
              <div className="fda-serv-val"><b>{servingG}</b><span>g / serving</span></div>
              <button onClick={() => setServingG((g) => g + 5)}>+</button>
            </div>
            <div className="ls-hint">≈ {servingsPer} servings per container · reference {defServing} g</div>
            {(() => { const racc = fdaRaccFor(recipe); if (!racc) return null; const off = Math.abs(servingG - racc.racc) / racc.racc > 0.25;
              return (
                <div className="fda-racc">
                  <div className="fda-racc-h"><Icon name="ruler" size={12} /> RACC reference <span>21 CFR 101.12</span></div>
                  <div className="fda-racc-body"><b>{racc.cat}</b><span>{racc.racc} {racc.unit} · {racc.house}</span></div>
                  <button className="fda-racc-apply" onClick={() => setServingG(racc.racc)}>Use RACC ({racc.racc}{racc.unit})</button>
                  {off && <div className="fda-racc-warn"><Icon name="alert-triangle" size={11} /> Declared serving differs &gt;25% from the RACC.</div>}
                </div>
              );
            })()}
            {(() => { const at = fdaAtwater(profile); const decl = Math.round(profile.energy_kcal); const diff = Math.abs(at - decl); if (at == null) return null;
              return <div className={`fda-atwater ${diff > decl * 0.1 ? "off" : ""}`}><Icon name="calculator" size={11} /> Atwater check: {at} kcal calculated (4·4·9·7) vs {decl} declared{diff > decl * 0.1 ? ", review macros" : ", consistent"}</div>;
            })()}
          </section>
          {(tab === "nft") && (
            <section className="ls-card">
              <div className="ls-card-h"><Icon name="users" size={14} /> Population (age group)</div>
              <div className="fda-fmt-list">
                {FDA_AGE_GROUPS.map((a) => (
                  <button key={a.id} className={`fda-fmt ${ageGroup === a.id ? "on" : ""}`} onClick={() => setAgeGroup(a.id)}>
                    <span className="fda-fmt-nm">{a.id === "adult" ? "Adult Nutrition Facts" : a.label + " Nutrition Facts"}</span>
                    <span className="fda-fmt-desc">{a.id === "adult" ? "FDA 2016 adult Daily Values" : "Age-specific Daily Values"}</span>
                  </button>
                ))}
              </div>
            </section>
          )}
          {(tab === "nft") && (
            <section className="ls-card">
              <div className="ls-card-h"><Icon name="layout-template" size={14} /> Format</div>
              <div className="fda-fmt-list">
                {FDA_FORMATS.map((f) => (
                  <button key={f.id} className={`fda-fmt ${format === f.id ? "on" : ""}`} onClick={() => setFormat(f.id)}>
                    <span className="fda-fmt-nm">{f.label}</span><span className="fda-fmt-desc">{f.desc}</span>
                  </button>
                ))}
              </div>
            </section>
          )}

          <section className="ls-card">
            <div className="ls-card-h"><Icon name="sliders-horizontal" size={14} /> Display</div>
            <label className="fda-toggle"><input type="checkbox" checked={rounded} onChange={(e) => setRounded(e.target.checked)} /> Apply FDA rounding</label>
            <div className="fda-zoom"><span>Zoom</span><input type="range" min="0.7" max="1.6" step="0.1" value={zoom} onChange={(e) => setZoom(Number(e.target.value))} /></div>
          </section>
        </aside>

        <main className="ls-center">
          <div className="ls-stage">
            <div className="ls-stage-inner" id="fda-stage">
              {tab === "nft" && <FdaNutritionFacts recipe={recipe} profile={profile} servings={servingsPer} rounded={rounded} zoom={zoom} format={format} ageGroup={ageGroup} />}
              {tab === "supplement" && <FdaSupplementFacts recipe={recipe} profile={profile} zoom={zoom} />}
              {tab === "menu" && <FdaMenuLabel recipe={recipe} profile={profile} servings={servingsPer} />}
              {tab === "claims" && <FdaClaims recipe={recipe} profile={profile} />}
              {tab === "validation" && <FdaValidationCenter validation={validation} profile={profile} recipe={recipe} ageGroup={ageGroup} servingG={servingG} role={role} />}
              {tab === "versions" && <FdaVersions recipe={recipe} profile={profile} servingG={servingG} servings={servingsPer} rounded={rounded} validation={validation} allergensReviewed={allergensReviewed} role={role} toast={toast} />}
              {tab === "export" && <FdaExport recipe={recipe} profile={profile} servings={servingsPer} rounded={rounded} format={format} validation={validation} sigs={sigs} setSigs={setSigs} role={role} toast={toast} />}
            </div>
          </div>
        </main>

        <aside className="ls-right">
          <section className="ls-card">
            <div className="ls-card-h"><Icon name="clipboard-check" size={14} /> Compliance</div>
            <div className="fda-vsum">
              <div className="fda-vsum-cell pass"><b>{validation.pass}</b><span>Pass</span></div>
              <div className="fda-vsum-cell warn"><b>{validation.warn}</b><span>Warn</span></div>
              <div className="fda-vsum-cell fail"><b>{validation.fail}</b><span>Fail</span></div>
            </div>
            {!allergensReviewed && <button className="btn secondary sm" style={{ marginTop: 12 }} onClick={() => { setAllergensReviewed(true); toast("Allergen statement marked reviewed"); }}><Icon name="shield-check" size={14} /> Mark allergens reviewed</button>}
            <button className="btn ghost sm" style={{ marginTop: 8, width: "100%" }} onClick={() => setTab("validation")}><Icon name="arrow-right" size={13} /> Open Validation Center</button>
          </section>
          <FdaFopCard profile={profile} recipe={recipe} ageGroup={ageGroup} />
          <FdaLoraa validation={validation} recipe={recipe} />
        </aside>
      </div>
    </div>
  );
}

/* ── §13 Supplement Facts ── */
function FdaSupplementFacts({ recipe, profile, zoom }) {
  const x = fdaExtra(profile, recipe);
  const rows = [
    { k: "Vitamin D", amt: `${x.vitamin_d_mcg} mcg`, dv: fdaDV(x.vitamin_d_mcg, "vitamin_d_mcg") },
    { k: "Calcium", amt: `${Math.round(profile.calcium_mg)} mg`, dv: fdaDV(profile.calcium_mg, "calcium_mg") },
    { k: "Iron", amt: `${Math.round(profile.iron_mg * 10) / 10} mg`, dv: fdaDV(profile.iron_mg, "iron_mg") },
    { k: "Potassium", amt: `${Math.round(profile.potassium_mg)} mg`, dv: fdaDV(profile.potassium_mg, "potassium_mg") },
  ];
  return (
    <div className="fda-nft fda-supp" style={{ transform: `scale(${zoom})` }}>
      <div className="fda-title" style={{ fontSize: 24 }}>Supplement Facts</div>
      <div className="fda-serv-size"><strong>Serving size</strong><strong>1 serving</strong></div>
      <div className="fda-rule-lg" />
      <div className="fda-dv-head">Amount Per Serving · % Daily Value*</div>
      <div className="fda-rows">
        {rows.map((r) => (
          <div key={r.k} className="fda-row ind-0 b"><span className="fda-row-l"><strong>{r.k}</strong> {r.amt}</span><span className="fda-row-dv">{r.dv == null ? "†" : r.dv + "%"}</span></div>
        ))}
        <div className="fda-row ind-0"><span className="fda-row-l">Proprietary Botanical Blend 250 mg</span><span className="fda-row-dv">†</span></div>
        <div className="fda-row ind-1"><span className="fda-row-l">Green Tea Extract, Turmeric, Ginger</span><span className="fda-row-dv"></span></div>
      </div>
      <div className="fda-rule-sm" />
      <div className="fda-foot">* Percent Daily Values are based on a 2,000 calorie diet. † Daily Value not established.</div>
    </div>
  );
}

/* ── §12 Menu Labeling (enterprise, 21 CFR 101.11) ── */
function FdaMenuLabel({ recipe, profile, servings }) {
  const cal = fdaRoundCal(profile.energy_kcal);
  // a small board of related items (this item + scaled siblings) for chain context
  const others = (typeof RECIPES !== "undefined" ? RECIPES.filter((r) => (r.status === "published" || r.status === "approved") && r.id !== recipe.id).slice(0, 3) : []);
  return (
    <div className="fda-menu">
      <div className="fda-menu-board">
        <div className="fda-menu-board-h">Menu / Menu Board</div>
        <div className="fda-menu-item primary">
          <div className="fda-menu-nm">{recipe.name}</div>
          <div className="fda-menu-cal">{cal} <span>Cal</span></div>
        </div>
        {others.map((r) => { const p = lblNutrientProfile(r); return (
          <div key={r.id} className="fda-menu-item"><div className="fda-menu-nm2">{r.name}</div><div className="fda-menu-cal2">{fdaRoundCal(p.energy_kcal)} Cal</div></div>
        ); })}
        <div className="fda-menu-statement">2,000 calories a day is used for general nutrition advice, but calorie needs vary.</div>
      </div>
      <div className="fda-menu-detail">
        <div className="fda-menu-detail-h"><Icon name="qr-code" size={14} /> Written nutrition information, available on request (21 CFR 101.11(b)(2)(ii))</div>
        <div className="fda-menu-grid">
          <div><span>Calories</span><b>{cal}</b></div>
          <div><span>Calories from fat</span><b>{Math.round((profile.fat_g || 0) * 9 / 5) * 5}</b></div>
          <div><span>Total Fat</span><b>{fdaRoundG(profile.fat_g)}g</b></div>
          <div><span>Saturated Fat</span><b>{fdaRoundG(profile.fat_saturated_g)}g</b></div>
          <div><span>Trans Fat</span><b>{fdaRoundG(profile.fat_trans_g)}g</b></div>
          <div><span>Cholesterol</span><b>{Math.round(profile.cholesterol_mg)}mg</b></div>
          <div><span>Sodium</span><b>{fdaRoundSodium(profile.sodium_mg)}mg</b></div>
          <div><span>Total Carbs</span><b>{fdaRoundG(profile.carbohydrate_g)}g</b></div>
          <div><span>Dietary Fiber</span><b>{fdaRoundG(profile.fibre_g)}g</b></div>
          <div><span>Total Sugars</span><b>{fdaRoundG(profile.sugars_g)}g</b></div>
          <div><span>Protein</span><b>{fdaRoundG(profile.protein_g)}g</b></div>
        </div>
        <div className="fda-menu-succinct">“The recommended limits for a 2,000 calorie daily diet are 65 g total fat, 20 g saturated fat, 300 mg cholesterol, and 2,400 mg sodium.”</div>
        <div className="fda-menu-disc"><Icon name="info" size={11} /> Calorie declaration is mandatory on menus &amp; menu boards for chains with 20+ locations. Full written nutrition info and ingredient/allergen disclosure must be available on request.</div>
      </div>
    </div>
  );
}

/* ── FDA Front-of-Package "Nutrition Info" box (proposed rule, 21 CFR 101.6) ── */
function FdaFopBoxArt({ box, zoom = 1 }) {
  return (
    <div className="fda-fopbox" style={{ transform: `scale(${zoom})` }}>
      <div className="fda-fopbox-h">Nutrition Info</div>
      <div className="fda-fopbox-rows">
        {box.rows.map((r) => (
          <div key={r.label} className="fda-fopbox-row">
            <span className="fda-fopbox-amt">{r.amount == null ? "—" : Math.round(r.amount) + (r.unit || "")}</span>
            <span className="fda-fopbox-lbl">{r.label}</span>
            <span className="fda-fopbox-dv">{r.dvPercent == null ? "—" : r.dvPercent + "% DV"}</span>
            <span className={`fda-fopbox-lvl lv-${r.level.toLowerCase()}`}>{r.level}</span>
          </div>
        ))}
      </div>
    </div>
  );
}
function FdaFopCard({ profile, recipe, ageGroup }) {
  const box = fdaFopBox(profile, recipe, ageGroup);
  const [open, setOpen] = useFdaState(false);
  return (
    <>
      <button className="fop-trigger" onClick={() => setOpen(true)}>
        <span className={`fop-trigger-ic ${box.anyHigh ? "req" : "ok"}`}><Icon name="scan-line" size={18} /></span>
        <span className="fop-trigger-tx">
          <b>Front-of-package · Nutrition Info</b>
          <span className={box.anyHigh ? "req" : ""}>{box.rows.map((r) => `${r.label.split(" ")[0]} ${r.level}`).join(" · ")}</span>
        </span>
        <Icon name="chevron-right" size={18} className="fop-trigger-arrow" />
      </button>
      <FopDrawer open={open} onClose={() => setOpen(false)} title="Front-of-package · Nutrition Info" subtitle="FDA proposed rule · 21 CFR 101.6" icon="scan-line">
        <section className="ls-card">
          <div className="ls-card-h"><Icon name="scan-line" size={14} /> Nutrition Info box <span className="ls-pill-note">PDP · upper third</span></div>
          <div className="fda-fop-preview"><FdaFopBoxArt box={box} zoom={1.25} /></div>
          <div className="fda-fop-legend">
            <span><i className="lv-low" /> Low ≤5% DV</span>
            <span><i className="lv-med" /> Med 6-19%</span>
            <span><i className="lv-high" /> High ≥20%</span>
          </div>
          <div className="ls-hint">FDA Nutrition Info box (proposed rule, 21 CFR 101.6), Saturated Fat, Sodium and Added Sugars with a Low / Med / High descriptor. Black-and-white, placed on the principal display panel. Not a "high in" warning symbol.</div>
        </section>
        <section className="ls-card">
          <div className="ls-card-h"><Icon name="list-checks" size={14} /> Nutrient detail</div>
          <div className="ls-fop">
            {box.rows.map((r) => (
              <div key={r.label} className={`ls-fop-row ${r.level === "High" ? "req" : ""}`}>
                <span>{r.label}</span>
                <span className="ls-fop-pct">{r.dvPercent == null ? "—" : r.dvPercent + "% DV"}</span>
                <span className={`pill ${r.level === "High" ? "warning" : r.level === "Med" ? "neutral" : "success"}`} style={{ fontSize: 10 }}>{r.level}</span>
              </div>
            ))}
          </div>
          <div className="ls-hint">Daily Values: {box.dvVersion}. {box.regulation}.</div>
        </section>
      </FopDrawer>
    </>
  );
}

/* ── Ask Loraa, FDA label copilot (supportive on flags), matches CFIA Ask-Loraa format ── */
function FdaLoraaLogo() {
  const onErr = (e) => { const img = e.currentTarget; const n = +(img.dataset.retry || 0); if (n < 4) { img.dataset.retry = n + 1; setTimeout(() => { img.src = `assets/loraa-logo.png?r=${n + 1}`; }, 250 * (n + 1)); } };
  return <span className="cu-loraa-logo sm"><img src="assets/loraa-logo.png" alt="Loraa" onError={onErr} /></span>;
}
function FdaLoraa({ validation, recipe }) {
  const [open, setOpen] = useFdaState(false);
  const [asked, setAsked] = useFdaState(null);
  const flagged = (validation.items || []).filter((i) => i.state !== "pass");
  const QS = [
    { q: "What's blocking approval?", a: validation.fail ? `${validation.fail} blocking error(s): ${flagged.filter((i) => i.state === "fail").map((i) => i.title).join(", ")}. Open the Validation Center, each maps to a regulation with the fix.` : validation.warn ? `No blocking errors. ${validation.warn} item(s) to confirm: ${flagged.map((i) => i.title).join(", ")}.` : "Nothing, every FDA check passes. You're clear to approve and export." },
    { q: "Why is a nutrient flagged?", a: flagged.length ? flagged.map((i) => `${i.title}: ${i.detail}`).slice(0, 2).join("  ") : "No nutrients are flagged. Saturated fat and sodium are within range for the selected age group." },
    { q: "How do I fix the warnings?", a: validation.calorieCheck && validation.calorieCheck.off ? `Calories differ from the macro cross-check (${validation.calorieCheck.calc} vs ${validation.calorieCheck.decl}), re-check the fat/carb/protein values. Then confirm allergens and any high-nutrient warnings.` : "Confirm the allergen Contains statement and review any saturated-fat / sodium warnings. Most warnings clear once a reviewer signs off." },
    { q: "Is this label ready to publish?", a: validation.status === "pass" ? "Yes, all checks pass. Sign off in Export → Electronic Signatures." : validation.status === "fail" ? "Not yet, resolve the blocking errors first." : "Almost, clear the warnings or have a reviewer confirm them, then sign and export." },
  ];
  return (
    <div className={`fda-loraa ${open ? "open" : ""}`}>
      <button className="fda-loraa-head" onClick={() => setOpen((o) => !o)}>
        <FdaLoraaLogo />
        <span className="fda-loraa-t">Ask Loraa about this label</span>
        <Icon name={open ? "chevron-up" : "chevron-down"} size={15} />
      </button>
      {open && (
        <div className="fda-loraa-body">
          <div className="fda-loraa-lead">Loraa reviewed this label against the FDA 2016 rules, the selected age group's Daily Values, and the calorie cross-check.</div>
          {asked && (
            <div className="fda-loraa-answer">
              <div className="fda-loraa-q"><Icon name="help-circle" size={13} /> {asked.q}</div>
              <div className="fda-loraa-a"><FdaLoraaLogo /><p>{asked.a}</p></div>
            </div>
          )}
          <div className="fda-loraa-qs">
            {QS.map((it) => <button key={it.q} className={`fda-loraa-qbtn ${asked && asked.q === it.q ? "on" : ""}`} onClick={() => setAsked(it)}>{it.q}</button>)}
          </div>
          <div className="fda-loraa-disc"><Icon name="info" size={11} /> Decision-support only, final FDA sign-off stays with your regulatory team.</div>
        </div>
      )}
    </div>
  );
}

/* ── §23 FDA Claims tab ── */
function FdaClaims({ recipe, profile }) {
  const { toast } = useApp();
  const [removed, setRemoved] = useFdaState([]);
  const ids = (typeof CLAIM_DEFS !== "undefined") ? CLAIM_DEFS.map((c) => c.id).filter((id) => !removed.includes(id)) : [];
  const res = (typeof claimValidateSet === "function") ? claimValidateSet(ids, profile, {}) : { results: [] };
  const meta = (typeof CLAIM_STATUS_META !== "undefined") ? CLAIM_STATUS_META : {};
  const order = { eligible: 0, warning: 1, restricted: 2, failed: 3 };
  const rows = (res.results || []).slice().sort((a, b) => (order[a.status] ?? 9) - (order[b.status] ?? 9));
  const icon = (s) => s === "eligible" ? "check-circle-2" : s === "warning" ? "alert-triangle" : "x-circle";
  return (
    <div className="fda-claims-tab">
      <div className="fda-exp-h"><Icon name="badge-check" size={15} /> Nutrient content claims <span className="fda-exp-sub">Evaluated live against this serving, 21 CFR 101.13/101.54</span></div>
      <div className="fda-claims-list">
        {rows.map((c) => (
          <div key={c.id} className={`fda-claim ${c.status}`}>
            <Icon name={icon(c.status)} size={15} />
            <div className="fda-claim-body">
              <div className="fda-claim-top"><span className="fda-claim-nm">{c.label}</span><span className={`pill ${c.status === "eligible" ? "success" : c.status === "warning" ? "warning" : "danger"}`} style={{ fontSize: 10 }}>{(meta[c.status] || {}).label || c.status}</span></div>
              <div className="fda-claim-why"><b>Why:</b> {c.message}</div>
              {c.status !== "eligible" && <div className="fda-claim-fix"><Icon name="wrench" size={11} /> <span><b>How to fix:</b> {fdaClaimFix(c)}</span></div>}
              {c.status !== "eligible" && (
                <div className="fda-claim-apply">
                  <button className="btn secondary sm" onClick={() => { setRemoved((r) => [...r, c.id]); toast(`"${c.label}" removed from the label`); }}><Icon name="trash-2" size={12} /> Remove claim from label</button>
                </div>
              )}
            </div>
          </div>
        ))}
        {rows.length === 0 && <div className="ls-hint">No claim definitions available.</div>}
      </div>
      {typeof CLAIM_DISCLAIMER !== "undefined" && <div className="fda-claims-disc"><Icon name="info" size={11} /> {CLAIM_DISCLAIMER}</div>}
    </div>
  );
}

/* ── §14 Validation Center ── */
function FdaValidationCenter({ validation, profile, recipe, ageGroup, servingG, role }) {
  return (
    <div className="fda-val">
      <div className={`fda-val-banner ${validation.status}`}>
        <Icon name={validation.status === "pass" ? "shield-check" : "shield-alert"} size={18} />
        <div><b>{validation.status === "pass" ? "All FDA checks pass" : validation.status === "warning" ? "Review needed before publishing" : "Blocking errors found"}</b>
          <span>{validation.pass} pass · {validation.warn} warning · {validation.fail} fail, each mapped to a regulation.</span></div>
      </div>
      <div className="fda-val-list">
        {validation.items.map((it) => (
          <div key={it.regKey} className={`fda-val-item ${it.state}`}>
            <Icon name={it.state === "pass" ? "check-circle-2" : it.state === "warning" ? "alert-triangle" : "x-circle"} size={15} />
            <div className="fda-val-body">
              <div className="fda-val-top"><span className="fda-val-title">{it.title}</span><span className="fda-val-reg">{it.reg}</span></div>
              <div className="fda-val-detail">{it.detail}</div>
              <div className="fda-val-kb"><Icon name="book-open" size={11} /> {it.body}</div>
            </div>
          </div>
        ))}
      </div>

      <FdaTransparency validation={validation} profile={profile} recipe={recipe} ageGroup={ageGroup} servingG={servingG} role={role} />
    </div>
  );
}

/* ── DV Transparency & Calculation Breakdown (review-only, never on the printed label) ── */
function FdaTransparency({ validation, profile, recipe, ageGroup, servingG, role }) {
  const [openDv, setOpenDv] = useFdaState(true);
  const [openAudit, setOpenAudit] = useFdaState(false);
  const [openCal, setOpenCal] = useFdaState(false);
  const [compare, setCompare] = useFdaState(false);
  const [calcRow, setCalcRow] = useFdaState(null);
  const ag = ageGroup || "adult";
  const agLabel = ag === "adult" ? "Adult Nutrition Facts" : (FDA_KIDS_DV[ag] || {}).label + " Nutrition Facts";
  const dvRows = fdaDvProfile(ag);
  const data = fdaNftRows(profile, recipe, true, ag);
  const dvKeyMap = { fat: "fat_g", saturated: "fat_saturated_g", cholesterol: "cholesterol_mg", sodium: "sodium_mg", carbohydrate: "carbohydrate_g", fibre: "fibre_g", added: "added_sugars_g", protein: "protein_g", vitamin_d: "vitamin_d_mcg", calcium: "calcium_mg", iron: "iron_mg", potassium: "potassium_mg" };
  const cal = validation.calorieCheck || { calc: 0, decl: 0, off: false };
  const who = (typeof currentUser === "function" && window.__role) ? currentUser(window.__role).name : "Reviewer";
  const now = new Date().toISOString().slice(0, 16).replace("T", " ");
  const auditRows = [
    { k: "Population", v: ag === "adult" ? "Adult" : (FDA_KIDS_DV[ag] || {}).label, state: "info" },
    { k: "Generated", v: now, state: "info" },
    { k: "Generated By", v: who, state: "info" },
    ...validation.items.map((it) => ({ k: it.title, v: it.state.toUpperCase(), state: it.state })),
  ];
  const cmp = fdaProfileComparison();

  const Section = ({ id, icon, title, open, set, children, badge }) => (
    <div className="fda-tp-card">
      <button className="fda-tp-head" onClick={() => set(!open)}>
        <Icon name={icon} size={14} /> <span>{title}</span>
        {badge && <span className={`pill ${badge.tone}`} style={{ fontSize: 10 }}>{badge.text}</span>}
        <Icon name={open ? "chevron-up" : "chevron-down"} size={15} className="fda-tp-chev" />
      </button>
      {open && <div className="fda-tp-body">{children}</div>}
    </div>
  );

  return (
    <div className="fda-tp">
      <div className="fda-tp-note"><Icon name="eye" size={12} /> Transparency &amp; audit, for reviewers, QA, and auditors. None of this appears on the printed FDA label.</div>

      <Section id="dv" icon="table-2" title="FDA Daily Value Profile" open={openDv} set={setOpenDv}>
        <div className="fda-tp-meta">
          <div><span>Selected population</span><b>{agLabel}</b></div>
          <div><span>Daily Value source</span><b>{FDA_DV_VERSION.replace("_", " ")} Daily Values</b></div>
          <div><span>Profile version</span><b>v1.0</b></div>
        </div>
        <div className="fda-tp-dvgrid">
          {dvRows.map((d) => <div key={d.label} className="fda-tp-dv"><span>{d.label}</span><b>{d.value}{d.unit}</b></div>)}
        </div>
        <button className="fda-tp-link" onClick={() => setCompare(true)}><Icon name="columns-3" size={13} /> Compare population profiles</button>
      </Section>

      <Section id="nutr" icon="calculator" title="Nutrient %DV Calculation Breakdown" open={true} set={() => {}}>
        <div className="fda-tp-calclist">
          {data.rows.filter((r) => r.dv != null).concat(data.micros).map((r) => {
            const dk = dvKeyMap[r.k]; const b = dk ? fdaCalcBreakdown(r.amount, dk, ag) : null;
            return (
              <button key={r.k} className="fda-tp-calc" onClick={() => b && setCalcRow({ ...b, label: r.label, amount: r.amount, unit: r.unit })}>
                <span className="fda-tp-calc-nm">{r.label}</span>
                <span className="fda-tp-calc-amt">{r.amount}{r.unit}</span>
                <span className="fda-tp-calc-dv">{r.dv}%</span>
                <Icon name="chevron-right" size={13} />
              </button>
            );
          })}
        </div>
      </Section>

      <Section id="cal" icon="flame" title="Calories Calculation" open={openCal} set={setOpenCal} badge={{ tone: cal.off ? "warning" : "success", text: cal.off ? "VARIANCE" : "PASS" }}>
        <div className="fda-tp-cal">
          <div className="fda-tp-cal-row"><span>Fat</span><span>{Math.round(profile.fat_g)}g × 9</span><b>{Math.round(profile.fat_g * 9)}</b></div>
          <div className="fda-tp-cal-row"><span>Carbohydrates</span><span>{Math.round(profile.carbohydrate_g)}g × 4</span><b>{Math.round(profile.carbohydrate_g * 4)}</b></div>
          <div className="fda-tp-cal-row"><span>Protein</span><span>{Math.round(profile.protein_g)}g × 4</span><b>{Math.round(profile.protein_g * 4)}</b></div>
          <div className="fda-tp-cal-row total"><span>Calculated</span><span></span><b>{cal.calc}</b></div>
          <div className="fda-tp-cal-row"><span>Declared</span><span></span><b>{cal.decl}</b></div>
          <div className="fda-tp-cal-row"><span>Variance</span><span></span><b>{Math.abs(cal.calc - cal.decl)}</b></div>
          <div className={`fda-tp-cal-verdict ${cal.off ? "warn" : "ok"}`}><Icon name={cal.off ? "alert-triangle" : "check-circle-2"} size={13} /> FDA tolerance (±10%): {cal.off ? "VARIANCE, review macros" : "PASS"}</div>
        </div>
      </Section>

      <Section id="audit" icon="file-clock" title="Label Audit Trail" open={openAudit} set={setOpenAudit}>
        <div className="fda-tp-audit">
          {auditRows.map((r, i) => (
            <div key={i} className="fda-tp-audit-row">
              <span>{r.k}</span>
              {r.state === "info" ? <b>{r.v}</b> : <span className={`pill ${r.state === "pass" ? "success" : r.state === "warning" ? "warning" : "danger"}`} style={{ fontSize: 10 }}>{r.v}</span>}
            </div>
          ))}
        </div>
      </Section>

      {calcRow && (
        <div className="fda-modal-scrim" onClick={() => setCalcRow(null)}>
          <div className="fda-modal" onClick={(e) => e.stopPropagation()}>
            <div className="fda-modal-h"><span><Icon name="calculator" size={15} /> View Calculation</span><button className="icon-btn" onClick={() => setCalcRow(null)}><Icon name="x" size={17} /></button></div>
            <div className="fda-modal-body">
              <div className="fda-modal-row"><span>Nutrient</span><b>{calcRow.label}</b></div>
              <div className="fda-modal-row"><span>Amount per serving</span><b>{calcRow.amount}{calcRow.unit}</b></div>
              <div className="fda-modal-row"><span>FDA Daily Value</span><b>{calcRow.dv}{calcRow.unit}</b></div>
              <div className="fda-modal-formula">{calcRow.formula}</div>
              <div className="fda-modal-row"><span>Result</span><b>{calcRow.raw}%</b></div>
              <div className="fda-modal-row"><span>Rounded</span><b>{calcRow.rounded}%</b></div>
              <div className="fda-modal-status"><Icon name="check-circle-2" size={13} /> {calcRow.status}</div>
            </div>
          </div>
        </div>
      )}

      {compare && (
        <div className="fda-modal-scrim" onClick={() => setCompare(false)}>
          <div className="fda-modal wide" onClick={(e) => e.stopPropagation()}>
            <div className="fda-modal-h"><span><Icon name="columns-3" size={15} /> Population Profile Comparison</span><button className="icon-btn" onClick={() => setCompare(false)}><Icon name="x" size={17} /></button></div>
            <div className="fda-modal-body">
              <table className="fda-cmp-table">
                <thead><tr><th>Nutrient</th>{cmp.groups.map((g) => <th key={g} className={g.includes(ag === "adult" ? "Adult" : (FDA_KIDS_DV[ag] || {}).label) ? "on" : ""}>{g}</th>)}</tr></thead>
                <tbody>
                  {cmp.rows.map((r) => <tr key={r.label}><td>{r.label}</td>{r.values.map((v, i) => <td key={i}>{v}{r.unit}</td>)}</tr>)}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

/* ── §10/§19 Export + Electronic Signatures ── */
function FdaExport({ recipe, profile, servings, rounded, format, validation, sigs, setSigs, role, toast }) {
  const [sigAction, setSigAction] = useFdaState("Approve");
  const [sigReason, setSigReason] = useFdaState("");
  const who = (typeof currentUser === "function" && window.__role) ? currentUser(window.__role).name : "You";
  const data = fdaNftRows(profile, recipe, rounded);

  const dl = (name, blob) => { const u = URL.createObjectURL(blob); const a = document.createElement("a"); a.href = u; a.download = name; document.body.appendChild(a); a.click(); a.remove(); setTimeout(() => URL.revokeObjectURL(u), 4000); };
  const fname = (recipe.name || "product").replace(/\s+/g, "-").toLowerCase();
  const audit = (fmt) => { toast(`FDA label exported (${fmt})`); };

  const buildSvg = () => {
    const lines = [];
    let y = 30;
    lines.push(`<text x="10" y="${y}" font-size="26" font-weight="800" font-family="Helvetica">Nutrition Facts</text>`); y += 22;
    lines.push(`<text x="10" y="${y}" font-size="12" font-family="Helvetica">${servings} servings per container</text>`); y += 18;
    lines.push(`<text x="10" y="${y}" font-size="13" font-weight="700" font-family="Helvetica">Serving size ${Math.round(profile.servingG)}g</text>`); y += 8;
    lines.push(`<rect x="8" y="${y}" width="264" height="6" fill="#000"/>`); y += 26;
    lines.push(`<text x="10" y="${y}" font-size="22" font-weight="800" font-family="Helvetica">Calories</text><text x="262" y="${y}" font-size="26" font-weight="800" text-anchor="end" font-family="Helvetica">${data.calories}</text>`); y += 10;
    lines.push(`<rect x="8" y="${y}" width="264" height="3" fill="#000"/>`); y += 18;
    data.rows.concat(data.micros).forEach((r) => {
      lines.push(`<text x="${10 + (r.indent || 0) * 14}" y="${y}" font-size="12" font-family="Helvetica">${r.label} ${r.amount == null ? "" : r.amount + (r.unit || "")}</text>${r.dv != null ? `<text x="262" y="${y}" font-size="12" font-weight="700" text-anchor="end" font-family="Helvetica">${r.dv}%</text>` : ""}`);
      lines.push(`<line x1="8" y1="${y + 4}" x2="272" y2="${y + 4}" stroke="#000" stroke-width="0.5"/>`); y += 18;
    });
    const h = y + 10;
    return `<svg xmlns="http://www.w3.org/2000/svg" width="280" height="${h}" viewBox="0 0 280 ${h}"><rect x="1" y="1" width="278" height="${h - 2}" fill="#fff" stroke="#000" stroke-width="2"/>${lines.join("")}</svg>`;
  };
  const exportJson = () => { dl(`fda-${fname}.json`, new Blob([JSON.stringify({ product: recipe.name, servingG: profile.servingG, servingsPerContainer: servings, dvVersion: FDA_DV_VERSION, calories: data.calories, nutrients: data.rows, micronutrients: data.micros }, null, 2)], { type: "application/json" })); audit("JSON"); };
  const exportSvg = () => { dl(`fda-${fname}.svg`, new Blob([buildSvg()], { type: "image/svg+xml" })); audit("SVG"); };
  const exportPng = () => {
    const svg = buildSvg(); const img = new Image();
    img.onload = () => { const c = document.createElement("canvas"); c.width = 560; c.height = img.height * (560 / img.width); const ctx = c.getContext("2d"); ctx.fillStyle = "#fff"; ctx.fillRect(0, 0, c.width, c.height); ctx.drawImage(img, 0, 0, c.width, c.height); c.toBlob((b) => { dl(`fda-${fname}.png`, b); audit("PNG"); }); };
    img.src = "data:image/svg+xml;base64," + btoa(unescape(encodeURIComponent(svg)));
  };
  const exportPdf = () => { exportFdaHtml(recipe, profile, servings, rounded, format); audit("PDF"); };
  const exportQr = () => {
    const stage = document.getElementById("fda-qr-holder"); if (!stage) return;
    stage.innerHTML = ""; if (window.QRCode) new window.QRCode(stage, { text: `https://nutridms.com/public/labels/${recipe.id}`, width: 150, height: 150, colorDark: "#15281c", colorLight: "#fff" });
    audit("QR");
  };

  const addSig = () => {
    if (validation.fail) { toast("Resolve blocking errors before signing"); return; }
    const rec = { action: sigAction, who, ts: new Date().toLocaleString(), reason: sigReason || "—" };
    setSigs((s) => [rec, ...s]); setSigReason("");
    toast(`${sigAction} signed by ${who}`);
  };

  const FMTS = [
    { k: "PDF", icon: "file-text", fn: exportPdf, cap: "Print-ready panel" },
    { k: "SVG", icon: "shapes", fn: exportSvg, cap: "Vector artwork" },
    { k: "PNG", icon: "image", fn: exportPng, cap: "Raster image" },
    { k: "JSON", icon: "braces", fn: exportJson, cap: "Structured data" },
    { k: "QR", icon: "qr-code", fn: exportQr, cap: "Public label URL" },
  ];
  return (
    <div className="fda-export">
      <div className="fda-exp-card">
        <div className="fda-exp-h"><Icon name="download" size={15} /> Export label · all outputs versioned</div>
        <div className="fda-exp-grid">
          {FMTS.map((f) => <button key={f.k} className="fda-exp-btn" onClick={f.fn}><Icon name={f.icon} size={16} /><span>{f.k}</span><small>{f.cap}</small></button>)}
        </div>
        <div id="fda-qr-holder" className="fda-qr-holder" />
      </div>

      <div className="fda-exp-card">
        <div className="fda-exp-h"><Icon name="pen-line" size={15} /> Electronic signatures <span className="fda-exp-sub">21 CFR Part 11, captures user, date, time &amp; reason</span></div>
        {validation.fail ? <div className="fda-sig-block"><Icon name="lock" size={13} /> {validation.fail} blocking error(s) must be resolved before signing.</div> : null}
        <div className="fda-sig-form">
          <select value={sigAction} onChange={(e) => setSigAction(e.target.value)}>{["Review", "Approve", "Reject", "Publish"].map((a) => <option key={a}>{a}</option>)}</select>
          <input value={sigReason} onChange={(e) => setSigReason(e.target.value)} placeholder="Reason / comments (optional)" />
          <button className="btn primary sm" disabled={!!validation.fail} onClick={addSig}><Icon name="pen-line" size={14} /> Sign as {who}</button>
        </div>
        <div className="fda-sig-list">
          {sigs.length === 0 && <div className="ls-hint">No signatures captured yet.</div>}
          {sigs.map((s, i) => (
            <div key={i} className={`fda-sig-row ${s.action.toLowerCase()}`}>
              <Icon name={s.action === "Reject" ? "x-circle" : s.action === "Publish" ? "globe" : s.action === "Approve" ? "check-circle-2" : "eye"} size={14} />
              <div><b>{s.action}</b>, {s.who}<span>{s.ts} · {s.reason}</span></div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function FdaVersions({ recipe, profile, servingG, servings, rounded, validation, allergensReviewed, role, toast }) {
  const LV = window.LabelVersions;
  const [tick, setTick] = useFdaState(0);
  const [sel, setSel] = useFdaState([]);
  if (!LV) return <div className="fda-empty">Version history unavailable.</div>;
  const list = LV.versions("FDA", recipe.id);
  const capture = () => {
    const data = fdaNftRows(profile, recipe, rounded);
    const rn = {}; (data.rows || []).forEach((r) => { if (r.amount != null) rn[r.label] = r.amount + (r.unit || ""); });
    LV.capture({
      jurisdiction: "FDA", recipeId: recipe.id, productName: recipe.name,
      ruleSetVersion: (typeof FDA_DV_VERSION !== "undefined" ? FDA_DV_VERSION.replace("_", " ") : "2016") + " DV",
      templateVersion: "v1.0", servingG: servingG, servingsPerContainer: servings,
      roundedNutrients: rn, allergens: recipe.allergens || [], claims: (recipe.claims || []),
      validation: { status: validation.status, items: validation.items || [] }, by: (typeof currentUser === "function" && window.__role) ? currentUser(window.__role).name : "You",
    });
    toast("Label version captured"); setTick((t) => t + 1);
  };
  const pick = (id) => setSel((s) => s.includes(id) ? s.filter((x) => x !== id) : [id, s[0]].filter(Boolean).slice(0, 2));
  const a = list.find((v) => v.id === sel[1]), b = list.find((v) => v.id === sel[0]);
  const changes = (a && b) ? LV.diff(a, b) : null;
  return (
    <div className="fda-versions">
      <div className="ps-cx-head" style={{ background: "var(--gray-50)", borderColor: "var(--gray-200)" }}>
        <div><b>Version history</b><span>Each capture is an immutable snapshot with a render checksum. Select two to compare, or download a regulatory report.</span></div>
        <button className="btn primary sm" onClick={capture}><Icon name="camera" size={14} /> Capture version</button>
      </div>
      {list.length === 0
        ? <div className="fda-empty" style={{ padding: 30, textAlign: "center", color: "var(--gray-500)" }}><Icon name="history" size={24} /><div style={{ marginTop: 8, fontWeight: 700 }}>No versions yet</div><div style={{ fontSize: 12.5 }}>Capture the current label to start the history.</div></div>
        : <div className="fda-ver-list">
            {list.map((v) => (
              <div key={v.id} className={"fda-ver-row" + (sel.includes(v.id) ? " on" : "")}>
                <label className="fda-ver-pick"><input type="checkbox" checked={sel.includes(v.id)} onChange={() => pick(v.id)} /></label>
                <span className="fda-ver-v">v{v.version}</span>
                <span className="fda-ver-meta">{new Date(v.at).toLocaleString()} · {v.by}</span>
                <span className={"pill " + (v.body.validation.status === "pass" ? "success" : v.body.validation.status === "fail" ? "error" : "warning")}>{v.body.validation.status}</span>
                <span className="fda-ver-chk">{v.checksum}</span>
                <span className="fda-ver-acts">
                  <button className="icon-btn" title="Download report (HTML)" onClick={() => LV.downloadReport(v, "Acme Foods", "html")}><Icon name="file-text" size={14} /></button>
                  <button className="icon-btn" title="Download report (JSON)" onClick={() => LV.downloadReport(v, "Acme Foods", "json")}><Icon name="braces" size={14} /></button>
                </span>
              </div>
            ))}
          </div>}
      {changes && (
        <div className="fda-ver-diff">
          <div className="ps-sec-h">Comparing v{a.version} → v{b.version}</div>
          {changes.length === 0
            ? <div className="fda-ver-nochange"><Icon name="check-circle-2" size={14} /> No differences between these versions.</div>
            : <table className="fda-cmp-table"><thead><tr><th>Field</th><th>v{a.version}</th><th>v{b.version}</th></tr></thead><tbody>
                {changes.map((c, i) => <tr key={i}><td><b>{c.group}</b> · {c.field}</td><td style={{ color: "#B23320" }}>{String(c.before) || "—"}</td><td style={{ color: "#1E7A49" }}>{String(c.after) || "—"}</td></tr>)}
              </tbody></table>}
        </div>
      )}
    </div>
  );
}

function exportFdaHtml(recipe, profile, servings, rounded, format) {
  const data = fdaNftRows(profile, recipe, rounded);
  const rows = data.rows.map((r) => `<div class="r ind${r.indent || 0} ${r.bold ? "b" : ""}"><span>${r.bold ? "<b>" + r.label + "</b>" : r.label} ${r.amount == null ? "—" : r.amount + (r.unit || "")}</span><span>${r.dv == null ? "" : r.dv + "%"}</span></div>`).join("");
  const micros = data.micros.map((r) => `<div class="r"><span>${r.label} ${r.amount}${r.unit}</span><span>${r.dv}%</span></div>`).join("");
  const html = `<!doctype html><html><head><meta charset="utf-8"><title>FDA Label, ${recipe.name}</title>
<style>body{font-family:Helvetica,Arial,sans-serif;padding:30px}.nft{width:280px;border:2px solid #000;padding:8px;font-size:12px}
.t{font-size:30px;font-weight:800;letter-spacing:-.5px}.sv{display:flex;justify-content:space-between;font-weight:700;border-bottom:8px solid #000;padding-bottom:3px}
.cal{display:flex;justify-content:space-between;align-items:flex-end;font-weight:800;border-bottom:4px solid #000}.cal b:last-child{font-size:30px}
.dvh{text-align:right;font-weight:700;border-bottom:1px solid #000;padding:2px 0}.r{display:flex;justify-content:space-between;border-bottom:1px solid #000;padding:2px 0}
.ind1 span:first-child{padding-left:16px}.ind2 span:first-child{padding-left:32px}.foot{font-size:9px;margin-top:4px}
.print{position:fixed;top:16px;right:16px;background:#1a52b8;color:#fff;border:0;border-radius:999px;padding:9px 16px;font-weight:700;cursor:pointer}@media print{.print{display:none}}</style></head>
<body><button class="print" onclick="window.print()">Print / Save PDF</button>
<div class="nft"><div class="t">Nutrition Facts</div><div>${servings} servings per container</div>
<div class="sv"><span>Serving size</span><span>${Math.round(profile.servingG)}g</span></div>
<div class="cal"><b>Calories</b><b>${data.calories}</b></div>
<div class="dvh">% Daily Value*</div>${rows}<div style="border-top:6px solid #000"></div>${micros}
<div class="foot">* The % Daily Value (DV) tells you how much a nutrient in a serving of food contributes to a daily diet. 2,000 calories a day is used for general nutrition advice.</div></div></body></html>`;
  const url = URL.createObjectURL(new Blob([html], { type: "text/html" }));
  const a = document.createElement("a"); a.href = url; a.download = `fda-label-${(recipe.name || "product").replace(/\s+/g, "-").toLowerCase()}.html`;
  document.body.appendChild(a); a.click(); a.remove(); setTimeout(() => URL.revokeObjectURL(url), 4000);
}

if (typeof window !== "undefined") Object.assign(window, { FdaLabelStudio, FdaNutritionFacts, FdaSupplementFacts, FdaMenuLabel, FdaClaims, FdaValidationCenter, FdaTransparency, FdaExport, FdaVersions });
