/* NutriDMS, Nutrition Insight Engine (consumer-facing, NOT FDA labels)
   Separate from the FDA label generator. Produces parent-friendly & teen
   nutrition summaries, a QR nutrition experience, and Loraa insights,
   each clearly marked as guidance, never as a Nutrition Facts label. */

const { useState: useNiState, useMemo: useNiMemo, useEffect: useNiEffect, useRef: useNiRef } = React;

function NutritionInsightEngine() {
  const { toast } = useApp();
  const recipes = useNiMemo(() => (typeof RECIPES !== "undefined") ? RECIPES.filter((r) => r.status === "published" || r.status === "approved") : [], []);
  const [recipeId, setRecipeId] = useNiState(recipes[0] ? recipes[0].id : null);
  const recipe = recipes.find((r) => r.id === recipeId) || recipes[0];
  const profile = useNiMemo(() => recipe ? lblNutrientProfile(recipe) : null, [recipe]);
  const [tab, setTab] = useNiState("parent");

  if (!recipe) return <div className="rp-empty"><div className="icon"><Icon name="lightbulb" size={24} /></div><h3>No published recipes</h3><p>Publish a recipe to generate consumer nutrition summaries.</p></div>;

  const TABS = [
    { id: "parent", label: "Parent-Friendly", icon: "baby" },
    { id: "teen", label: "Teen Summary", icon: "user" },
    { id: "qr", label: "QR Experience", icon: "qr-code" },
    { id: "loraa", label: "Loraa Insights", icon: "lightbulb" },
  ];

  return (
    <div className="ni">
      <div className="page-head">
        <div>
          <h1 className="page-title">Nutrition Insight Engine</h1>
          <p className="page-sub">Consumer-facing nutrition summaries &amp; experiences, generated separately from FDA labels.</p>
        </div>
      </div>

      <div className="ni-sep-banner">
        <Icon name="alert-circle" size={15} />
        <div><b>Not an FDA Nutrition Facts label.</b> These are consumer nutrition summaries for guidance only. For the legally compliant panel, use <b>FDA Label Studio</b>.</div>
      </div>

      <div className="ni-controls">
        <label className="ni-recipe"><span>Product</span>
          <select value={recipeId} onChange={(e) => setRecipeId(e.target.value)}>
            {recipes.map((r) => <option key={r.id} value={r.id}>{r.name}</option>)}
          </select>
        </label>
        <div className="ni-tabs">
          {TABS.map((t) => <button key={t.id} className={`ni-tab ${tab === t.id ? "on" : ""}`} onClick={() => setTab(t.id)}><Icon name={t.icon} size={14} /> {t.label}</button>)}
        </div>
      </div>

      <div className="ni-stage">
        {tab === "parent" && <NiAgeSummary recipe={recipe} profile={profile} groups={["1-3", "4-8", "9-13"]} kind="parent" />}
        {tab === "teen" && <NiAgeSummary recipe={recipe} profile={profile} groups={["14-18"]} kind="teen" />}
        {tab === "qr" && <NiQrExperience recipe={recipe} profile={profile} />}
        {tab === "loraa" && <NiLoraa recipe={recipe} profile={profile} />}
      </div>
    </div>
  );
}

/* Parent-friendly / teen age-band summary (reuses fdaKidsMonitor, for guidance, not labeling) */
function NiAgeSummary({ recipe, profile, groups, kind }) {
  const [group, setGroup] = useNiState(groups[0]);
  const m = fdaKidsMonitor(profile, recipe, group);
  const flagCls = (f) => f === "high" ? "ni-high" : f === "watch" ? "ni-watch" : "ni-ok";
  const flagWord = (f) => f === "high" ? "High" : f === "watch" ? "Worth watching" : "Looks good";
  return (
    <div className="ni-card-wrap">
      {groups.length > 1 && (
        <div className="ni-agebar">
          {groups.map((g) => <button key={g} className={`ni-agebtn ${group === g ? "on" : ""}`} onClick={() => setGroup(g)}>{FDA_KIDS_DV[g].label}</button>)}
        </div>
      )}
      <div className="ni-summary">
        <div className="ni-summary-h">
          <span className="ni-badge"><Icon name={kind === "teen" ? "user" : "baby"} size={13} /> {kind === "teen" ? "Teen Nutrition Summary" : "Parent-Friendly Summary"}</span>
          <span className="ni-summary-grp">{m.group}</span>
        </div>
        <div className="ni-summary-nm">{recipe.name}</div>
        <div className="ni-cal-big">{fdaRoundCal(profile.energy_kcal)} <span>calories per serving</span></div>
        <div className="ni-monitors">
          <div className={`ni-mon ${flagCls(m.sodium.flag)}`}>
            <div className="ni-mon-top"><span>Sodium</span><b>{m.sodium.mg}mg</b></div>
            <div className="ni-mon-bar"><i style={{ width: Math.min(100, m.sodium.pct) + "%" }} /></div>
            <div className="ni-mon-foot"><span>{m.sodium.pct}% of a {m.group.toLowerCase()} day</span><span className="ni-mon-flag">{flagWord(m.sodium.flag)}</span></div>
          </div>
          <div className={`ni-mon ${flagCls(m.addedSugars.flag)}`}>
            <div className="ni-mon-top"><span>Added Sugars</span><b>{m.addedSugars.g}g</b></div>
            <div className="ni-mon-bar"><i style={{ width: Math.min(100, m.addedSugars.pct) + "%" }} /></div>
            <div className="ni-mon-foot"><span>{m.addedSugars.pct}% of a {m.group.toLowerCase()} day</span><span className="ni-mon-flag">{flagWord(m.addedSugars.flag)}</span></div>
          </div>
        </div>
        <div className="ni-growth-h">Growth nutrients</div>
        <div className="ni-growth">
          {m.growth.map((g) => <div key={g.k} className="ni-g"><span>{g.k}</span><b>{g.v}</b><div className="ni-g-bar"><i style={{ width: Math.min(100, g.pct) + "%" }} /></div></div>)}
        </div>
        <div className="ni-disc"><Icon name="info" size={11} /> Friendly guidance based on age-specific reference values, not a substitute for the FDA Nutrition Facts panel or medical advice.</div>
      </div>
    </div>
  );
}

