/* NutriDMS, Data Verification page */
const { useState: useVfState, useEffect: useVfEffect } = React;
const _VfCtx = { role:"super-admin", page:"verification", setPage:()=>{}, lang:"en", setLang:()=>{}, openCmd:()=>{}, openNotif:()=>{} };

const VDS = window.NUTRIDMS_SANDBOX || { ingredients: [], recipes: [], beverages: [] };

/* ─── Nav ─── */
function VfNav() {
  return (
    <div className="ld-nav-wrap">
      <nav className="ld-nav">
        <a href="Landing.html" className="ld-logo">
          <NutriHoriz height={36}/>
        </a>
        <div className="ld-nav-links">
          <a href="Landing.html#platform">Platform</a>
          <a href="data-verification.html" style={{color:"var(--brand-700)",background:"var(--green-50)"}}>Verification</a>
          <a href="api-sandbox.html">Sandbox</a>
          <a href="security.html">Security</a>
          <a href="documentation.html">Docs</a>
        </div>
        <div className="ld-nav-cta">
          <LangSwitch />
          <ThemeToggle />
          <a href="signin.html" className="btn ghost sm">Sign in</a>
          <a href="book-demo.html" className="btn primary sm"><Icon name="calendar" size={14} stroke={2.2}/> Book Demo</a>
        </div>
      </nav>
    </div>
  );
}

