/* NutriDMS, NAFDAC Label Studio (Nigeria)
   Chunk 1: Nutrition Information panel + ingredient/allergen declaration +
   claim validation + compliance score. Source toggle + Ask Loraa.
   Shares the recipe/nutrition source with FDA/CFIA. */

const { useState: useNafState, useMemo: useNafMemo, useEffect: useNafEffect } = React;

/* ── NAFDAC Nutrition Information panel ── */
function NafdacPanel({ recipe, nutr, zoom, format, micros, water, fat, servingG }) {
  const fmt = format || { layout: "standard", theme: { bg: "#FBF7EF", border: "#E7C9A6", bar: "#2f6b18", text: "#1a2218" } };
  const th = fmt.theme;
  const dark = th.text === "#fff";
  const R = (l, v, sub) => (<div className={`naf-row ${sub ? "sub" : ""}`}><span>{l}</span><b>{v}</b></div>);
  const wrapStyle = { transform: `scale(${zoom || 1})`, background: "#fff", borderColor: th.bar, color: "#111" };
  const head = (
    <div className="naf-panel-head" style={{ background: th.bar, color: dark || th.bar !== "#2f6b18" ? "#fff" : "#fff" }}>
      <div className="naf-panel-h2">Nutrition Information</div>
      <div className="naf-panel-basis2">{nutr.unitLabel}</div>
    </div>
  );
  const core = (
    <>
      {R("Energy", `${nutr.energy_kj}kJ / ${nutr.energy_kcal}kcal`)}
      {R("Protein", `${nutr.protein_g}g`)}
      {R("Fat", `${nutr.fat_g}g`)}
      {R("of which saturates", `${nutr.fat_saturated_g}g`, true)}
      {R("trans fat", `${nutr.fat_trans_g}g`, true)}
      {R("Carbohydrate", `${nutr.carbohydrate_g}g`)}
      {R("of which sugars", `${nutr.sugars_g}g`, true)}
      {R("Fibre", `${nutr.fibre_g}g`)}
      {R("Salt", `${nutr.salt_g}g`)}
    </>
  );

  // ── Fortified / Supplement: STANDARD table first, then vitamins/minerals appended below ──
  if ((fmt.layout === "fortified" || fmt.layout === "supplement") && micros) {
    const showBenefit = fmt.layout === "fortified";
    return (
      <div className="naf-panel naf-panel-fort" style={wrapStyle}>
        {head}
        {core}
        <div className="naf-rule thin" style={{ background: th.bar }} />
        <div className="naf-vit-h">Vitamins &amp; Minerals</div>
        <table className="naf-vtable">
          <thead><tr style={{ background: th.bar, color: "#fff" }}><th>Nutrient</th><th>Per 100g</th><th>Per serve<br /><small>{servingG || 20}g</small></th><th>% NRV</th>{showBenefit && <th>Known benefits</th>}</tr></thead>
          <tbody>
            {micros.map((m, i) => <tr key={m.code}><td>{m.label}</td><td>{m.per100}{m.unit}</td><td>{m.perServe}{m.unit}</td><td>{m.nrvPct}%</td>{showBenefit && (i % 4 === 0 ? <td rowSpan={Math.min(4, micros.length - i)} className="naf-vbenefit">{m.benefit}</td> : null)}</tr>)}
          </tbody>
        </table>
        <div className="naf-panel-foot">Per serve = per 100g × serving ÷ 100 · %NRV vs Nutrient Reference Values · Vitamins/minerals below 5% NRV are not declared.</div>
      </div>
    );
  }
  // ── Oil & Fat: fatty acid profile ──
  if (fmt.layout === "oil" && fat) {
    return (
      <div className="naf-panel" style={wrapStyle}>
        {head}
        {R("Energy", `${nutr.energy_kj}kJ / ${nutr.energy_kcal}kcal`)}
        {R("Total Fat", `${fat.total}g`)}
        {R("Saturated Fat", `${fat.saturated}g`, true)}
        {R("Monounsaturated Fat", `${round1(fat.mono)}g`, true)}
        {R("Polyunsaturated Fat", `${round1(fat.poly)}g`, true)}
        {R("Trans Fat", `${fat.trans}g`, true)}
        <div className="naf-rule thin" style={{ background: th.bar }} />
        {R("Cholesterol", `${fat.cholesterol}mg`)}
        {R("Salt", `${nutr.salt_g}g`)}
        <div className="naf-panel-foot">Energy from fat = fat g × 9 kcal · kJ = kcal × 4.184 · Fatty-acid breakdown required for oils & fats.</div>
      </div>
    );
  }
  // ── Bottled Water: mineral analysis, no nutrition table ──
  if (fmt.layout === "water" && water) {
    return (
      <div className="naf-panel" style={wrapStyle}>
        <div className="naf-panel-head" style={{ background: th.bar, color: "#fff" }}><div className="naf-panel-h2">Typical Analysis</div><div className="naf-panel-basis2">mg/L unless stated</div></div>
        {water.map((m) => <div key={m.label} className="naf-row"><span>{m.label}</span><b>{m.v}{m.unit ? " " + m.unit : ""}</b></div>)}
        <div className="naf-panel-foot">Mineral analysis per litre. Bottled water does not require a standard nutrition facts table.</div>
      </div>
    );
  }
  // ── Beverage / Dairy / Standard / Noodles / Prepared: core table ──
  // ── Beverage / Dairy / Standard / Noodles / Prepared: authentic Nutrition Facts layout ──
  const DV = { fat_g: 78, fat_saturated_g: 20, cholesterol_mg: 300, sodium_mg: 2300, carbohydrate_g: 275, fibre_g: 28, added_sugars_g: 50, calcium_mg: 1300, iron_mg: 18, potassium_mg: 4700 };
  const dv = (v, k) => DV[k] && v != null ? Math.round((v / DV[k]) * 100) + "%" : "";
  const added = round1((nutr.sugars_g || 0) * 0.55);
  const DRow = (l, v, pct, opt) => (
    <div className={`nf-row ${opt && opt.bold ? "b" : ""} ${opt && opt.ind ? "ind" + opt.ind : ""}`}>
      <span className="nf-l">{opt && opt.bold ? <strong>{l}</strong> : l} {v}</span><span className="nf-dv">{pct}</span>
    </div>
  );
  return (
    <div className="nf-panel" style={{ transform: `scale(${zoom || 1})`, borderColor: "#000" }}>
      <div className="nf-title">Nutrition Information</div>
      <div className="nf-serv-size"><strong>{nutr.unitLabel}</strong><strong>{Math.round(nutr.servingG)}{(fmt.basis === "100ml" || fmt.layout === "beverage" || fmt.layout === "dairy") ? "ml" : "g"} / serving</strong></div>
      <div className="nf-bar-lg" />
      <div className="nf-dvhead">% Daily Value*</div>
      {DRow("Energy", `${nutr.energy_kj}kJ / ${nutr.energy_kcal}kcal`, "", { bold: true })}
      {DRow("Protein", `${nutr.protein_g}g`, "", { bold: true })}
      {DRow("Total Fat", `${nutr.fat_g}g`, dv(nutr.fat_g, "fat_g"), { bold: true })}
      {DRow("Saturated Fat", `${nutr.fat_saturated_g}g`, dv(nutr.fat_saturated_g, "fat_saturated_g"), { ind: 1 })}
      {DRow("Trans Fat", `${nutr.fat_trans_g}g`, "", { ind: 1 })}
      {DRow("Cholesterol", `${nutr.cholesterol_mg}mg`, dv(nutr.cholesterol_mg, "cholesterol_mg"), { bold: true })}
      {DRow("Total Carbohydrate", `${nutr.carbohydrate_g}g`, dv(nutr.carbohydrate_g, "carbohydrate_g"), { bold: true })}
      {DRow("Dietary Fibre", `${nutr.fibre_g}g`, dv(nutr.fibre_g, "fibre_g"), { ind: 1 })}
      {DRow("Total Sugars", `${nutr.sugars_g}g`, "", { ind: 1 })}
      {DRow("Includes Added Sugars", `${added}g`, dv(added, "added_sugars_g"), { ind: 2 })}
      {DRow("Sodium", `${nutr.sodium_mg}mg`, dv(nutr.sodium_mg, "sodium_mg"), { bold: true })}
      {DRow("Salt", `${nutr.salt_g}g`, "", { ind: 1 })}
      <div className="nf-bar-lg" />
      {DRow("Calcium", `${nutr.calcium_mg}mg`, dv(nutr.calcium_mg, "calcium_mg"))}
      {DRow("Iron", `${nutr.iron_mg}mg`, dv(nutr.iron_mg, "iron_mg"))}
      {(fmt.layout === "dairy" || fmt.layout === "beverage") && DRow("Potassium", `${nutr.potassium_mg}mg`, dv(nutr.potassium_mg, "potassium_mg"))}
      <div className="nf-bar-sm" />
      <div className="nf-foot">* % Daily Value. Energy: protein/carb 4kcal, fat 9kcal, fibre 2kcal · kJ = kcal × 4.184 · Salt = Sodium × 2.5.</div>
    </div>
  );
}

