// Sahh — Engine demo + Auth + Badge lifecycle + Retention KPIs
// Four big sections that drop into the v2 landing page.

// ============================================================
// 07 — ENGINE LIVE DEMO
// ============================================================
const EngineDemoSection = ({ t, dir }) => {
  const ar = dir === "rtl";
  const SAMPLE = ar
    ? "180جم صدر دجاج مشوي\n150جم أرز بسمتي مطبوخ\n½ حبة أفوكادو\n1 م.ك زيت زيتون\n60جم خس روماني\n30جم طحينة"
    : "180g chicken breast, grilled\n150g basmati rice, cooked\n½ avocado\n1 tbsp olive oil\n60g romaine lettuce\n30g tahini";
  const [text, setText] = React.useState(SAMPLE);
  const [result, setResult] = React.useState(null);
  const [busy, setBusy] = React.useState(false);

  const run = async () => {
    setBusy(true);
    const r = window.SahhEngine.computeRecipe(text, 1);
    // Only call Claude fallback when we have unresolved lines AND nothing was
    // resolved locally — otherwise the local engine is authoritative.
    if (r.unresolved.length > 0 && r.items.length === 0 && window.claude) {
      const ext = await window.SahhEngine.resolveWithClaude(r.unresolved);
      if (ext && Array.isArray(ext)) {
        for (const e of ext) {
          r.perServing.kcal += (e.kcal || 0);
          r.perServing.p += (e.p || 0);
          r.perServing.c += (e.c || 0);
          r.perServing.f += (e.f || 0);
        }
      }
    }
    setResult(r);
    setBusy(false);
  };

  React.useEffect(() => { run(); /* eslint-disable-next-line */ }, []);

  return (
    <section className="section" style={{ background: "var(--paper-2)" }} id="engine">
      <div className="container">
        <div className="section-head" style={{ textAlign: "center", margin: "0 auto 48px", maxWidth: 720 }}>
          <div className="eyebrow eyebrow-green">{ar ? "07 — المحرّك الحي" : "07 — Live engine"}</div>
          <h2 className="h-display" style={{ fontSize: "clamp(36px, 4vw, 56px)", margin: "16px auto", letterSpacing: "-0.04em", lineHeight: 1.04 }}>
            {ar ? "اكتب وصفة. شاهد المحرّك يعمل." : "Type a recipe. Watch the engine work."}
          </h2>
          <p style={{ color: "var(--ink-2)", fontSize: 17, lineHeight: 1.55, margin: 0 }}>
            {ar ? "ليس عرضاً — هذا هو المحرّك نفسه. قاعدة بيانات USDA + SFDA، تحليل لغة طبيعية، احتساب أتواتر، ودرجة صحّ خلال جزء من الثانية." : "Not a mock — this is the actual engine. USDA + SFDA database, natural-language parser, Atwater computation, and a Sahh Score in milliseconds."}
          </p>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 24 }} className="calc-grid">
          {/* Input */}
          <div className="card card-pad-lg">
            <div className="row" style={{ marginBottom: 12, justifyContent: "space-between" }}>
              <span className="chip chip-green chip-dot" style={{ fontSize: 11 }}>{ar ? "إدخال" : "Recipe input"}</span>
              <span className="mono" style={{ fontSize: 11, color: "var(--ink-3)" }}>{text.split(/\n/).filter(l=>l.trim()).length} {ar ? "أسطر" : "lines"}</span>
            </div>
            <textarea
              value={text}
              onChange={e => setText(e.target.value)}
              spellCheck={false}
              style={{
                width: "100%",
                minHeight: 220,
                background: "var(--paper)",
                border: "1px solid var(--hair)",
                borderRadius: 12,
                padding: 16,
                fontFamily: "var(--f-mono)",
                fontSize: 13,
                lineHeight: 1.7,
                color: "var(--ink)",
                resize: "vertical",
                outline: "none",
                direction: dir,
              }}
            />
            <div className="row" style={{ marginTop: 14, justifyContent: "space-between" }}>
              <div style={{ fontSize: 12, color: "var(--ink-3)" }}>
                {ar ? "اضغط احسب — يعمل محلياً، يتوسّع بـ Claude للمكوّنات النادرة." : "Press calculate — runs locally, falls back to Claude for rare items."}
              </div>
              <button className="btn btn-primary btn-sm" onClick={run} disabled={busy}>
                <Icon name="spark" size={13}/> {busy ? (ar?"يحسب…":"Calculating…") : (ar?"احسب":"Calculate")}
              </button>
            </div>
          </div>

          {/* Output */}
          <div className="card card-pad-lg" style={{ background: "var(--green-3)", color: "#fff" }}>
            {result && <EngineResult r={result} dir={dir} />}
          </div>
        </div>
      </div>
    </section>
  );
};

