// nutrios.jsx — NutriOS workflow animation (Option A style, self-contained)
const { useState, useEffect } = React;

const NUDATA = {
  ingredients: [
    ['Whole Wheat Flour', '62%'],
    ['Refined Palm Oil', '18%'],
    ['Cane Sugar', '12%'],
    ['Iodised Salt', '1.2%'],
    ['Raising Agent (INS 500(ii))', '0.8%'],
  ],
  serve: 40, // grams
  // name, per-100g value, unit, decimals, RDA (daily reference value, same unit | null)
  nutrition: [
    ['Energy', 478, 'kcal', 0, 2000],
    ['Protein', 7.4, 'g', 1, 50],
    ['Total Fat', 21.3, 'g', 1, 67],
    ['Carbohydrate', 63.2, 'g', 1, 300],
    ['Total Sugars', 14.1, 'g', 1, null],
    ['Sodium', 0.41, 'g', 2, 2],
  ],
};

const NUSTEPS = [
  { key: 'ingredients', label: 'Ingredient details',  title: 'Add your ingredients', win: [0.4, 4.6] },
  { key: 'nutrition',   label: 'Nutrition · per 100 g / per serve', title: 'Nutrition analysis', win: [4.9, 9.0] },
];
const NULOOP = 11.0;

const nclamp = (x, a, b) => Math.max(a, Math.min(b, x));
const nprog  = (t, a, b) => nclamp((t - a) / (b - a), 0, 1);
const nNextStart = (i) => (NUSTEPS[i + 1] ? NUSTEPS[i + 1].win[0] : NULOOP);
function nActive(t) { for (let i = 0; i < NUSTEPS.length; i++) { if (t < nNextStart(i)) return i; } return NUSTEPS.length - 1; }

function useNuLoop(duration) {
  const [t, setT] = useState(0);
  useEffect(() => {
    let raf, start = performance.now();
    const tick = (now) => {
      if (window.__forceT != null) setT(window.__forceT);
      else setT(((now - start) / 1000) % duration);
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [duration]);
  return t;
}

/* ---- final output panel: per 100g + per serve ---- */
function NutriPanel({ t }) {
  const calc = t < 5.5;
  const p = nprog(t, 5.5, 8.6);
  const done = t >= 8.6;
  return (
    <div className={'np' + (done ? ' np-done' : '')}>
      <div className="np-head">
        <div className="np-title">NUTRITIONAL INFORMATION</div>
        <div className="np-serve">Serving size <b>{NUDATA.serve} g</b></div>
      </div>
      <div className="np-rule"></div>
      {calc
        ? <div className="np-calc"><span className="np-spin"></span>Computing energy, macros &amp; micronutrients from recipe…</div>
        : <div className="np-table">
            <div className="np-thead">
              <span></span><b>per 100 g</b><b>per serve ({NUDATA.serve} g)</b><b>% RDA / serve</b>
            </div>
            {NUDATA.nutrition.map((r, i) => {
              const perServe = r[1] * (NUDATA.serve / 100);
              const rda = r[4] ? Math.round((perServe / r[4]) * 100 * p) : null;
              return (
                <div className="np-row" key={i}>
                  <span>{r[0]}</span>
                  <b className="mono">{(r[1] * p).toFixed(r[3])} <u>{r[2]}</u></b>
                  <b className="mono">{(perServe * p).toFixed(r[3])} <u>{r[2]}</u></b>
                  <b className="mono">{rda == null ? '\u2014' : rda + '%'}</b>
                </div>
              );
            })}
          </div>}
      <div className="np-foot mono">{done ? '✓ Computed from recipe · % RDA per serve vs. ICMR daily reference values' : 'analysing…'}</div>
    </div>
  );
}

/* ---- step input panels ---- */
function NuStepInputs({ stepKey, t }) {
  if (stepKey === 'ingredients') {
    return (
      <div className="si">
        <div className="si-tablehead"><span>Ingredient</span><span>%</span></div>
        {NUDATA.ingredients.map((r, i) => {
          const show = t >= 0.4 + i * 0.6;
          return <div className={'si-trow' + (show ? ' in' : '')} key={i}><span>{r[0]}</span><b className="mono">{r[1]}</b></div>;
        })}
      </div>
    );
  }
  // nutrition step renders the panel
  return <div className="nu-finalwrap"><NutriPanel t={t} /></div>;
}

function NutriSplit() {
  const t = useNuLoop(NULOOP);
  const ai = nActive(t);
  const isLast = ai === NUSTEPS.length - 1;
  const pct = ((ai + nprog(t, NUSTEPS[ai].win[0], nNextStart(ai))) / NUSTEPS.length) * 100;
  const summaries = { ingredients: '5 ingredients', nutrition: 'computed' };
  return (
    <div className={'vA' + (isLast ? ' vA-labelmode' : '')}>
      <div className="vA-form">
        <div className="vA-brand"><span className="dot"></span>Nutri<i>OS</i><span className="vA-badge mono">new analysis</span></div>
        <div className="vA-list">
          {NUSTEPS.map((s, i) => {
            const state = i < ai ? 'done' : i === ai ? 'active' : 'todo';
            return (
              <div className={'vA-item ' + state} key={s.key}>
                <div className="vA-irow">
                  <span className="vA-ix mono">{state === 'done' ? '✓' : String(i + 1).padStart(2, '0')}</span>
                  <span className="vA-ilabel">{s.label}</span>
                  {state === 'done' && <span className="vA-isum">{summaries[s.key]}</span>}
                </div>
                {state === 'active' && <div className="vA-ibody">{s.key === 'nutrition'
                  ? <div className="vA-finalwrap"><NutriPanel t={t} /></div>
                  : <NuStepInputs stepKey={s.key} t={t} />}</div>}
              </div>
            );
          })}
        </div>
        <div className="vA-prog"><i style={{ width: pct + '%' }}></i></div>
      </div>
    </div>
  );
}

Object.assign(window, { NUDATA, NUSTEPS, NULOOP, useNuLoop, NutriPanel, NutriSplit });