function NafdacLabelStudio() {
  const { role, toast } = useApp();
  const recipes = useNafMemo(() => (typeof RECIPES !== "undefined") ? RECIPES.filter((r) => r.status === "published" || r.status === "approved") : [], []);
  const ofAll = useNafMemo(() => (typeof ofLoad === "function") ? ofLoad() : [], []);
  const [source, setSource] = useNafState("recipe");
  const [recipeId, setRecipeId] = useNafState(recipes[0] ? recipes[0].id : null);
  const [zoom, setZoom] = useNafState(1);
  const [tab, setTab] = useNafState("nutrition");
  const recipe = recipes.find((r) => r.id === recipeId) || recipes[0];
  const [format, setFormat] = useNafState(() => (typeof nafdacSuggestFormat === "function" && recipe) ? nafdacSuggestFormat(recipe) : "standard_food");
  useNafEffect(() => { if (recipe && typeof nafdacSuggestFormat === "function") setFormat(nafdacSuggestFormat(recipe)); }, [recipeId]);
  const fmtDef = (NAFDAC_FORMATS.find((f) => f.id === format)) || NAFDAC_FORMATS[0];
  const basis = fmtDef.basis;
  const [details, setDetails] = useNafState(() => { try { return JSON.parse(localStorage.getItem("nutridms_nafdac_details_" + recipeId) || "{}"); } catch (e) { return {}; } });
  useNafEffect(() => { try { setDetails(JSON.parse(localStorage.getItem("nutridms_nafdac_details_" + recipeId) || "{}")); } catch (e) { setDetails({}); } }, [recipeId]);
  const setD = (k, v) => setDetails((d) => { const n = { ...d, [k]: v }; try { localStorage.setItem("nutridms_nafdac_details_" + recipeId, JSON.stringify(n)); } catch (e) {} return n; });

  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 = useNafMemo(() => {
    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 products</h3><p>Publish a recipe to generate a NAFDAC label.</p></div>;

  const ingredients = useNafMemo(() => nafdacIngredients(recipe), [recipe]);
  const declaration = nafdacDeclaration(ingredients);
  const allergens = nafdacAllergenScan(ingredients, []);
  const nutr = useNafMemo(() => nafdacNutrition(recipe, { basis }), [recipe, basis]);
  const nutr100g = useNafMemo(() => nafdacNutrition(recipe, { basis: "100g" }), [recipe]);

  // claim validation against declared diet tags
  const claimIds = useNafMemo(() => {
    const tags = (recipe.diet || []).join(" ").toLowerCase();
    const ids = [];
    if (/protein/.test(tags)) ids.push("high-protein");
    if (/fib/.test(tags)) ids.push("source-fibre");
    if (/low.?fat/.test(tags)) ids.push("low-fat");
    if (/low.?sugar|sugar.?free/.test(tags)) ids.push("low-sugar");
    if (/low.?salt|low.?sodium/.test(tags)) ids.push("low-salt");
    return ids.length ? ids : ["source-protein"];
  }, [recipe]);
  const claimsAll = claimIds.map((id) => nafdacValidateClaim(id, nutr100g)).filter(Boolean);
  const [hiddenClaims, setHiddenClaims] = useNafState([]);
  const removeClaim = (id) => { setHiddenClaims((h) => [...h, id]); if (toast) toast("Claim removed from label"); };
  const claims = claimsAll.filter((c) => !hiddenClaims.includes(c.id));

  // compliance score, full validator (reads label details); 100% gated on all critical fields
  const validation = useNafMemo(() => nafdacFullValidate({ recipe, ingredients, nutr100g, allergens, details, claims }), [recipe, ingredients, nutr100g, allergens, details, claims]);
  const score = validation.score;
  const scoreLabel = validation.verdict;
  const printLabel = () => {
    const html = nafdacLabelHtml(recipe, { ingredients, declaration, allergens, nutr, details, validation, template });
    const w = URL.createObjectURL(new Blob([html], { type: "text/html" }));
    const a = document.createElement("a"); a.href = w; a.download = `nafdac-label-${(recipe.name || "product").replace(/\s+/g, "-").toLowerCase()}.html`;
    document.body.appendChild(a); a.click(); a.remove(); setTimeout(() => URL.revokeObjectURL(w), 4000);
    toast("NAFDAC label exported, open & print");
  };

  return (
    <div className="ls fda-ls naf-ls">
      <div className="page-head">
        <div>
          <h1 className="page-title">NAFDAC Label Studio</h1>
          <p className="page-sub">Nigeria, NAFDAC Pre-Packaged Food (Labelling) Regulations 2022. Legally compliant labels only.</p>
        </div>
        <div className="ls-head-pills">
          <span className={`pill ${score >= 100 ? "success" : score >= 80 ? "warning" : "danger"}`}><Icon name="shield-check" size={13} /> {score}% · {scoreLabel}</span>
          <button className="btn primary sm" disabled={!validation.ready} title={validation.ready ? "" : "Resolve all critical fields before printing"} onClick={printLabel}><Icon name="printer" size={14} /> Print label</button>
        </div>
      </div>

      <div className="fda-legal-note"><Icon name="shield-check" size={13} /> Generates legally compliant NAFDAC labels. {validation.ready ? "All mandatory fields complete, ready to print." : `${validation.failed.length} mandatory field(s) outstanding, complete them in Label Details / Traceability before printing.`}</div>

      <div className="fda-source-seg" style={{ marginBottom: 4 }}>
        <button className={`fda-source-btn ${tab === "format" ? "on" : ""}`} onClick={() => setTab("format")}><Icon name="layout-template" size={13} /> Format &amp; Product Type</button>
        <button className={`fda-source-btn ${tab === "nutrition" ? "on" : ""}`} onClick={() => setTab("nutrition")}><Icon name="table-2" size={13} /> Nutrition Information</button>
        <button className={`fda-source-btn ${tab === "declaration" ? "on" : ""}`} onClick={() => setTab("declaration")}><Icon name="ruler" size={13} /> Nutrition Declaration</button>
        <button className={`fda-source-btn ${tab === "details" ? "on" : ""}`} onClick={() => setTab("details")}><Icon name="clipboard-list" size={13} /> Label Details</button>
        <button className={`fda-source-btn ${tab === "trace" ? "on" : ""}`} onClick={() => setTab("trace")}><Icon name="qr-code" size={13} /> Traceability &amp; Registration</button>
        <button className={`fda-source-btn ${tab === "preview" ? "on" : ""}`} onClick={() => setTab("preview")}><Icon name="eye" size={13} /> Package Preview</button>
        <button className={`fda-source-btn ${tab === "validate" ? "on" : ""}`} onClick={() => setTab("validate")}><Icon name="shield-check" size={13} /> Validator &amp; Report</button>
        <button className={`fda-source-btn ${tab === "ask" ? "on" : ""}`} onClick={() => setTab("ask")}><Icon name="lightbulb" size={13} /> Ask Loraa</button>
      </div>

      {tab === "ask" && <NafdacAsk />}
      {tab === "details" && <NafdacDetails recipe={recipe} details={details} setD={setD} />}
      {tab === "trace" && <NafdacTrace recipe={recipe} details={details} setD={setD} ingredients={ingredients} />}
      {tab === "validate" && <NafdacValidator recipe={recipe} details={details} ingredients={ingredients} nutr100g={nutr100g} allergens={allergens} claims={claims} role={role} toast={toast} />}
      {tab === "format" && <NafdacFormatTab recipe={recipe} format={format} setFormat={setFormat} suggested={nafdacSuggestFormat(recipe)} goPreview={() => setTab("preview")} />}
      {tab === "declaration" && <NafdacDeclaration recipe={recipe} nutr={nutr} nutr100g={nutr100g} claims={claims} fmtDef={fmtDef} details={details} setD={setD} onRemove={removeClaim} />}
      {tab === "preview" && <NafdacFullPreview recipe={recipe} nutr={nutr} fmtDef={fmtDef} details={details} ingredients={ingredients} declaration={declaration} allergens={allergens} validation={validation} micros={nafdacMicros(recipe, basis, nutr.servingG)} water={nafdacWaterAnalysis(recipe)} fat={nafdacFatProfile(nutr)} />}
      {tab === "nutrition" && (
      <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="layout-template" size={14} /> Label format</div>
            <select className="naf-fmt-select" value={format} onChange={(e) => setFormat(e.target.value)}>
              {NAFDAC_FORMATS.map((f) => <option key={f.id} value={f.id}>{f.name}</option>)}
            </select>
            <div className="naf-loraa-tip"><Icon name="lightbulb" size={12} /> Loraa suggests <b>{(NAFDAC_FORMATS.find((f) => f.id === nafdacSuggestFormat(recipe)) || {}).name}</b> for this product. Basis: <b>{basis === "100g" ? "per 100g" : basis === "100ml" ? "per 100ml" : "per serving"}</b> (set by format).</div>
            <div className="fda-zoom"><span>Zoom</span><input type="range" min="0.7" max="1.5" step="0.1" value={zoom} onChange={(e) => setZoom(Number(e.target.value))} /></div>
          </section>

          <section className="ls-card">
            <div className="ls-card-h"><Icon name="gauge" size={14} /> Compliance score</div>
            <div className={`naf-score ${score >= 100 ? "ok" : score >= 80 ? "warn" : "bad"}`}>
              <div className="naf-score-v">{score}</div>
              <div className="naf-score-l">{scoreLabel}</div>
            </div>
            <div className="naf-score-checks">
              {validation.checks.filter((c) => c.crit).slice(0, 16).map((c) => (
                <div key={c.id} className={`naf-check ${c.state}`}>
                  <Icon name={c.state === "pass" ? "check-circle-2" : c.state === "fail" ? "x-circle" : "alert-triangle"} size={13} /> {c.label}
                </div>
              ))}
            </div>
          </section>
        </aside>

        <main className="ls-center">
          <div className="naf-tmpl-bar">
            {NAFDAC_FORMATS.map((f) => <button key={f.id} className={`naf-tmpl-btn ${format === f.id ? "on" : ""}`} onClick={() => setFormat(f.id)} title={f.name}><Icon name={f.icon} size={14} /> {f.name}</button>)}
          </div>
          <div className="ls-stage"><div className="ls-stage-inner">
            <NafdacPanel recipe={recipe} nutr={nutr} zoom={zoom} format={fmtDef} micros={nafdacMicros(recipe, basis, nutr.servingG)} water={nafdacWaterAnalysis(recipe)} fat={nafdacFatProfile(nutr)} servingG={Math.round(nutr.servingG)} />
          </div></div>
        </main>

        <aside className="ls-right">
          <section className="ls-card">
            <div className="ls-card-h"><Icon name="list-ordered" size={14} /> Ingredient declaration</div>
            <div className="naf-decl"><b>Ingredients:</b> {declaration}.</div>
            <div className="naf-ing-table">
              {ingredients.map((i) => (
                <div key={i.id} className="naf-ing-row">
                  <span className="naf-ing-nm">{i.name}{i.allergen.length ? <span className="naf-ing-allg" title="Allergen">⚠</span> : null}{i.gmo ? <span className="naf-ing-gmo" title="GMO">GMO</span> : null}</span>
                  <span className="naf-ing-w">{i.weight_g}g</span>
                  <span className="naf-ing-pct">{i.percentage}%</span>
                </div>
              ))}
            </div>
          </section>

          <section className="ls-card">
            <div className="ls-card-h"><Icon name="alert-octagon" size={14} /> Allergen declaration</div>
            <div className={`naf-allg ${allergens.contains.length ? "has" : "none"}`}>{allergens.statement}</div>
            {allergens.mayContain && <div className="naf-allg may">{allergens.mayContain}</div>}
          </section>

          <section className="ls-card">
            <div className="ls-card-h"><Icon name="badge-check" size={14} /> Claim validation</div>
            <div className="naf-claims">
              {claims.map((c) => (
                <div key={c.id} className={`naf-claim ${c.status}`}>
                  <div className="naf-claim-top"><Icon name={c.status === "eligible" ? "check-circle-2" : "x-circle"} size={14} /> <span>{c.label}</span><span className={`pill ${c.status === "eligible" ? "success" : "danger"}`} style={{ fontSize: 10 }}>{c.status === "eligible" ? "Eligible" : "Not met"}</span></div>
                  <div className="naf-claim-why"><b>Why:</b> {c.why}</div>
                  {c.status !== "eligible" && <div className="fda-claim-fix"><Icon name="wrench" size={11} /> <span><b>How to fix:</b> {c.fix}</span></div>}
                  {c.status !== "eligible" && <button className="fda-claim-apply" onClick={() => removeClaim(c.id)}><Icon name="trash-2" size={12} /> Remove claim from label</button>}
                </div>
              ))}
            </div>
          </section>
        </aside>
      </div>
      )}
    </div>
  );
}

/* ── Chunk 2: Label Details (net content, dates, batch, storage, directions, origin) ── */
function NafdacDetails({ recipe, details, setD }) {
  const d = details || {};
  const pullSpec = () => {
    try {
      const offs = (typeof ofLoad === "function") ? ofLoad() : [];
      const off = offs.find((o) => o.single && o.single.recipeId === recipe.id) || offs.find((o) => o.id === recipe.id);
      const spec = off && typeof psGet === "function" ? psGet(off.id) : null;
      if (!spec) { if (window.__toast) window.__toast("No linked Product Specification found"); return; }
      const det = spec.details || {}, pk = spec.packaging || {}, st = spec.storage || {}, mf = spec.manufacturing || {};
      if (det.netWeightG) { setD("netValue", det.netWeightG); setD("netUnit", "g"); }
      if (det.countryOfOrigin) setD("originCountry", det.countryOfOrigin);
      if (mf.facilityName) setD("manufacturer", mf.facilityName);
      if (mf.countryOfManufacture && mf.countryOfManufacture !== det.countryOfOrigin) { setD("imported", true); }
      if (st.shelfLifeDays) setD("shelfLifeDays", st.shelfLifeDays);
      if (st.storageType) setD("storage", ({ ambient: "Store in a cool dry place.", refrigerated: "Keep refrigerated at 0-4°C.", frozen: "Keep frozen at -18°C." })[st.storageType] || "Store in a cool dry place.");
      if (window.__toast) window.__toast("Pulled packaging, storage & manufacturing from Product Specification");
    } catch (e) {}
  };
  const net = nafdacNetContent(d.netValue, d.netUnit || "g", d.drained);
  const computedExpiry = (d.mfgDate && d.shelfLifeDays) ? nafdacShelfLife(d.mfgDate, d.shelfLifeDays) : null;
  const dateChk = nafdacDateValid(d.mfgDate, d.expiry || computedExpiry);
  const batch = nafdacBatchCode(d.mfgDate, d.batchSeq || 1);
  const origin = nafdacOrigin(d.originCountry, d.imported, d.importer);
  return (
    <div className="naf-details">
      <div className="naf-m19-bar"><span><Icon name="link" size={12} /> One source of truth, reuse your Product Specification data.</span><button className="naf-mini-btn" onClick={pullSpec}><Icon name="download" size={11} /> Pull from Product Specification</button></div>
      <div className="naf-det-grid">
        <section className="ls-card">
          <div className="ls-card-h"><Icon name="scale" size={14} /> Net content</div>
          <div className="naf-field-row">
            <label className="ls-field"><span>Net quantity</span><input type="number" value={d.netValue || ""} onChange={(e) => setD("netValue", e.target.value)} placeholder="500" /></label>
            <label className="ls-field"><span>Unit</span><select value={d.netUnit || "g"} onChange={(e) => setD("netUnit", e.target.value)}>{["g", "kg", "ml", "L"].map((u) => <option key={u}>{u}</option>)}</select></label>
          </div>
          <label className="ls-field"><span>Drained weight (canned, optional)</span><input type="number" value={d.drained || ""} onChange={(e) => setD("drained", e.target.value)} placeholder="320" /></label>
          <div className={`naf-det-out ${net.valid ? "ok" : "bad"}`}>Net Content: {net.display}{net.drained ? ` · ${net.drainedDisplay}` : ""}{net.drained && !net.drainedValid ? " ⚠ drained must be ≤ net" : ""}</div>
        </section>

        <section className="ls-card">
          <div className="ls-card-h"><Icon name="calendar" size={14} /> Dates &amp; shelf life</div>
          <div className="naf-field-row">
            <label className="ls-field"><span>Manufacturing date</span><input type="date" value={d.mfgDate || ""} onChange={(e) => setD("mfgDate", e.target.value)} /></label>
            <label className="ls-field"><span>Shelf life (days)</span><input type="number" value={d.shelfLifeDays || ""} onChange={(e) => setD("shelfLifeDays", e.target.value)} placeholder="180" /></label>
          </div>
          <label className="ls-field"><span>Best before / Expiry</span><input type="date" value={d.expiry || computedExpiry || ""} onChange={(e) => setD("expiry", e.target.value)} /></label>
          {computedExpiry && <div className="naf-det-out ok">Auto-computed expiry: {nafdacFmtDate(computedExpiry)} (mfg + {d.shelfLifeDays} days){!d.expiry ? ", applied" : ""} {d.expiry !== computedExpiry && <button className="naf-mini-btn" onClick={() => setD("expiry", computedExpiry)}>Use this</button>}</div>}
          <div className={`naf-det-out ${dateChk.valid ? "ok" : "bad"}`}>{dateChk.reason}{dateChk.valid ? ` · MFG ${nafdacFmtDate(d.mfgDate)} → EXP ${nafdacFmtDate(d.expiry || computedExpiry)}` : ""}</div>
        </section>

        <section className="ls-card">
          <div className="ls-card-h"><Icon name="building-2" size={14} /> Manufacturer / responsible party</div>
          <label className="ls-field"><span>Manufacturer name</span><input value={d.manufacturer || ""} onChange={(e) => setD("manufacturer", e.target.value)} placeholder="FreshLife Foods Ltd." /></label>
          <label className="ls-field"><span>Manufacturer address</span><input value={d.manufacturerAddr || ""} onChange={(e) => setD("manufacturerAddr", e.target.value)} placeholder="12 Industrial Ave, Lagos, Nigeria" /></label>
          <label className="naf-toggle"><input type="checkbox" checked={d.english !== false} onChange={(e) => setD("english", e.target.checked)} /> Declarations are in English (NAFDAC mandatory)</label>
        </section>

        <section className="ls-card">
          <div className="ls-card-h"><Icon name="hash" size={14} /> Batch code</div>
          <label className="ls-field"><span>Sequence number</span><input type="number" value={d.batchSeq || ""} onChange={(e) => setD("batchSeq", e.target.value)} placeholder="1" /></label>
          <div className="naf-det-out ok naf-batch">{batch}</div>
          <div className="ls-hint">Format: BT + YYMMDD (from mfg date) + 3-digit sequence.</div>
        </section>

        <section className="ls-card">
          <div className="ls-card-h"><Icon name="globe" size={14} /> Country of origin</div>
          <label className="naf-toggle"><input type="checkbox" checked={!!d.imported} onChange={(e) => setD("imported", e.target.checked)} /> Imported product</label>
          <label className="ls-field"><span>{d.imported ? "Made in (country)" : "Country"}</span><input value={d.originCountry || ""} onChange={(e) => setD("originCountry", e.target.value)} placeholder={d.imported ? "China" : "Nigeria"} /></label>
          {d.imported && <label className="ls-field"><span>Imported by</span><input value={d.importer || ""} onChange={(e) => setD("importer", e.target.value)} placeholder="ABC Nigeria Ltd." /></label>}
          <div className="naf-det-out ok">{origin}</div>
        </section>

        <section className="ls-card">
          <div className="ls-card-h"><Icon name="thermometer-snowflake" size={14} /> Storage instructions</div>
          <div className="naf-preset-chips">{NAFDAC_STORAGE.map((s) => <button key={s} className={`naf-chip ${d.storage === s ? "on" : ""}`} onClick={() => setD("storage", s)}>{s}</button>)}</div>
          <textarea className="naf-textarea" value={d.storage || ""} onChange={(e) => setD("storage", e.target.value)} placeholder="Store in a cool dry place." />
        </section>

        <section className="ls-card">
          <div className="ls-card-h"><Icon name="list-checks" size={14} /> Directions for use</div>
          <div className="naf-preset-chips">{NAFDAC_DIRECTIONS.map((s) => <button key={s} className={`naf-chip ${d.directions === s ? "on" : ""}`} onClick={() => setD("directions", s)}>{s}</button>)}</div>
          <textarea className="naf-textarea" value={d.directions || ""} onChange={(e) => setD("directions", e.target.value)} placeholder="Shake well before use." />
        </section>
      </div>
    </div>
  );
}

/* ── Chunk 3: Traceability (GS1/QR), NAFDAC registration, GMO, irradiation ── */
function NafdacTrace({ recipe, details, setD, ingredients }) {
  const d = details || {};
  const Barc = window.Barcode, QRc = window.QR;
  const prefix = d.gs1Prefix || "615" + String(nafdacHash(recipe.id) % 10000).padStart(4, "0"); // 615 = Nigeria GS1 prefix
  const gtinType = d.gtinType || "ean_13";
  const itemRef = d.itemRef || String(nafdacHash(recipe.name) % 1000).padStart(3, "0");
  const gtin = useNafMemo(() => {
    try {
      const body11 = (prefix + itemRef).replace(/\D/g, "").slice(0, 11).padEnd(11, "0");
      const body12 = (prefix + itemRef).replace(/\D/g, "").slice(0, 12).padEnd(12, "0");
      if (gtinType === "upc_a") return body11 + window.gs1CheckDigit(body11);
      return body12 + window.gs1CheckDigit(body12);
    } catch (e) { return ""; }
  }, [prefix, itemRef, gtinType]);
  const batch = nafdacBatchCode(d.mfgDate, d.batchSeq || 1);
  const reg = nafdacRegValid(d.regNo, d.regIssue, d.regExpiry);
  const gmo = nafdacGmoStatement(ingredients);
  const tracePayload = nafdacTracePayload({ gtin, batch, expiry: d.expiry, manufacturer: d.importer || "FreshLife Foods Ltd." });

  return (
    <div className="naf-details">
      <div className="naf-det-grid">
        <section className="ls-card">
          <div className="ls-card-h"><Icon name="scan-barcode" size={14} /> GS1 barcode</div>
          <div className="naf-field-row">
            <label className="ls-field"><span>Barcode type</span><select value={gtinType} onChange={(e) => setD("gtinType", e.target.value)}><option value="ean_13">EAN-13 (GTIN-13)</option><option value="upc_a">UPC-A (GTIN-12)</option></select></label>
            <label className="ls-field"><span>Item reference</span><input value={d.itemRef || itemRef} onChange={(e) => setD("itemRef", e.target.value.replace(/\D/g, ""))} /></label>
          </div>
          <div className="naf-barcode">{Barc ? <Barc type={gtinType} value={gtin} scale={2} height={14} /> : <div className="naf-det-out ok naf-batch">{gtin}</div>}</div>
          <div className="ls-hint">GTIN check digit auto-calculated (GS1 mod-10). Nigeria GS1 prefix 615.</div>
        </section>

        <section className="ls-card">
          <div className="ls-card-h"><Icon name="qr-code" size={14} /> QR traceability</div>
          <div className="naf-qr-wrap">{QRc ? <QRc value={tracePayload} size={120} /> : null}</div>
          <pre className="naf-trace-json">{JSON.stringify(JSON.parse(tracePayload), null, 1)}</pre>
        </section>

        <section className="ls-card">
          <div className="ls-card-h"><Icon name="badge-check" size={14} /> NAFDAC registration</div>
          <label className="ls-field"><span>NAFDAC registration number</span><input value={d.regNo || ""} onChange={(e) => setD("regNo", e.target.value)} placeholder="A7-1234L" /></label>
          <div className="naf-field-row">
            <label className="ls-field"><span>Issue date</span><input type="date" value={d.regIssue || ""} onChange={(e) => setD("regIssue", e.target.value)} /></label>
            <label className="ls-field"><span>Expiry date</span><input type="date" value={d.regExpiry || ""} onChange={(e) => setD("regExpiry", e.target.value)} /></label>
          </div>
          <div className={`naf-det-out ${reg.formatOk && !reg.expired ? "ok" : "bad"}`}>{reg.display}{!reg.formatOk ? " ⚠ check format (e.g. A7-1234L)" : reg.expired ? " ⚠ registration expired" : reg.expiryDisplay ? ` · valid to ${reg.expiryDisplay}` : ""}</div>
        </section>

        <section className="ls-card">
          <div className="ls-card-h"><Icon name="sprout" size={14} /> GMO &amp; irradiation</div>
          <div className={`naf-det-out ${gmo ? "bad" : "ok"}`}>{gmo || "No genetically modified ingredients detected."}</div>
          <label className="naf-toggle" style={{ marginTop: 10 }}><input type="checkbox" checked={!!d.irradiated} onChange={(e) => setD("irradiated", e.target.checked)} /> Treated with ionizing radiation</label>
          {d.irradiated && (
            <div className="naf-irr"><span className="naf-radura" title="Radura symbol">☢</span> <div><b>Treated With Ionizing Radiation</b><div className="ls-hint">Radura symbol must appear on the label (placeholder shown).</div></div></div>
          )}
        </section>
      </div>
    </div>
  );
}

/* ── Chunk 4: Compliance validator + registration readiness report + audit ── */
function NafdacValidator({ recipe, details, ingredients, nutr100g, allergens, claims, role, toast }) {
  const res = useNafMemo(() => nafdacFullValidate({ recipe, ingredients, nutr100g, allergens, details, claims }), [recipe, ingredients, nutr100g, allergens, details, claims]);
  const crit = res.checks.filter((c) => c.crit);
  const warn = res.checks.filter((c) => !c.crit);
  const exportReport = () => {
    const html = nafdacReportHtml(recipe, res, details, nutr100g, ingredients, allergens);
    const url = URL.createObjectURL(new Blob([html], { type: "text/html" }));
    const a = document.createElement("a"); a.href = url; a.download = `nafdac-registration-${(recipe.name || "product").replace(/\s+/g, "-").toLowerCase()}.html`;
    document.body.appendChild(a); a.click(); a.remove(); setTimeout(() => URL.revokeObjectURL(url), 4000);
    toast("Registration readiness report generated");
  };
  return (
    <div className="naf-details">
      <div className={`naf-rr-hero ${res.ready ? "ok" : "bad"}`}>
        <div className="naf-rr-score"><div className="naf-rr-num">{res.score}%</div><div className="naf-rr-verdict">{res.verdict}</div></div>
        <div className="naf-rr-stats">
          <div className="naf-rr-stat"><b>{res.passed.length}</b><span>Passed</span></div>
          <div className="naf-rr-stat warn"><b>{res.warned.length}</b><span>Warnings</span></div>
          <div className="naf-rr-stat bad"><b>{res.failed.length}</b><span>Errors</span></div>
          <div className="naf-rr-stat"><b>{res.total}</b><span>Checks</span></div>
        </div>
        <div className="naf-rr-ready">
          <Icon name={res.ready ? "check-circle-2" : "x-circle"} size={16} /> Ready for registration: <b>{res.ready ? "YES" : "NO"}</b>
          <div className="naf-rr-actions">
            {(() => {
              const stKey = "nutridms_nafdac_pub_" + recipe.id;
              const cur = (() => { try { return localStorage.getItem(stKey) || ""; } catch (e) { return ""; } })();
              const canApprove = role === "manager" || role === "compliance" || role === "admin" || role === "super-admin";
              const who = (typeof currentUser === "function" && window.__role) ? currentUser(window.__role).name : "Reviewer";
              const stamp = (action, status) => { try { localStorage.setItem(stKey, status); } catch (e) {} toast(`${action} recorded locally`); };
              return (
                <>
                  {cur && <span className={`pill ${cur === "published" ? "success" : "warning"}`} style={{ fontSize: 10 }}>{cur === "published" ? "Published" : "Approved"}</span>}
                  <button className="btn secondary sm" disabled={!res.ready || !canApprove || cur === "approved" || cur === "published"} title={!canApprove ? "Manager / Compliance / Admin only" : !res.ready ? "Resolve critical fields first" : ""} onClick={() => stamp("Label approved", "approved")}><Icon name="stamp" size={14} /> Approve</button>
                  <button className="btn primary sm" disabled={!res.ready || !canApprove || cur === "published"} title={!canApprove ? "Manager / Compliance / Admin only" : ""} onClick={() => stamp("Label published", "published")}><Icon name="send" size={14} /> Publish</button>
                </>
              );
            })()}
            <button className="btn secondary sm" onClick={exportReport}><Icon name="file-text" size={14} /> Report (PDF)</button>
          </div>
        </div>
      </div>
      <div className="naf-det-grid">
        <section className="ls-card">
          <div className="ls-card-h"><Icon name="alert-octagon" size={14} /> Critical checks ({crit.filter(c=>c.state==="pass").length}/{crit.length})</div>
          <div className="naf-val-list">
            {crit.map((c) => <div key={c.id} className={`naf-vrow ${c.state}`}><Icon name={c.state === "pass" ? "check-circle-2" : "x-circle"} size={13} /> {c.label}</div>)}
          </div>
        </section>
        <section className="ls-card">
          <div className="ls-card-h"><Icon name="alert-triangle" size={14} /> Advisory checks ({warn.filter(c=>c.state==="pass").length}/{warn.length})</div>
          <div className="naf-val-list">
            {warn.map((c) => <div key={c.id} className={`naf-vrow ${c.state}`}><Icon name={c.state === "pass" ? "check-circle-2" : "alert-triangle"} size={13} /> {c.label}</div>)}
          </div>
        </section>
      </div>
    </div>
  );
}
/* Full printable NAFDAC label, auto-populates from every engine (Module 17). */
function nafdacLabelHtml(recipe, ctx) {
  const { ingredients, declaration, allergens, nutr, details, validation } = ctx;
  const d = details || {};
  const batch = nafdacBatchCode(d.mfgDate, d.batchSeq || 1);
  const expiry = d.expiry || nafdacShelfLife(d.mfgDate, d.shelfLifeDays);
  const origin = nafdacOrigin(d.originCountry, d.imported, d.importer);
  const gmo = nafdacGmoStatement(ingredients);
  const nrow = (l, v, sub) => `<div class="nr ${sub ? "sub" : ""}"><span>${l}</span><b>${v}</b></div>`;
  return `<!doctype html><html><head><meta charset="utf-8"><title>NAFDAC Label, ${recipe.name}</title>
<style>body{font-family:Helvetica,Arial,sans-serif;color:#111;max-width:420px;margin:0 auto;padding:24px}
.lbl{border:2px solid #000;padding:14px}
h1{font-size:20px;margin:0 0 2px}.brand{font-size:11px;font-weight:700;text-transform:uppercase;color:#444}
.sec{margin-top:11px;font-size:12px;line-height:1.5}.sec b.h{display:block;font-size:10px;text-transform:uppercase;letter-spacing:.04em;color:#555;margin-bottom:2px}
.nft{border:1.5px solid #000;padding:7px;margin-top:11px}.nft .t{font-size:15px;font-weight:800;border-bottom:5px solid #000;padding-bottom:2px}
.nr{display:flex;justify-content:space-between;border-bottom:1px solid #000;padding:2px 0;font-size:12px}.nr.sub{padding-left:14px;font-size:11px;border-bottom:1px solid #ccc}
.allg{background:#fdf6e3;border:1px solid #e8d9a0;padding:7px;border-radius:4px;font-weight:700;font-size:11.5px;margin-top:11px}
.meta{display:flex;justify-content:space-between;font-size:11px;border-top:1px solid #ccc;padding-top:4px;margin-top:4px}
.reg{font-weight:800;font-size:13px;margin-top:8px}.foot{font-size:9px;color:#777;margin-top:8px}
.print{position:fixed;top:16px;right:16px;background:#15803d;color:#fff;border:0;border-radius:999px;padding:9px 16px;font-weight:700;cursor:pointer}@media print{.print{display:none}.lbl{border-width:1px}}</style></head>
<body><button class="print" onclick="window.print()">Print / Save PDF</button>
<div class="lbl">
<div class="brand">${d.manufacturer || "FreshLife Foods"}</div><h1>${recipe.name}</h1>
<div class="sec"><b class="h">Ingredients</b>${declaration}.</div>
${allergens.contains.length ? `<div class="allg">${allergens.statement}</div>` : ""}
<div class="nft"><div class="t">Nutrition Information</div><div style="font-size:11px;font-weight:700">${nutr.unitLabel}</div>
${nrow("Energy", nutr.energy_kj + "kJ / " + nutr.energy_kcal + "kcal")}${nrow("Protein", nutr.protein_g + "g")}${nrow("Fat", nutr.fat_g + "g")}${nrow("of which saturates", nutr.fat_saturated_g + "g", 1)}${nrow("trans fat", nutr.fat_trans_g + "g", 1)}${nrow("Carbohydrate", nutr.carbohydrate_g + "g")}${nrow("of which sugars", nutr.sugars_g + "g", 1)}${nrow("Fibre", nutr.fibre_g + "g")}${nrow("Salt", nutr.salt_g + "g")}</div>
<div class="sec"><b class="h">Net content</b>${d.netValue ? d.netValue + (d.netUnit || "g") : "—"}${d.drained ? " · Drained: " + d.drained + (d.netUnit || "g") : ""}</div>
${d.storage ? `<div class="sec"><b class="h">Storage</b>${d.storage}</div>` : ""}
${d.directions ? `<div class="sec"><b class="h">Directions</b>${d.directions}</div>` : ""}
${gmo ? `<div class="sec"><b class="h">GMO</b>${gmo}</div>` : ""}
${d.irradiated ? `<div class="sec"><b class="h">Irradiation</b>Treated With Ionizing Radiation ☢</div>` : ""}
<div class="sec"><b class="h">Manufactured by</b>${d.manufacturer || "—"}${d.manufacturerAddr ? ", " + d.manufacturerAddr : ""}<br>${origin}</div>
<div class="meta"><span>BATCH: ${batch}</span><span>MFG: ${nafdacFmtDate(d.mfgDate)}</span><span>EXP: ${nafdacFmtDate(expiry)}</span></div>
${d.regNo ? `<div class="reg">NAFDAC REG NO: ${d.regNo}</div>` : ""}
<div class="foot">Label auto-generated by NutriDMS · Compliance ${validation.score}% (${validation.verdict}). Review before final NAFDAC submission.</div>
</div></body></html>`;
}
function nafdacReportHtml(recipe, res, details, nutr, ingredients, allergens) {
  const d = details || {};
  const row = (c) => `<tr><td>${c.label}</td><td class="${c.state}">${c.state === "pass" ? "PASS" : c.state === "fail" ? "ERROR" : "WARNING"}</td></tr>`;
  return `<!doctype html><html><head><meta charset="utf-8"><title>NAFDAC Registration Readiness, ${recipe.name}</title>
<style>body{font-family:-apple-system,Segoe UI,Roboto,sans-serif;color:#1a2218;max-width:820px;margin:0 auto;padding:32px}
h1{font-size:23px;margin:0}.sub{color:#5a6657;font-size:13px;margin:2px 0 18px}
.hero{display:flex;gap:18px;align-items:center;background:${res.ready ? "#ECF7E3" : "#FEF3F2"};border:1px solid ${res.ready ? "#C6E2AE" : "#F4C7C7"};border-radius:12px;padding:18px;margin-bottom:18px}
.score{font-size:38px;font-weight:800;color:${res.ready ? "#2c5e14" : "#b42318"}}
.stats{display:flex;gap:20px;margin-left:auto}.stats div{text-align:center}.stats b{display:block;font-size:20px}
table{width:100%;border-collapse:collapse;font-size:12.5px;margin-top:10px}th{text-align:left;background:#f1f6ea;padding:8px;border-bottom:2px solid #2f6b18}
td{padding:7px 8px;border-bottom:1px solid #eee}td.pass{color:#2c5e14;font-weight:700}td.fail{color:#b42318;font-weight:700}td.warn{color:#B45309;font-weight:700}
h2{font-size:14px;margin:20px 0 6px}.kv{font-size:12.5px;color:#444;line-height:1.7}.print{position:fixed;top:16px;right:16px;background:#2f6b18;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>
<h1>NAFDAC Registration Readiness Report</h1><div class="sub">${recipe.name} · generated ${new Date().toLocaleString()}</div>
<div class="hero"><div><div class="score">${res.score}%</div><div>${res.verdict}</div></div>
<div class="stats"><div><b>${res.passed.length}</b>Passed</div><div><b style="color:#B45309">${res.warned.length}</b>Warnings</div><div><b style="color:#b42318">${res.failed.length}</b>Errors</div><div><b>${res.ready ? "YES" : "NO"}</b>Ready</div></div></div>
<h2>Product summary</h2><div class="kv">Ingredients: ${nafdacDeclaration(ingredients)}.<br>${allergens.statement}<br>Energy: ${nutr.energy_kj}kJ / ${nutr.energy_kcal}kcal per 100g · Salt ${nutr.salt_g}g<br>Net content: ${d.netValue || "—"}${d.netUnit || ""} · Batch ${nafdacBatchCode(d.mfgDate, d.batchSeq || 1)} · NAFDAC ${d.regNo || "(pending)"}</div>
<h2>Compliance checks (${res.total})</h2><table><thead><tr><th>Check</th><th>Result</th></tr></thead><tbody>${res.checks.map(row).join("")}</tbody></table>
<p style="font-size:10px;color:#9aa595;margin-top:18px">Generated by NutriDMS NAFDAC Compliance Engine. Decision-support only, final registration submission must be reviewed by an authorized regulatory officer.</p></body></html>`;
}

if (typeof window !== "undefined") Object.assign(window, { NafdacLabelStudio, NafdacPanel, NafdacDetails, NafdacTrace, NafdacValidator, NafdacFormatTab, NafdacDeclaration, NafdacFullPreview });

/* ── Format & Product Type tab ── */
function NafdacFormatTab({ recipe, format, setFormat, suggested, goPreview }) {
  const pick = (id) => { setFormat(id); if (goPreview) setTimeout(goPreview, 60); };
  return (
    <div className="naf-details">
      <div className="naf-m19-bar"><span><Icon name="lightbulb" size={12} /> Loraa recommends <b>{(NAFDAC_FORMATS.find((f) => f.id === suggested) || {}).name}</b> for “{recipe.name}”.</span>{format !== suggested && <button className="naf-mini-btn" onClick={() => pick(suggested)}>Use suggestion</button>}</div>
      <div className="naf-fmt-grid">
        {NAFDAC_FORMATS.map((f) => (
          <button key={f.id} className={`naf-fmt-card ${format === f.id ? "on" : ""}`} onClick={() => pick(f.id)}>
            <span className="naf-fmt-ic" style={{ background: f.theme.bar }}><Icon name={f.icon} size={16} /></span>
            <span className="naf-fmt-nm">{f.name}{f.id === suggested && <span className="naf-fmt-sug">Suggested</span>}</span>
            <span className="naf-fmt-basis">Nutrition basis: {f.basis === "100g" ? "per 100g" : f.basis === "100ml" ? "per 100ml" : "per serving"}</span>
          </button>
        ))}
      </div>
    </div>
  );
}

/* ── Nutrition Declaration tab (basis, serving, claims, thresholds, benefits) ── */
function NafdacDeclaration({ recipe, nutr, nutr100g, claims, fmtDef, details, setD, onRemove }) {
  const d = details || {};
  return (
    <div className="naf-details">
      <div className="naf-det-grid">
        <section className="ls-card">
          <div className="ls-card-h"><Icon name="ruler" size={14} /> Declaration basis</div>
          <div className="naf-det-out ok">This format declares nutrition <b>{fmtDef.basis === "100g" ? "per 100g" : fmtDef.basis === "100ml" ? "per 100ml" : "per serving"}</b> (set by the {fmtDef.name} format).</div>
          <label className="ls-field" style={{ marginTop: 10 }}><span>Serving size (g/ml)</span><input type="number" value={d.servingSize || Math.round(nutr.servingG)} onChange={(e) => setD("servingSize", e.target.value)} /></label>
          <label className="ls-field"><span>Servings per container</span><input type="number" value={d.servings || nutr.servings} onChange={(e) => setD("servings", e.target.value)} /></label>
          <div className="naf-calc-note"><Icon name="calculator" size={11} /> Per serve = per 100g × serving ÷ 100 · kJ = kcal × 4.184 · Salt = Sodium × 2.5 ÷ 1000</div>
        </section>
        <section className="ls-card">
          <div className="ls-card-h"><Icon name="badge-check" size={14} /> Claim validation</div>
          <div className="naf-claims">
            {claims.map((c) => (
              <div key={c.id} className={`naf-claim ${c.status}`}>
                <div className="naf-claim-top"><Icon name={c.status === "eligible" ? "check-circle-2" : "x-circle"} size={14} /> <span>{c.label}</span><span className={`pill ${c.status === "eligible" ? "success" : "danger"}`} style={{ fontSize: 10 }}>{c.status === "eligible" ? "Eligible" : "Not met"}</span></div>
                <div className="naf-claim-why"><b>Why:</b> {c.why}</div>
                {c.status !== "eligible" && <div className="fda-claim-fix"><Icon name="wrench" size={11} /> <span><b>How to fix:</b> {c.fix}</span></div>}
                {c.status !== "eligible" && onRemove && <button className="fda-claim-apply" onClick={() => onRemove(c.id)}><Icon name="trash-2" size={12} /> Remove claim from label</button>}
              </div>
            ))}
          </div>
          <div className="naf-calc-note"><Icon name="info" size={11} /> Vitamins/minerals below 5% NRV must not be declared. Benefit statements may only use approved structure/function wording, never disease claims.</div>
        </section>
      </div>
    </div>
  );
}

/* ── Full Label Preview tab, Nutrition Panel / Front / Back / Full / Print ── */
function NafdacFullPreview({ recipe, nutr, fmtDef, details, ingredients, declaration, allergens, validation, micros, water, fat }) {
  const prepared = fmtDef.layout === "prepared";
  const [mode, setMode] = useNafState(prepared ? "back" : "full");
  const d = details || {};
  const th = fmtDef.theme;
  const batch = nafdacBatchCode(d.mfgDate, d.batchSeq || 1);
  const expiry = d.expiry || nafdacShelfLife(d.mfgDate, d.shelfLifeDays);
  const origin = nafdacOrigin(d.originCountry, d.imported, d.importer);
  const MODES = [{ id: "panel", l: "Nutrition Panel" }, { id: "front", l: "Front Label" }, { id: "back", l: "Back Label" }, { id: "full", l: "Full Label" }, { id: "print", l: "Print Layout" }];
  const Front = () => (
    <div className="naf-front" style={{ background: th.bg, borderColor: th.bar }}>
      <div className="naf-front-brand" style={{ color: th.bar }}>{d.manufacturer || "FreshLife"}</div>
      <div className="naf-front-nm">{recipe.name}</div>
      <div className="naf-front-soi">{fmtDef.name.replace(" Format", "")}{prepared ? " · Ready-to-Eat" : ""}</div>
      <div className="naf-front-net">{d.netValue ? d.netValue + (d.netUnit || "g") : "Net weight:,"}</div>
      {prepared && <div className="naf-front-store">Keep refrigerated</div>}
      {validation.ready && d.regNo && <div className="naf-front-reg">NAFDAC: {d.regNo}</div>}
    </div>
  );
  const Back = () => (
    <div className="naf-back" style={{ borderColor: th.bar }}>
      <div className="naf-back-sec"><b>Ingredients:</b> {declaration}.</div>
      {allergens.contains.length > 0 && <div className="naf-back-allg">{allergens.statement}</div>}
      <NafdacPanel recipe={recipe} nutr={nutr} zoom={0.92} format={fmtDef} micros={micros} water={water} fat={fat} servingG={Math.round(nutr.servingG)} />
      {d.storage && <div className="naf-back-sec"><b>Storage:</b> {d.storage}</div>}
      {d.directions && <div className="naf-back-sec"><b>Directions:</b> {d.directions}</div>}
      <div className="naf-back-sec"><b>Manufactured by:</b> {d.manufacturer || "—"}{d.manufacturerAddr ? ", " + d.manufacturerAddr : ""} · {origin}</div>
      <div className="naf-back-meta"><span>BATCH: {batch}</span><span>MFG: {nafdacFmtDate(d.mfgDate)}</span><span>EXP: {nafdacFmtDate(expiry)}</span></div>
      {d.regNo && <div className="naf-back-reg">NAFDAC REG NO: {d.regNo}</div>}
    </div>
  );
  return (
    <div className="naf-preview-wrap">
      <div className="naf-mode-bar">
        {MODES.map((m) => <button key={m.id} className={`fda-source-btn ${mode === m.id ? "on" : ""}`} onClick={() => setMode(m.id)}>{m.l}</button>)}
        <span className={`pill ${validation.ready ? "success" : "warning"}`} style={{ fontSize: 10, marginLeft: "auto" }}>Full-label compliance: {validation.score}%</span>
      </div>
      {!validation.ready && <div className="fda-legal-note" style={{ marginTop: 10 }}><Icon name="alert-triangle" size={13} /> This preview is not yet compliant, {validation.failed.length} mandatory field(s) outstanding. The score reflects the full label, not just the nutrition panel.</div>}
      <div className={`naf-preview-stage ${mode === "print" ? "print" : ""}`}>
        {mode === "panel" && <NafdacPanel recipe={recipe} nutr={nutr} zoom={1} format={fmtDef} micros={micros} water={water} fat={fat} servingG={Math.round(nutr.servingG)} />}
        {mode === "front" && <Front />}
        {mode === "back" && <Back />}
        {(mode === "full" || mode === "print") && <div className="naf-fullwrap"><Front /><Back /></div>}
      </div>
    </div>
  );
}

/* ── International labels, coming soon placeholders (UK/EU/Australia/Mexico) ── */
function IntlLabelComingSoon({ market }) {
  const M = {
    uk: { name: "United Kingdom", reg: "UK FIC Regulation (assimilated EU 1169/2011) + FSA", flag: "🇬🇧" },
    eu: { name: "European Union", reg: "EU Regulation 1169/2011 (Food Information to Consumers)", flag: "🇪🇺" },
    au: { name: "Australia", reg: "FSANZ Food Standards Code (Standard 1.2.8 NIP)", flag: "🇦🇺" },
    mx: { name: "Mexico", reg: "NOM-051-SCFI/SSA1 (front-of-pack warning seals)", flag: "🇲🇽" },
  }[market] || { name: "Market", reg: "", flag: "🌍" };
  return (
    <div className="ls fda-ls">
      <div className="page-head"><div>
        <h1 className="page-title">{M.name} Label Studio</h1>
        <p className="page-sub">Multi-country compliance, built on the same NutriDMS core engine.</p>
      </div></div>
      <div className="naf-soon">
        <div className="naf-soon-flag">{M.flag}</div>
        <h2>{M.name} labels, coming soon</h2>
        <p>The {M.name} generator will follow {M.reg}. It reuses the same nutrition calculation, ingredient declaration, allergen, GS1, and validation engine already powering the CFIA, FDA, and NAFDAC modules, so your product data carries over with no re-entry.</p>
        <div className="naf-soon-pills">
          <span class="pill neutral">Nutrition engine ready</span>
          <span class="pill neutral">Ingredient &amp; allergen engine ready</span>
          <span class="pill neutral">GS1 / QR ready</span>
        </div>
      </div>
    </div>
  );
}
/* ── Ask Loraa, NAFDAC compliance knowledge Q&A ── */
function NafdacLoraaLogo() {
  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 nafStatusTone(s) { return /block|critical|no\b/i.test(s) ? "bad" : /required|calculation/i.test(s) ? "warn" : "ok"; }

/* One answered turn, streams the answer, then reveals supporting detail + follow-ups. */
function NafdacTurn({ turn, onFollow, isLast }) {
  const a = turn.a;
  const [stream, setStream] = useNafState(turn.streamed ? a.answer : "");
  const [done, setDone] = useNafState(!!turn.streamed);
  useNafEffect(() => {
    if (turn.streamed) return; // already shown
    setStream(""); setDone(false);
    const full = a.answer; let i = 0; let alive = true;
    const tick = () => {
      if (!alive) return;
      i += Math.max(1, Math.round(full.length / 220));
      setStream(full.slice(0, i));
      if (i < full.length) setTimeout(tick, 38);
      else { setStream(full); setDone(true); turn.streamed = true; }
    };
    const t = setTimeout(tick, 80);
    return () => { alive = false; clearTimeout(t); };
  }, []);
  return (
    <div className="naf-turn">
      <div className="naf-ask-q"><Icon name="help-circle" size={14} /> {turn.q}</div>
      <div className="naf-ask-a">
        <NafdacLoraaLogo />
        <div className="naf-ask-a-body">
          {a.warm && done && <p className="naf-ask-warm">{a.warm}</p>}
          <p className="naf-ask-direct">{stream}{!done && <span className="naf-ask-caret" />}</p>
          {done && (
            <div className="naf-ask-rest">
              {a.why && <div className="naf-ask-why"><b>Why it matters:</b> {a.why} {a.ref && <a className="naf-ask-ref" href={a.ref} target="_blank" rel="noopener noreferrer">Read the NAFDAC labelling guide <Icon name="external-link" size={11} /></a>}</div>}
              {a.apply && <div className="naf-ask-apply"><Icon name="wand-2" size={12} /> <span><b>How to apply it:</b> {a.apply}</span></div>}
              <div className="naf-ask-meta">
                <span className={`pill ${nafStatusTone(a.status) === "ok" ? "success" : nafStatusTone(a.status) === "warn" ? "warning" : "danger"}`} style={{ fontSize: 10 }}>Status: {a.status}</span>
                {a.fields && a.fields.length > 0 && <span className="naf-ask-fields"><Icon name="list-checks" size={11} /> NutriDMS checks: {a.fields.join(", ")}</span>}
              </div>
              {isLast && a.follow && a.follow.length > 0 && (
                <div className="naf-ask-follow">
                  <span className="naf-ask-follow-l">Continue the conversation</span>
                  <div className="naf-ask-follow-chips">{a.follow.map((q) => <button key={q} className="naf-ask-chip sm" onClick={() => onFollow(q)}><Icon name="corner-down-right" size={11} /> {q}</button>)}</div>
                </div>
              )}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

function NafdacAsk() {
  const [thread, setThread] = useNafState([]);
  const [typed, setTyped] = useNafState("");
  const ask = (q) => { setThread((t) => [...t, { q, a: nafdacAsk(q), streamed: false }]); };
  const submit = () => { if (!typed.trim()) return; ask(typed.trim()); setTyped(""); };
  return (
    <div className="naf-ask">
      <div className="naf-ask-head"><NafdacLoraaLogo /> <span>Ask Loraa about NAFDAC compliance</span></div>
      <div className="naf-ask-lead">Loraa answers from NutriDMS's internal NAFDAC regulatory knowledge, the Pre-Packaged Food (Labelling) Regulations 2022, not the open internet. It never invents rules.</div>

      {thread.length === 0 ? (
        <div className="naf-ask-empty">
          <NafdacLoraaLogo />
          <p>Hi, I'm Loraa. Ask me anything about getting your product label NAFDAC-compliant, I'll explain the rule, why it matters, and exactly how to apply it in NutriDMS.</p>
        </div>
      ) : (
        <div className="naf-ask-thread">
          {thread.map((turn, i) => <NafdacTurn key={i} turn={turn} onFollow={ask} isLast={i === thread.length - 1} />)}
        </div>
      )}

      <div className="naf-ask-suggest">
        {NAFDAC_SUGGESTED_Q.map((q) => <button key={q} className="naf-ask-chip" onClick={() => ask(q)}><Icon name="message-circle" size={12} /> {q}</button>)}
      </div>

      <div className="naf-ask-bar">
        <input value={typed} onChange={(e) => setTyped(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter") submit(); }} placeholder="Ask a NAFDAC compliance question…" />
        <button className="naf-ask-send" disabled={!typed.trim()} onClick={submit} aria-label="Ask"><Icon name="arrow-up" size={15} stroke={2.4} /></button>
      </div>
      <div className="naf-ask-disc"><Icon name="info" size={11} /> NutriDMS compliance guidance, review with a qualified regulatory professional before final NAFDAC submission.</div>
    </div>
  );
}

if (typeof window !== "undefined") Object.assign(window, { IntlLabelComingSoon, NafdacAsk });