const EngineResult = ({ r, dir }) => {
  const ar = dir === "rtl";
  return (
    <div>
      <div className="row" style={{ justifyContent: "space-between", alignItems: "flex-start", marginBottom: 18 }}>
        <div>
          <div style={{ fontSize: 11, color: "var(--lime)", letterSpacing: "0.14em", textTransform: "uppercase", fontWeight: 700, fontFamily: "var(--f-mono)", marginBottom: 4 }}>
            Sahh Score
          </div>
          <div className="h-display tnum" style={{ fontSize: 72, color: "var(--lime)", lineHeight: 1 }}>{r.score}</div>
          <div style={{ fontSize: 11, color: "rgba(255,255,255,0.7)", marginTop: 4 }}>
            {ar ? "ثقة" : "confidence"} {Math.round(r.confidence * 100)}%
          </div>
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 4, alignItems: "flex-end" }}>
          {r.tags.map((tag, i) => (
            <span key={i} className="chip chip-lime" style={{ fontSize: 10, color: "var(--green-3)" }}>{ar ? tag.ar : tag.en}</span>
          ))}
        </div>
      </div>

      {/* macros */}
      <div style={{
        display: "grid",
        gridTemplateColumns: "repeat(4, 1fr)",
        gap: 8,
        padding: "16px 0",
        borderTop: "1px solid rgba(255,255,255,0.12)",
        borderBottom: "1px solid rgba(255,255,255,0.12)",
        marginBottom: 16,
      }}>
        {[
          [ar ? "سعرات" : "Calories", Math.round(r.perServing.kcal), "kcal"],
          [ar ? "بروتين" : "Protein", r.perServing.p.toFixed(1), "g"],
          [ar ? "كارب" : "Carbs", r.perServing.c.toFixed(1), "g"],
          [ar ? "دهون" : "Fat", r.perServing.f.toFixed(1), "g"],
        ].map(([l, v, u], i) => (
          <div key={i}>
            <div style={{ fontSize: 10, color: "rgba(255,255,255,0.6)", letterSpacing: "0.08em", textTransform: "uppercase", fontWeight: 600 }}>{l}</div>
            <div className="tnum" style={{ fontSize: 22, fontWeight: 700, marginTop: 2 }}>{v}<span style={{ fontSize: 11, opacity: 0.6, fontWeight: 500 }}> {u}</span></div>
          </div>
        ))}
      </div>

      {/* breakdown bars */}
      <div style={{ display: "flex", flexDirection: "column", gap: 7, marginBottom: 14 }}>
        {Object.entries(r.breakdown).map(([k, v]) => (
          <div key={k} className="row" style={{ gap: 10 }}>
            <div style={{ flex: 1, fontSize: 11, color: "rgba(255,255,255,0.75)", textTransform: "capitalize" }}>{k}</div>
            <div style={{ flex: 2, height: 5, background: "rgba(255,255,255,0.1)", borderRadius: 999, overflow: "hidden" }}>
              <div style={{ width: v + "%", height: "100%", background: "var(--lime)", borderRadius: 999 }} />
            </div>
            <div className="mono tnum" style={{ width: 28, textAlign: "end", fontSize: 11, color: "var(--lime)", fontWeight: 600 }}>{v}</div>
          </div>
        ))}
      </div>

      {/* sources */}
      <div style={{ fontSize: 10, color: "rgba(255,255,255,0.5)", fontFamily: "var(--f-mono)", lineHeight: 1.6 }}>
        {ar ? "المصادر:" : "Sources:"} {r.sources.slice(0, 3).join(" · ")}
        {r.unresolved.length > 0 && <span> · {r.unresolved.length} {ar ? "تقدير بـ Claude" : "Claude-estimated"}</span>}
      </div>
    </div>
  );
};