/* ─── Hero ─── */
function VfHero() {
  return (
    <section className="vf-hero">
      <div className="inner">
        <span className="ld-eyebrow"><Icon name="shield-check" size={12} stroke={2.5}/> Data Verification</span>
        <h1>Every ingredient, recipe, and beverage, verified by Registered Dietitians.</h1>
        <p className="lede">
          NutriDMS data isn't random AI output. It comes from a controlled verification workflow:
          master-DB mapping, AI second-layer validation, allergen and health-rule checks, and
          final human sign-off by Registered Dietitians (RDN) before anything reaches the API.
        </p>

        <div className="vf-rdn">
          <div className="avatars">
            <div className="av">EH</div>
            <div className="av">MP</div>
            <div className="av">SC</div>
            <div className="av">+12</div>
          </div>
          <div>
            <div className="t">RDN-reviewed by 15+ Registered Dietitians</div>
            <div className="s">Every verified record carries a reviewer signature and timestamp.</div>
          </div>
        </div>

        <div className="stats">
          <div className="stat">
            <div className="v">2800+</div>
            <div className="l">Verified ingredients</div>
            <div className="sub">Mapped to USDA / FDA references</div>
          </div>
          <div className="stat">
            <div className="v">625</div>
            <div className="l">RDN-approved recipes</div>
            <div className="sub">Caribbean library · expanding</div>
          </div>
          <div className="stat">
            <div className="v">120</div>
            <div className="l">Verified beverages</div>
            <div className="sub">Juices · smoothies · teas</div>
          </div>
          <div className="stat">
            <div className="v">9</div>
            <div className="l">Verification API modules</div>
            <div className="sub">Ingredient · recipe · beverage · allergen · …</div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ─── Sources ─── */
function VfSources() {
  const sources = [
    { ic: "leaf", n: "2800+", t: "Master Ingredient Database",
      d: "Canonical ingredient names mapped to USDA / FDA / WAFCT references with calories, macros, micros, allergens, and health tags per 100g.",
      samples: VDS.ingredients.slice(0, 6) },
    { ic: "chef-hat", n: 625, t: "Recipe Database",
      d: "RDN-approved recipes with per-serving nutrition, allergen declarations, health tags, prep + cook times, and cultural context.",
      samples: VDS.recipes.slice(0, 6) },
    { ic: "droplet", n: 120, t: "Beverage Database",
      d: "Juices, smoothies, and teas with per-serving nutrition, key benefits, allergens, and ml-based serving sizes.",
      samples: VDS.beverages.slice(0, 6) },
  ];
  return (
    <section className="vf-section">
      <div className="ld-container">
        <div className="ld-section-head">
          <span className="ld-eyebrow"><Icon name="database" size={12} stroke={2.5}/> Verified Sources</span>
          <h2 className="ld-h2">Three verified data sources, one verification workflow.</h2>
          <p className="ld-lede">Every record flows through the same pipeline before it can be served by the API or used in nutrition labels.</p>
        </div>
        <div className="vf-sources">
          {sources.map((s, i) => (
            <div key={i} className="vf-source-card">
              <div className="head">
                <div className="ic"><Icon name={s.ic} size={20} stroke={2.2}/></div>
                <div className="count">{s.n}</div>
              </div>
              <h3>{s.t}</h3>
              <p>{s.d}</p>
              <div className="samples">
                {s.samples.map(it => (
                  <span key={it.id} className="sample"><span className="em">{it.emoji}</span> {it.name.length > 18 ? it.name.slice(0, 16) + "…" : it.name}</span>
                ))}
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ─── Steps ─── */
const STEPS_DATA = [
  { id: "intake", n: 1, t: "Ingredient Intake",
    lead: "Ingredients can enter NutriDMS from admin upload, recipe upload, API submission, CSV import, or manual entry.",
    checks: ["Ingredient name","Category","Raw / cooked state","Serving size","Nutrition per 100g/ml","Allergen flags","Health tags","Source / reference","Duplicate matches"] },
  { id: "mapping", n: 2, t: "Ingredient Mapping",
    lead: "Every submitted ingredient is mapped to the canonical master record. We capture confidence and reviewer overrides.",
    stored: ["Canonical ingredient name","Ingredient ID","Match confidence","Nutrition source","Verification status"],
    example: { from: "Red onion", to: "Onion, red · ing_0042" } },
  { id: "nutrition", n: 3, t: "Nutrition Verification",
    lead: "We verify each nutrient against the source. Missing values are flagged for human review before enterprise use.",
    fields: ["Calories","Protein","Fat","Carbohydrates","Sugar","Fiber","Sodium","Potassium","Calcium","Iron","Vitamins (A, C, D, E, K, B-complex)","Minerals (Mg, Zn, Cu, Se, Mn, P)"],
    note: "If nutrition is missing, the record becomes Needs Review and an RDN must approve before enterprise use." },
  { id: "recipe", n: 4, t: "Recipe Verification",
    lead: "For every recipe, NutriDMS verifies the structural inputs and the derived nutrition outputs.",
    checks: ["All ingredients are mapped","Ingredient quantities are valid","Serving size is present","Cooking yield is calculated","Nutrition per serving is calculated","Allergens are detected","Health tags are validated","Recipe is approved before publishing"] },
  { id: "beverage", n: 5, t: "Beverage Verification",
    lead: "Beverages follow the same workflow, with ml-based servings and yield calculations specific to liquids.",
    checks: ["Drink name & type","Ingredients & quantities","Serving size in ml","Yield ml","Calories per serving","Sugar level","Allergens","Health tags","Preparation steps","Review status"] },
  { id: "ai", n: 6, t: "AI QA Review (Laura.ai)",
    lead: "Laura.ai runs a second-layer review on every record, catching missing values, unit mistakes, allergen mismatches, and suspicious calorie ranges.",
    checks: ["Missing nutrition values","Wrong unit format","Invalid serving size","Allergen mismatch","Health tag conflict","Duplicate ingredient","Suspicious calorie values","Incomplete recipe data"],
    note: "AI output is always labeled: Verified · Warning · Needs Human Review · AI Suggested. It never publishes on its own." },
  { id: "human", n: 7, t: "Human Approval (RDN)",
    lead: "Final approval is always human. Only records approved by an Admin, Dietitian, Nutrition reviewer, or Compliance reviewer can be served by the enterprise API.",
    fields: ["Admin","Registered Dietitian (RDN)","Nutrition reviewer","Compliance reviewer"],
    note: "Approval signatures are tamper-evident, timestamped, and visible in every audit log." },
];

function VfSteps() {
  const [active, setActive] = useVfState("intake");
  useVfEffect(() => {
    const ids = STEPS_DATA.map(s => s.id);
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => { if (e.isIntersecting) setActive(e.target.id); });
    }, { rootMargin: "-30% 0px -60% 0px", threshold: 0 });
    ids.forEach(id => { const el = document.getElementById(id); if (el) io.observe(el); });
    return () => io.disconnect();
  }, []);
  return (
    <section className="vf-section band">
      <div className="ld-container">
        <div className="ld-section-head">
          <span className="ld-eyebrow"><Icon name="git-branch" size={12} stroke={2.5}/> Verification Workflow</span>
          <h2 className="ld-h2">Seven steps. Every record. Every time.</h2>
          <p className="ld-lede">No nutrition data reaches the API until it's been mapped, validated, AI-reviewed, and human-approved by an RDN.</p>
        </div>
        <div className="vf-steps">
          <aside className="vf-step-nav">
            <h4>Workflow Steps</h4>
            {STEPS_DATA.map(s => (
              <a key={s.id} href={`#${s.id}`} className={active === s.id ? "on" : ""}>
                <span className="n">{s.n}</span> {s.t}
              </a>
            ))}
          </aside>
          <div>
            {STEPS_DATA.map(s => (
              <div key={s.id} id={s.id} className="vf-step">
                <div className="head">
                  <div className="num-tile">{s.n}</div>
                  <div>
                    <h2>Step {s.n}, {s.t}</h2>
                    <p className="lead">{s.lead}</p>
                  </div>
                </div>
                <div className="body">
                  {s.checks && <>
                    <h4><Icon name="check-square" size={13} stroke={2.4}/> System checks</h4>
                    <ul>{s.checks.map(c => <li key={c}><Icon name="check" size={13} stroke={2.6}/> {c}</li>)}</ul>
                  </>}
                  {s.fields && <>
                    <h4><Icon name="list" size={13} stroke={2.4}/> Verified fields / roles</h4>
                    <ul>{s.fields.map(f => <li key={f}><Icon name="check" size={13} stroke={2.6}/> {f}</li>)}</ul>
                  </>}
                  {s.stored && <>
                    <h4><Icon name="database" size={13} stroke={2.4}/> What we store</h4>
                    <ul>{s.stored.map(f => <li key={f}><Icon name="check" size={13} stroke={2.6}/> {f}</li>)}</ul>
                  </>}
                  {s.example && (
                    <div className="example">
                      <strong>Example mapping</strong>
                      <div className="arrow" style={{marginTop:6}}>
                        <span className="from">User input: <strong>{s.example.from}</strong></span>
                        <Icon name="arrow-right" size={14} stroke={2.4}/>
                        <span className="to">{s.example.to}</span>
                      </div>
                    </div>
                  )}
                  {s.note && <div className="example" style={{marginTop:14}}><Icon name="info" size={13} stroke={2.4} style={{verticalAlign:"middle",color:"var(--brand-700)"}}/> {s.note}</div>}
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

/* ─── Statuses ─── */
function VfStatuses() {
  const items = [
    { cls: "ok", t: "Verified", d: "Approved and ready for API and enterprise use. Backed by RDN signature." },
    { cls: "pending", t: "Pending Review", d: "Waiting for admin or dietitian review. Not available via the API yet." },
    { cls: "suggested", t: "AI Suggested", d: "AI filled missing information. Visible to reviewers; not enterprise-serveable until approved." },
    { cls: "correction", t: "Needs Correction", d: "Missing or conflicting data flagged by AI or human reviewer." },
    { cls: "rejected", t: "Rejected", d: "Data failed review and was not promoted to the verified state." },
    { cls: "archived", t: "Archived", d: "Old or inactive record kept for audit purposes but not served by the API." },
  ];
  return (
    <section className="vf-section">
      <div className="ld-container">
        <div className="ld-section-head">
          <span className="ld-eyebrow"><Icon name="tag" size={12} stroke={2.5}/> Verification Statuses</span>
          <h2 className="ld-h2">Every record carries an explicit status.</h2>
          <p className="ld-lede">No silent fallback. The API never serves data the workflow hasn't promoted to Verified.</p>
        </div>
        <div className="vf-statuses">
          {items.map((it, i) => (
            <div key={i} className="vf-status">
              <span className={`badge ${it.cls}`}>{it.t}</span>
              <h4>{it.t}</h4>
              <p>{it.d}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ─── Sample previews ─── */
function VfSamples() {
  const ings = VDS.ingredients.filter(i => i.health_tags.length).slice(0, 3);
  const recs = VDS.recipes.slice(0, 3);
  const bevs = VDS.beverages.slice(0, 3);
  const Block = ({ title, sub, items, kind }) => (
    <div style={{marginBottom:32}}>
      <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:14}}>
        <div>
          <h3 style={{fontFamily:"var(--serif)",fontSize:22,margin:0,letterSpacing:"-.012em"}}>{title}</h3>
          <p style={{margin:"4px 0 0",fontSize:13,color:"var(--gray-600)"}}>{sub}</p>
        </div>
        <a href={kind === "ing" ? "api-sandbox.html#ingredient" : kind === "rec" ? "api-sandbox.html#recipe" : "api-sandbox.html#beverage"} className="btn ghost sm">Try in sandbox <Icon name="arrow-right" size={13} stroke={2.4}/></a>
      </div>
      <div className="vf-samples">
        {items.map(item => (
          <div key={item.id} className="vf-sample">
            <div className="photo">
              <span className="em">{item.emoji}</span>
              <span className="badge"><Icon name="check" size={9} stroke={3}/> RDN</span>
            </div>
            <div className="body">
              <div className="nm">{item.name}</div>
              <div className="ct">
                {kind === "ing" ? `${item.category} · ${item.state}` :
                 kind === "rec" ? `${item.country} · ${item.serving_g}g serving` :
                 `${item.type} · ${item.serving_ml}ml`}
              </div>
              <div className="row">
                <div className="kc">
                  {kind === "ing" ? item.nutrition_per_100g.calories_kcal : item.nutrition_per_serving.calories_kcal}
                  <span className="u"> kcal{kind === "ing" ? "/100g" : ""}</span>
                </div>
                <div className="tags">
                  {(kind === "ing" ? item.health_tags : kind === "rec" ? item.tags : item.tags).slice(0, 2).map((t, i) => (
                    <span key={i} className="tg">{t}</span>
                  ))}
                </div>
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
  return (
    <section className="vf-section band">
      <div className="ld-container">
        <div className="ld-section-head">
          <span className="ld-eyebrow"><Icon name="eye" size={12} stroke={2.5}/> Verified Records</span>
          <h2 className="ld-h2">A peek at what verified data looks like.</h2>
          <p className="ld-lede">Every record below has passed the full 7-step workflow and carries an RDN approval signature.</p>
        </div>
        <Block title="Verified ingredients" sub={`${VDS.ingredients.length}+ entries mapped to USDA references`} items={ings} kind="ing"/>
        <Block title="RDN-approved recipes" sub="Caribbean recipe library with full nutrition" items={recs} kind="rec"/>
        <Block title="Verified beverages" sub="Juices, smoothies, and teas" items={bevs} kind="bev"/>
      </div>
    </section>
  );
}

/* ─── CTA ─── */
function VfCta() {
  return (
    <section className="vf-section" style={{paddingTop:0}}>
      <div className="ld-container">
        <div className="vf-cta">
          <div>
            <h3>Test the verified API. No keys required.</h3>
            <p>Try the NutriDMS API in our public sandbox. Every response uses data verified by Registered Dietitians and mapped to USDA references.</p>
          </div>
          <div className="row">
            <a href="api-sandbox.html" className="btn primary lg"><Icon name="play" size={15} stroke={2.4}/> Open the sandbox</a>
            <a href="book-demo.html" className="btn secondary lg"><Icon name="calendar" size={15} stroke={2.4}/> Talk to sales</a>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ─── Shell ─── */
function VfShell() {
  return (
    <AppCtx.Provider value={_VfCtx}>
      <div>
        <VfNav/>
        <VfHero/>
        <VfSources/>
        <VfSteps/>
        <VfStatuses/>
        <VfSamples/>
        <VfCta/>
      </div>
    </AppCtx.Provider>
  );
}

function VfApp() { return <I18nProvider><VfShell/></I18nProvider>; }
ReactDOM.createRoot(document.getElementById("root")).render(<VfApp/>);