/* QR Nutrition Experience, scannable consumer card */
function NiQrExperience({ recipe, profile }) {
  const ref = useNiRef(null);
  useNiEffect(() => {
    const el = ref.current; if (!el || !window.QRCode) return;
    el.innerHTML = "";
    new window.QRCode(el, { text: `https://nutridms.com/x/${recipe.id}`, width: 150, height: 150, colorDark: "#15281c", colorLight: "#fff" });
  }, [recipe]);
  const macros = [
    { k: "Calories", v: fdaRoundCal(profile.energy_kcal) },
    { k: "Protein", v: Math.round(profile.protein_g) + "g" },
    { k: "Carbs", v: Math.round(profile.carbohydrate_g) + "g" },
    { k: "Fat", v: Math.round(profile.fat_g) + "g" },
    { k: "Fiber", v: Math.round(profile.fibre_g) + "g" },
    { k: "Sodium", v: Math.round(profile.sodium_mg) + "mg" },
  ];
  const tags = (recipe.diet || []).slice(0, 4);
  return (
    <div className="ni-qr-wrap">
      <div className="ni-qr-phone">
        <div className="ni-qr-card">
          <div className="ni-qr-card-h">Nutrition at a glance</div>
          <div className="ni-qr-nm">{recipe.name}</div>
          <div className="ni-qr-macros">
            {macros.map((mm) => <div key={mm.k} className="ni-qr-m"><b>{mm.v}</b><span>{mm.k}</span></div>)}
          </div>
          {tags.length > 0 && <div className="ni-qr-tags">{tags.map((t) => <span key={t} className="ni-qr-tag">{t}</span>)}</div>}
          <div className="ni-qr-note">Consumer nutrition experience · not an FDA label</div>
        </div>
      </div>
      <div className="ni-qr-side">
        <div className="ni-qr-code" ref={ref} />
        <div className="ni-qr-side-h">Scannable QR experience</div>
        <p>Diners scan to open this nutrition card, calories, macros, and dietary tags in a friendly mobile view. Links to the public product page; the legal Nutrition Facts panel is available separately.</p>
      </div>
    </div>
  );
}

/* Loraa Nutrition Insights, consumer-friendly, generated from the profile */
function NiLoraa({ recipe, profile }) {
  const insights = [];
  const p = profile;
  if (p.protein_g >= 20) insights.push({ ic: "beef", t: `High in protein, ${Math.round(p.protein_g)}g per serving supports muscle maintenance and keeps you full.` });
  if (p.fibre_g >= 5) insights.push({ ic: "sprout", t: `A good source of fiber (${Math.round(p.fibre_g)}g), supports digestion and steady energy.` });
  if (p.sodium_mg >= 700) insights.push({ ic: "alert-triangle", t: `Higher in sodium (${Math.round(p.sodium_mg)}mg), something to balance across the rest of your day.` });
  else insights.push({ ic: "heart", t: `Moderate sodium (${Math.round(p.sodium_mg)}mg), a heart-friendlier choice.` });
  if (p.energy_kcal <= 450) insights.push({ ic: "leaf", t: `Lighter option at ${fdaRoundCal(p.energy_kcal)} calories, fits well into a balanced day.` });
  insights.push({ ic: "info", t: `Pairs nutrition with the rest of your meals, Loraa can suggest balanced combinations on request.` });
  return (
    <div className="ni-loraa">
      <div className="ni-loraa-h"><span className="ni-loraa-spark"><Icon name="lightbulb" size={14} /></span> Loraa Nutrition Insights <span className="pill neutral" style={{ fontSize: 10 }}>Consumer guidance</span></div>
      <div className="ni-loraa-list">
        {insights.map((i, idx) => <div key={idx} className="ni-loraa-item"><span className="ni-loraa-ic"><Icon name={i.ic} size={15} /></span><span>{i.t}</span></div>)}
      </div>
      <div className="ni-disc"><Icon name="info" size={11} /> Loraa insights are friendly, plain-language guidance, not an FDA Nutrition Facts label or medical advice.</div>
    </div>
  );
}

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