// ============================================================
// 08 — AUTH FLOWS  (3 roles, signup/login/MFA)
// ============================================================
const AuthSection = ({ t, dir }) => {
  const A = t.auth;
  const ar = dir === "rtl";
  const [role, setRole] = React.useState("R");
  const [stage, setStage] = React.useState("signin"); // signin | mfa

  return (
    <section className="section" id="auth">
      <div className="container">
        <div className="section-head" style={{ textAlign: "center", margin: "0 auto 48px", maxWidth: 720 }}>
          <div className="eyebrow eyebrow-green">{A.eyebrow}</div>
          <h2 className="h-display" style={{ fontSize: "clamp(36px, 4vw, 56px)", margin: "16px auto", letterSpacing: "-0.04em", lineHeight: 1.04 }}>{A.h2}</h2>
          <p style={{ color: "var(--ink-2)", fontSize: 17, lineHeight: 1.55, margin: 0 }}>{A.lede}</p>
        </div>

        {/* role switcher */}
        <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 12, marginBottom: 28 }} className="grid-flip">
          {[
            ["R", A.roleR, A.roleRSub, "chef"],
            ["K", A.roleK, A.roleKSub, "shield"],
            ["M", A.roleM, A.roleMSub, "scan"],
          ].map(([id, label, sub, icon]) => (
            <button key={id} onClick={() => setRole(id)} style={{
              padding: 18,
              borderRadius: 14,
              textAlign: ar ? "right" : "left",
              background: role === id ? "var(--ink)" : "var(--paper)",
              color: role === id ? "var(--paper)" : "var(--ink)",
              border: role === id ? "1px solid var(--ink)" : "1px solid var(--hair)",
              cursor: "pointer",
              transition: "all .15s",
            }}>
              <div className="row" style={{ gap: 10, marginBottom: 6 }}>
                <div style={{ width: 28, height: 28, borderRadius: 8, background: role === id ? "var(--lime)" : "var(--green-soft)", display: "grid", placeItems: "center" }}>
                  <Icon name={icon} size={14} color={role === id ? "var(--green-3)" : "var(--green)"} />
                </div>
                <div style={{ fontWeight: 700, fontSize: 14 }}>{label}</div>
              </div>
              <div style={{ fontSize: 12, color: role === id ? "rgba(255,255,255,0.6)" : "var(--ink-3)", lineHeight: 1.5 }}>{sub}</div>
            </button>
          ))}
        </div>

        {/* form + side */}
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 0, borderRadius: 24, overflow: "hidden", border: "1px solid var(--hair)", background: "var(--paper)" }} className="calc-grid">
          {/* Left: form */}
          <div style={{ padding: 40 }}>
            {stage === "signin" && (
              <div>
                <h3 style={{ fontFamily: "var(--f-display)", fontWeight: 800, fontSize: 24, letterSpacing: "-0.03em", margin: "0 0 6px" }}>{A.formTitle}</h3>
                <div style={{ fontSize: 13, color: "var(--ink-3)", marginBottom: 22 }}>{A.formSub}</div>

                <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                  <button className="btn btn-outline" style={{ justifyContent: "center", padding: "10px 14px" }}>
                    <svg width="14" height="14" viewBox="0 0 24 24"><path fill="#4285f4" d="M22 12.2c0-.7-.1-1.4-.2-2H12v3.9h5.6c-.2 1.3-1 2.4-2 3.1v2.6h3.3c1.9-1.8 3.1-4.4 3.1-7.6z"/><path fill="#34a853" d="M12 22c2.7 0 5-.9 6.7-2.4l-3.3-2.6c-.9.6-2 1-3.4 1-2.6 0-4.8-1.8-5.6-4.1H3v2.6C4.7 19.6 8.1 22 12 22z"/><path fill="#fbbc05" d="M6.4 13.9c-.2-.6-.3-1.2-.3-1.9s.1-1.3.3-1.9V7.5H3C2.4 8.9 2 10.4 2 12s.4 3.1 1 4.5l3.4-2.6z"/><path fill="#ea4335" d="M12 6c1.5 0 2.8.5 3.8 1.5l2.9-2.9C17 3 14.7 2 12 2 8.1 2 4.7 4.4 3 7.5l3.4 2.6c.8-2.3 3-4.1 5.6-4.1z"/></svg>
                    {A.ssoG}
                  </button>
                  {role === "R" && (
                    <button className="btn btn-outline" style={{ justifyContent: "center", padding: "10px 14px" }}>
                      <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M17.05 20.28c-.98.95-2.05.8-3.08.35-1.09-.46-2.09-.48-3.24 0-1.44.62-2.2.44-3.06-.35C2.79 15.25 3.51 7.59 9.05 7.31c1.35.07 2.29.74 3.08.8 1.18-.24 2.31-.93 3.57-.84 1.51.12 2.65.72 3.4 1.8-3.12 1.87-2.38 5.98.48 7.13-.57 1.5-1.31 2.99-2.54 4.09l.01-.01zM12 7.25c-.15-2.23 1.66-4.07 3.74-4.25.29 2.58-2.34 4.5-3.74 4.25z"/></svg>
                      {A.ssoA}
                    </button>
                  )}
                  {role !== "R" && (
                    <button className="btn btn-outline" style={{ justifyContent: "center", padding: "10px 14px" }}>
                      <Icon name="lock" size={13} /> {A.ssoSAML}
                    </button>
                  )}
                </div>

                <div className="row" style={{ gap: 10, color: "var(--ink-3)", fontSize: 11, margin: "16px 0" }}>
                  <div style={{ flex: 1, height: 1, background: "var(--hair)" }} />
                  <span>{ar ? "أو" : "OR"}</span>
                  <div style={{ flex: 1, height: 1, background: "var(--hair)" }} />
                </div>

                <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
                  <Field label={A.email} defaultValue={
                    role === "R" ? "layla@najdkitchen.sa" :
                    role === "K" ? "omar@kal.team" :
                    "inspector@moh.gov.sa"
                  } />
                  <Field label={A.password} type="password" defaultValue="••••••••••" />
                  <div className="row" style={{ justifyContent: "space-between", marginTop: 4 }}>
                    <label className="row" style={{ gap: 6, fontSize: 12, color: "var(--ink-3)", cursor: "pointer" }}>
                      <input type="checkbox" defaultChecked />
                      {A.remember}
                    </label>
                    <a href="#" style={{ fontSize: 12, color: "var(--green)", fontWeight: 500 }}>{A.forgot}</a>
                  </div>
                  <button className="btn btn-primary btn-lg" style={{ marginTop: 12, justifyContent: "center" }} onClick={() => setStage("mfa")}>
                    {A.submit} <Icon name="arrow" size={14} />
                  </button>
                </div>
              </div>
            )}

            {stage === "mfa" && (
              <div>
                <button onClick={() => setStage("signin")} style={{ fontSize: 12, color: "var(--ink-3)", marginBottom: 16, background: "none", border: "none", cursor: "pointer" }}>
                  ← {ar ? "رجوع" : "Back"}
                </button>
                <div style={{ width: 48, height: 48, borderRadius: 12, background: "var(--green-soft)", display: "grid", placeItems: "center", marginBottom: 18 }}>
                  <Icon name="shield" size={20} color="var(--green)" />
                </div>
                <h3 style={{ fontFamily: "var(--f-display)", fontWeight: 800, fontSize: 24, letterSpacing: "-0.03em", margin: "0 0 6px" }}>{A.mfaTitle}</h3>
                <div style={{ fontSize: 13, color: "var(--ink-3)", marginBottom: 22 }}>{A.mfaSub}</div>
                <div className="row" style={{ gap: 8, marginBottom: 16 }}>
                  {[3,1,4,1,5,9].map((d, i) => (
                    <input key={i} maxLength={1} defaultValue={d} style={{
                      width: 48, height: 56, textAlign: "center",
                      fontFamily: "var(--f-mono)", fontWeight: 700, fontSize: 22,
                      border: "1.5px solid var(--ink)", borderRadius: 10,
                      background: "var(--white)",
                    }} />
                  ))}
                </div>
                <label className="row" style={{ gap: 6, fontSize: 12, color: "var(--ink-3)", marginBottom: 16 }}>
                  <input type="checkbox" defaultChecked /> {A.mfaTrust}
                </label>
                <button className="btn btn-primary btn-lg" style={{ width: "100%", justifyContent: "center" }}>
                  {A.submit} <Icon name="arrow" size={14}/>
                </button>
                <div style={{ marginTop: 14, fontSize: 12, color: "var(--ink-3)", textAlign: "center" }}>
                  {ar ? "لم يصل الرمز؟" : "Didn't receive it?"} <a href="#" style={{ color: "var(--green)", fontWeight: 600 }}>{A.resend}</a>
                </div>
              </div>
            )}
          </div>

          {/* Right: contextual preview */}
          <div style={{
            background: role === "R" ? "var(--green-3)" : role === "K" ? "var(--ink)" : "var(--paper-2)",
            color: role === "M" ? "var(--ink)" : "#fff",
            padding: 40,
            position: "relative",
            overflow: "hidden",
            display: "flex",
            flexDirection: "column",
            justifyContent: "space-between",
          }}>
            <RolePreview role={role} dir={dir} />
            <div style={{ fontSize: 11, color: role === "M" ? "var(--ink-3)" : "rgba(255,255,255,0.5)", fontFamily: "var(--f-mono)", marginTop: 24 }}>
              {A.footMeta}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
};

const Field = ({ label, type = "text", defaultValue }) => (
  <div>
    <label style={{ display: "block", fontSize: 11, color: "var(--ink-3)", marginBottom: 4, fontWeight: 500 }}>{label}</label>
    <input type={type} defaultValue={defaultValue} style={{
      width: "100%",
      padding: "10px 12px",
      border: "1px solid var(--hair)",
      borderRadius: 10,
      background: "var(--white)",
      fontSize: 13,
      fontFamily: "inherit",
      outline: "none",
    }} />
  </div>
);

const RolePreview = ({ role, dir }) => {
  const ar = dir === "rtl";
  if (role === "R") {
    return (
      <div>
        <div style={{ fontSize: 11, color: "var(--lime)", letterSpacing: "0.14em", textTransform: "uppercase", fontWeight: 700, fontFamily: "var(--f-mono)", marginBottom: 12 }}>{ar ? "بعد الدخول" : "After sign-in"}</div>
        <div style={{ fontFamily: "var(--f-display)", fontWeight: 800, fontSize: 28, letterSpacing: "-0.03em", lineHeight: 1.1, marginBottom: 16 }}>
          {ar ? "نجد كيتشن · الرياض" : "Najd Kitchen · Riyadh"}
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
          {[
            [ar ? "أطباق نشطة" : "Active dishes", "127"],
            [ar ? "في انتظار التدقيق" : "Awaiting audit", "3"],
            [ar ? "مسحات اليوم" : "Scans today", "1,847"],
            [ar ? "متوسط مؤشر صح" : "Avg Sahh Score", "82"],
          ].map(([l, v], i) => (
            <div key={i} className="row" style={{ justifyContent: "space-between", padding: "8px 0", borderBottom: i < 3 ? "1px solid rgba(255,255,255,0.08)" : "none" }}>
              <span style={{ fontSize: 12, color: "rgba(255,255,255,0.7)" }}>{l}</span>
              <span className="mono tnum" style={{ fontSize: 14, fontWeight: 600, color: "var(--lime)" }}>{v}</span>
            </div>
          ))}
        </div>
      </div>
    );
  }
  if (role === "K") {
    return (
      <div>
        <div style={{ fontSize: 11, color: "var(--lime)", letterSpacing: "0.14em", textTransform: "uppercase", fontWeight: 700, fontFamily: "var(--f-mono)", marginBottom: 12 }}>{ar ? "قائمة المراجعة" : "Review queue"}</div>
        <div style={{ fontFamily: "var(--f-display)", fontWeight: 800, fontSize: 28, letterSpacing: "-0.03em", lineHeight: 1.1, marginBottom: 16 }}>
          {ar ? "8 طلبات تنتظرك" : "8 submissions waiting"}
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
          {[
            ["Najd Kitchen", "Lamb Mandi", "P1", "var(--danger)"],
            ["Maraheb", "Kunafa Cheese", "P2", "var(--warn)"],
            ["Bait Mandi", "Saffron Rice", "P2", "var(--warn)"],
            ["Cafe Nouri", "Date Bowl", "P3", "var(--lime)"],
          ].map(([rest, dish, prio, col], i) => (
            <div key={i} className="row" style={{ gap: 10, padding: "8px 0", borderBottom: i < 3 ? "1px solid rgba(255,255,255,0.08)" : "none" }}>
              <div style={{ width: 6, height: 6, borderRadius: "50%", background: col }} />
              <div style={{ flex: 1, fontSize: 12 }}>
                <div style={{ fontWeight: 600 }}>{dish}</div>
                <div style={{ color: "rgba(255,255,255,0.5)", fontSize: 11 }}>{rest}</div>
              </div>
              <span className="mono" style={{ fontSize: 10, color: col, fontWeight: 700 }}>{prio}</span>
            </div>
          ))}
        </div>
      </div>
    );
  }
  // ministry
  return (
    <div style={{ color: "var(--ink)" }}>
      <div style={{ fontSize: 11, color: "var(--green)", letterSpacing: "0.14em", textTransform: "uppercase", fontWeight: 700, fontFamily: "var(--f-mono)", marginBottom: 12 }}>{ar ? "السجل العام" : "Public registry"}</div>
      <div style={{ fontFamily: "var(--f-display)", fontWeight: 800, fontSize: 28, letterSpacing: "-0.03em", lineHeight: 1.1, marginBottom: 16, color: "var(--ink)" }}>
        {ar ? "1,247 مطعماً موثّقاً" : "1,247 verified restaurants"}
      </div>
      <div style={{ background: "var(--white)", border: "1px solid var(--hair)", borderRadius: 12, padding: 14, marginBottom: 10 }}>
        <div className="row" style={{ gap: 8, marginBottom: 6 }}>
          <Icon name="search" size={14} color="var(--ink-3)" />
          <span style={{ fontSize: 12, color: "var(--ink-3)" }}>{ar ? "ابحث عن مطعم أو طبق…" : "Search restaurant or dish…"}</span>
        </div>
      </div>
      <div style={{ fontSize: 12, color: "var(--ink-3)", lineHeight: 1.6 }}>
        {ar ? "وصول للقراءة فقط · سجلات تدقيق كاملة · تصدير CSV" : "Read-only access · Full audit logs · CSV export"}
      </div>
    </div>
  );
};

// ============================================================
// 09 — BADGE LIFECYCLE
// ============================================================
const BadgeLifecycleSection = ({ t, dir }) => {
  const B = t.badge;
  const ar = dir === "rtl";
  const [active, setActive] = React.useState(1); // ACTIVE by default

  const STATE_COLORS = {
    ISSUED:   { bg: "var(--green-soft)", fg: "var(--green-3)", line: "var(--green)" },
    ACTIVE:   { bg: "var(--lime-soft)",  fg: "var(--green-3)", line: "var(--lime-2)" },
    EXPIRING: { bg: "#FFF1E0",           fg: "#7A4A10",        line: "var(--warn)" },
    REVOKED:  { bg: "#FBE6E2",           fg: "#7A2418",        line: "var(--danger)" },
    LOCKED:   { bg: "var(--paper-2)",    fg: "var(--ink)",     line: "var(--ink-3)" },
  };

  return (
    <section className="section" style={{ background: "var(--paper-2)" }} id="badges">
      <div className="container">
        <div className="section-head" style={{ textAlign: "center", margin: "0 auto 48px", maxWidth: 720 }}>
          <div className="eyebrow eyebrow-green">{B.eyebrow}</div>
          <h2 className="h-display" style={{ fontSize: "clamp(36px, 4vw, 56px)", margin: "16px auto", letterSpacing: "-0.04em", lineHeight: 1.04 }}>{B.h2}</h2>
          <p style={{ color: "var(--ink-2)", fontSize: 17, lineHeight: 1.55, margin: 0 }}>{B.lede}</p>
        </div>

        {/* state strip — clickable */}
        <div style={{ display: "grid", gridTemplateColumns: "repeat(5, 1fr)", gap: 12, marginBottom: 28 }} className="grid-flip">
          {B.states.map(([code, label, desc, when], i) => {
            const col = STATE_COLORS[code];
            const isActive = i === active;
            return (
              <button key={code} onClick={() => setActive(i)} style={{
                padding: 18,
                borderRadius: 14,
                background: isActive ? col.bg : "var(--white)",
                border: isActive ? `1.5px solid ${col.line}` : "1px solid var(--hair)",
                textAlign: ar ? "right" : "left",
                cursor: "pointer",
                transition: "all .18s",
              }}>
                <div className="mono" style={{ fontSize: 10, color: col.line, fontWeight: 700, letterSpacing: "0.1em", marginBottom: 8 }}>0{i+1}</div>
                <div style={{ fontFamily: "var(--f-display)", fontWeight: 700, fontSize: 16, letterSpacing: "-0.02em", marginBottom: 4, color: isActive ? col.fg : "var(--ink)" }}>{label}</div>
                <div style={{ fontSize: 11, color: "var(--ink-3)" }}>{when}</div>
              </button>
            );
          })}
        </div>

        {/* Active state preview */}
        <div style={{ display: "grid", gridTemplateColumns: "1.2fr 1fr", gap: 32, alignItems: "stretch" }} className="calc-grid">
          {/* Sample badge in this state */}
          <div className="card card-pad-lg">
            <BadgePreview state={B.states[active][0]} stateLabel={B.states[active][1]} colors={STATE_COLORS[B.states[active][0]]} dir={dir} />
          </div>

          <div>
            <div className="mono" style={{ fontSize: 11, color: "var(--green)", fontWeight: 700, letterSpacing: "0.12em", marginBottom: 8 }}>
              0{active+1} · {B.states[active][0]}
            </div>
            <h3 style={{ fontFamily: "var(--f-display)", fontWeight: 800, fontSize: 32, letterSpacing: "-0.03em", margin: "0 0 14px" }}>{B.states[active][1]}</h3>
            <p style={{ fontSize: 15, color: "var(--ink-2)", lineHeight: 1.6, margin: "0 0 24px" }}>{B.states[active][2]}</p>

            {/* Trigger events */}
            <div style={{ borderTop: "1px solid var(--hair)", paddingTop: 20 }}>
              <div className="eyebrow" style={{ marginBottom: 12, fontSize: 11 }}>{B.eventsTitle}</div>
              <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                {B.events.map(([trigger, desc, target], i) => {
                  const col = STATE_COLORS[target];
                  return (
                    <div key={i} className="row" style={{ gap: 12, padding: "10px 12px", background: "var(--white)", borderRadius: 10, border: "1px solid var(--hair)" }}>
                      <div style={{ width: 4, height: 32, background: col.line, borderRadius: 2, flexShrink: 0 }} />
                      <div style={{ flex: 1 }}>
                        <div style={{ fontSize: 13, fontWeight: 600, color: "var(--ink)" }}>{trigger}</div>
                        <div style={{ fontSize: 11, color: "var(--ink-3)" }}>{desc}</div>
                      </div>
                      <span className="mono" style={{ fontSize: 9, fontWeight: 700, padding: "4px 8px", background: col.bg, color: col.fg, borderRadius: 999, letterSpacing: "0.08em" }}>→ {target}</span>
                    </div>
                  );
                })}
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
};

const BadgePreview = ({ state, stateLabel, colors, dir }) => {
  const ar = dir === "rtl";
  return (
    <div>
      <div style={{
        position: "relative",
        background: state === "REVOKED" ? "#3A1714" : state === "LOCKED" ? "var(--ink)" : "var(--green-3)",
        color: "#fff",
        borderRadius: 18,
        padding: 28,
        overflow: "hidden",
      }}>
        {state === "REVOKED" && (
          <div aria-hidden style={{ position: "absolute", inset: 0, backgroundImage: "repeating-linear-gradient(45deg, transparent 0 12px, rgba(255,255,255,0.04) 12px 14px)" }} />
        )}
        <div style={{ position: "relative" }}>
          <div className="row" style={{ justifyContent: "space-between", alignItems: "flex-start", marginBottom: 20 }}>
            <div>
              <div style={{ fontSize: 10, color: colors.line === "var(--ink-3)" ? "var(--ink-4)" : "var(--lime)", letterSpacing: "0.16em", textTransform: "uppercase", fontWeight: 700, fontFamily: "var(--f-mono)", marginBottom: 6 }}>
                Sahh · {stateLabel}
              </div>
              <div style={{ fontFamily: "var(--f-display)", fontWeight: 800, fontSize: 22, letterSpacing: "-0.025em", lineHeight: 1.1 }}>
                {ar ? "بول دجاج مشوي" : "Grilled Chicken Bowl"}
              </div>
              <div style={{ fontSize: 11, color: "rgba(255,255,255,0.6)", marginTop: 4 }}>
                {ar ? "نجد كيتشن · الرياض" : "Najd Kitchen · Riyadh"}
              </div>
            </div>
            <SahhScoreRing value={state === "REVOKED" ? 0 : state === "LOCKED" ? 86 : 86} size={68} dark />
          </div>

          {/* state-specific footer */}
          {state === "ISSUED" && (
            <div className="mono" style={{ fontSize: 10, color: "var(--lime)", letterSpacing: "0.08em" }}>
              ✓ {ar ? "صادرة قبل دقائق" : "Issued moments ago"} · ID SH-7K2-441
            </div>
          )}
          {state === "ACTIVE" && (
            <div className="row" style={{ gap: 8, fontSize: 10, color: "rgba(255,255,255,0.7)" }}>
              <span className="mono">ID SH-7K2-441</span>
              <span style={{ opacity: 0.4 }}>·</span>
              <span className="tnum">8,431 {ar ? "مسحة" : "scans"}</span>
              <span style={{ opacity: 0.4 }}>·</span>
              <span>{ar ? "ساري حتى مارس 2027" : "Valid through Mar 2027"}</span>
            </div>
          )}
          {state === "EXPIRING" && (
            <div style={{ background: "rgba(224,138,42,0.15)", border: "1px solid rgba(224,138,42,0.4)", borderRadius: 8, padding: "8px 12px", fontSize: 11, color: "#FFD8A8" }}>
              ⚠ {ar ? "تنتهي خلال 18 يوماً — أعد التدقيق بنقرة" : "Expires in 18 days — re-audit in one click"}
            </div>
          )}
          {state === "REVOKED" && (
            <div style={{ background: "rgba(196,70,55,0.18)", border: "1px solid rgba(196,70,55,0.4)", borderRadius: 8, padding: "8px 12px", fontSize: 11, color: "#FFB8AE" }}>
              ✕ {ar ? "ملغاة · تعديل وصفة دون تدقيق · 12 مارس" : "Revoked · Recipe drift, un-audited · 12 Mar"}
            </div>
          )}
          {state === "LOCKED" && (
            <div style={{ background: "rgba(255,255,255,0.08)", border: "1px solid rgba(255,255,255,0.18)", borderRadius: 8, padding: "8px 12px", fontSize: 11, color: "rgba(255,255,255,0.85)" }}>
              <Icon name="lock" size={11} color="var(--lime)" /> {ar ? "قيد تفتيش الوزارة · قراءة فقط" : "Under MoH inspection · read-only"}
            </div>
          )}
        </div>
      </div>

      {/* registry link */}
      <div style={{ marginTop: 14, padding: 14, background: "var(--paper)", border: "1px dashed var(--hair-2)", borderRadius: 12, fontSize: 11, color: "var(--ink-3)", fontFamily: "var(--f-mono)" }}>
        sahh.sa/r/SH-7K2-441 → {ar ? "صفحة السجل العام" : "Public registry page"}
      </div>
    </div>
  );
};

// ============================================================
// 10 — RETENTION KPIs
// ============================================================
const RetentionSection = ({ t, dir }) => {
  const K = t.kpis;
  const ar = dir === "rtl";

  return (
    <section className="section" id="retention">
      <div className="container">
        <div className="section-head" style={{ textAlign: "center", margin: "0 auto 48px", maxWidth: 720 }}>
          <div className="eyebrow eyebrow-green">{K.eyebrow}</div>
          <h2 className="h-display" style={{ fontSize: "clamp(36px, 4vw, 56px)", margin: "16px auto", letterSpacing: "-0.04em", lineHeight: 1.04 }}>{K.h2}</h2>
          <p style={{ color: "var(--ink-2)", fontSize: 17, lineHeight: 1.55, margin: 0 }}>{K.lede}</p>
        </div>

        {/* Headline trio */}
        <div className="grid-3" style={{ gap: 16, marginBottom: 28 }}>
          {[
            [K.logoTitle, K.logoStat, K.logoNote, "var(--green)"],
            [K.nrrTitle, K.nrrStat, K.nrrNote, "var(--lime-2)"],
            [K.ttvTitle, K.ttvStat, K.ttvNote, "var(--ink)"],
          ].map(([title, stat, note, col], i) => (
            <div key={i} className="card card-pad-lg" style={{ position: "relative", overflow: "hidden" }}>
              <div aria-hidden style={{ position: "absolute", top: 0, [ar ? "right" : "left"]: 0, width: 4, height: "100%", background: col }} />
              <div className="eyebrow" style={{ marginBottom: 8, fontSize: 11 }}>{title}</div>
              <div className="h-display tnum" style={{ fontSize: 56, color: col, lineHeight: 1, letterSpacing: "-0.04em" }}>{stat}</div>
              <div style={{ marginTop: 10, fontSize: 13, color: "var(--ink-3)", lineHeight: 1.55 }}>{note}</div>
            </div>
          ))}
        </div>

        {/* Drivers + Churn signals */}
        <div style={{ display: "grid", gridTemplateColumns: "1.2fr 1fr", gap: 20, marginBottom: 28 }} className="calc-grid">
          {/* Drivers */}
          <div className="card card-pad-lg">
            <div className="row" style={{ justifyContent: "space-between", marginBottom: 4 }}>
              <h3 style={{ fontFamily: "var(--f-display)", fontWeight: 700, fontSize: 20, letterSpacing: "-0.025em", margin: 0 }}>{K.driversTitle}</h3>
              <span className="chip chip-green chip-dot" style={{ fontSize: 11 }}>Q1 2026</span>
            </div>
            <div style={{ fontSize: 12, color: "var(--ink-3)", marginBottom: 18 }}>{K.driversSub}</div>
            <div style={{ display: "flex", flexDirection: "column", gap: 0 }}>
              {K.drivers.map(([name, val, unit, delta, why], i) => (
                <div key={i} style={{ padding: "16px 0", borderTop: i === 0 ? "none" : "1px solid var(--hair)" }}>
                  <div className="row" style={{ alignItems: "baseline", gap: 12, marginBottom: 4 }}>
                    <div style={{ fontWeight: 600, fontSize: 14, flex: 1 }}>{name}</div>
                    <div className="h-display tnum" style={{ fontSize: 26, lineHeight: 1, letterSpacing: "-0.03em" }}>{val}</div>
                    <div className="mono tnum" style={{ fontSize: 11, color: delta.startsWith("-") ? "var(--danger)" : "var(--green)", fontWeight: 700, minWidth: 48, textAlign: "end" }}>{delta}</div>
                  </div>
                  <div className="row" style={{ gap: 8 }}>
                    <span className="mono" style={{ fontSize: 11, color: "var(--ink-3)" }}>{unit}</span>
                  </div>
                  <div style={{ fontSize: 12, color: "var(--ink-2)", lineHeight: 1.5, marginTop: 6 }}>{why}</div>
                </div>
              ))}
            </div>
          </div>

          {/* Churn */}
          <div className="card card-pad-lg" style={{ background: "var(--ink)", color: "#fff" }}>
            <div className="row" style={{ justifyContent: "space-between", marginBottom: 4 }}>
              <h3 style={{ fontFamily: "var(--f-display)", fontWeight: 700, fontSize: 20, letterSpacing: "-0.025em", margin: 0 }}>{K.churnTitle}</h3>
              <span className="mono" style={{ fontSize: 10, color: "var(--lime)", letterSpacing: "0.1em", fontWeight: 700 }}>● LIVE</span>
            </div>
            <div style={{ fontSize: 12, color: "rgba(255,255,255,0.6)", marginBottom: 18 }}>{K.churnSub}</div>
            <div style={{ display: "flex", flexDirection: "column", gap: 0 }}>
              {K.churn.map(([signal, sev, count, color], i) => (
                <div key={i} className="row" style={{ gap: 10, padding: "12px 0", borderTop: i === 0 ? "none" : "1px solid rgba(255,255,255,0.08)" }}>
                  <div style={{ width: 8, height: 8, borderRadius: "50%", background: color, flexShrink: 0 }} />
                  <div style={{ flex: 1, fontSize: 13 }}>{signal}</div>
                  <div className="mono tnum" style={{ fontSize: 11, color: "rgba(255,255,255,0.7)" }}>{count}</div>
                  <span className="mono" style={{ fontSize: 9, color, fontWeight: 700, letterSpacing: "0.08em", textTransform: "uppercase" }}>{sev}</span>
                </div>
              ))}
            </div>
          </div>
        </div>

        {/* Cohort retention curves */}
        <div className="card card-pad-lg" style={{ marginBottom: 28 }}>
          <div className="row" style={{ justifyContent: "space-between", marginBottom: 4 }}>
            <h3 style={{ fontFamily: "var(--f-display)", fontWeight: 700, fontSize: 20, letterSpacing: "-0.025em", margin: 0 }}>{K.cohortsTitle}</h3>
            <span className="chip chip-lime" style={{ fontSize: 11 }}>NRR 118%</span>
          </div>
          <div style={{ fontSize: 12, color: "var(--ink-3)", marginBottom: 24 }}>{K.cohortsSub}</div>
          <CohortChart dir={dir} />
        </div>

        {/* Retention nudges */}
        <div>
          <div className="row" style={{ justifyContent: "space-between", marginBottom: 16 }}>
            <h3 style={{ fontFamily: "var(--f-display)", fontWeight: 700, fontSize: 20, letterSpacing: "-0.025em", margin: 0 }}>{K.nudgeTitle}</h3>
          </div>
          <div className="grid-2" style={{ gap: 12 }}>
            {K.nudges.map(([title, desc], i) => (
              <div key={i} className="card card-pad" style={{ display: "flex", gap: 14, alignItems: "flex-start" }}>
                <div style={{ width: 32, height: 32, borderRadius: 8, background: "var(--lime-soft)", display: "grid", placeItems: "center", flexShrink: 0 }}>
                  <Icon name={["bell","star","trend","mail"][i]} size={14} color="var(--green-3)" />
                </div>
                <div>
                  <div style={{ fontWeight: 700, fontSize: 14, marginBottom: 2 }}>{title}</div>
                  <div style={{ fontSize: 12, color: "var(--ink-3)", lineHeight: 1.5 }}>{desc}</div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
};

const CohortChart = ({ dir }) => {
  // 6 quarters × 8 month points; values = NRR-style retention
  const cohorts = [
    { label: "Q1'25", color: "var(--ink-4)",   data: [100, 102, 99, 101, 104, 108, 113, 119] },
    { label: "Q2'25", color: "var(--ink-3)",   data: [100, 103, 105, 108, 112, 116, 120, null] },
    { label: "Q3'25", color: "var(--green)",   data: [100, 105, 109, 113, 117, 121, null, null] },
    { label: "Q4'25", color: "var(--lime-2)",  data: [100, 107, 113, 119, 125, null, null, null] },
  ];
  const xs = ["M0","M2","M4","M6","M8","M10","M12","M14"];
  const W = 800, H = 280, P = 30;
  const xScale = i => P + (i / (xs.length - 1)) * (W - P * 2);
  const yScale = v => P + ((140 - v) / 70) * (H - P * 2); // 70..140 range

  return (
    <div style={{ width: "100%" }}>
      <svg viewBox={`0 0 ${W} ${H}`} style={{ width: "100%", height: "auto", maxHeight: 320 }}>
        {/* gridlines */}
        {[80, 100, 120, 140].map(y => (
          <g key={y}>
            <line x1={P} x2={W-P} y1={yScale(y)} y2={yScale(y)} stroke="var(--hair)" strokeDasharray="2 4" />
            <text x={P-6} y={yScale(y)+4} fontSize="10" textAnchor="end" fill="var(--ink-3)" fontFamily="var(--f-mono)">{y}%</text>
          </g>
        ))}
        {/* x labels */}
        {xs.map((x, i) => (
          <text key={i} x={xScale(i)} y={H-8} fontSize="10" textAnchor="middle" fill="var(--ink-3)" fontFamily="var(--f-mono)">{x}</text>
        ))}
        {/* baseline 100 */}
        <line x1={P} x2={W-P} y1={yScale(100)} y2={yScale(100)} stroke="var(--ink-3)" strokeWidth="1" />
        {/* lines */}
        {cohorts.map((c, ci) => {
          const pts = c.data.map((v, i) => v == null ? null : `${xScale(i)},${yScale(v)}`).filter(Boolean).join(" L");
          return (
            <g key={c.label}>
              <path d={`M${pts}`} stroke={c.color} strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round" />
              {c.data.map((v, i) => v == null ? null : (
                <circle key={i} cx={xScale(i)} cy={yScale(v)} r="3" fill={c.color} />
              ))}
            </g>
          );
        })}
      </svg>
      {/* legend */}
      <div className="row" style={{ gap: 18, marginTop: 12, justifyContent: "center", flexWrap: "wrap" }}>
        {cohorts.map(c => (
          <div key={c.label} className="row" style={{ gap: 6 }}>
            <span style={{ width: 10, height: 10, borderRadius: 2, background: c.color }} />
            <span className="mono" style={{ fontSize: 11, color: "var(--ink-2)" }}>{c.label}</span>
          </div>
        ))}
      </div>
    </div>
  );
};

window.EngineDemoSection = EngineDemoSection;
window.AuthSection = AuthSection;
window.BadgeLifecycleSection = BadgeLifecycleSection;
window.RetentionSection = RetentionSection;
