// Program Studio — Simulate tab
// Bulk-run the current rule set against 12,847 historical cases.
// Shows before/after outcome distribution, a table of changed cases,
// and a chart comparing the two configurations.

function StudioSimulate({ rules, parentRules, lib, caseImpacts }) {
  const [scenario, setScenario] = React.useState("last-90"); // last-90 | last-12mo | sohar-only | high-dti
  const [running, setRunning] = React.useState(false);
  const [done, setDone] = React.useState(true);
  const [filter, setFilter] = React.useState("changed"); // all | changed | newly-eligible | newly-rejected

  const SCENARIOS = {
    "last-90": { name: "Last 90 days · all governorates", n: 4214, base: { stp: 2837, review: 1086, rej: 291 }, prop: { stp: 3142, review: 920, rej: 152 } },
    "last-12mo": { name: "Last 12 months · all governorates", n: 12847, base: { stp: 8642, review: 3210, rej: 995 }, prop: { stp: 9412, review: 2840, rej: 595 } },
    "sohar-only": { name: "Sohar wilayat · last 12 months", n: 2104, base: { stp: 1342, review: 587, rej: 175 }, prop: { stp: 1612, review: 412, rej: 80 } },
    "high-dti": { name: "DTI > 40% cases · last 12 months", n: 1840, base: { stp: 0, review: 1421, rej: 419 }, prop: { stp: 312, review: 1280, rej: 248 } },
  };
  const s = SCENARIOS[scenario];

  function runSimulation() {
    setRunning(true);
    setDone(false);
    setTimeout(() => {
      setRunning(false);
      setDone(true);
    }, 1400);
  }

  // Synthesize changed cases
  const changedCases = React.useMemo(() => generateChangedCases(s, filter), [scenario, filter]);

  return (
    <div className="studio-simulate">
      <div className="sim-head">
        <div>
          <div className="label-eyebrow">What-if simulation</div>
          <h2 className="h2" style={{marginTop:4, fontSize:26}}>Run this rule set against real history.</h2>
          <p className="muted text-14" style={{maxWidth:560, marginTop:8}}>
            Replay {s.n.toLocaleString()} historical applications through your draft. See exactly which cases would have changed outcome — and which citizens would benefit before you approve the change.
          </p>
        </div>
        <div className="sim-controls">
          <div className="field-label">Scenario</div>
          <select className="select" value={scenario} onChange={(e) => setScenario(e.target.value)}>
            {Object.entries(SCENARIOS).map(([id, sc]) => <option key={id} value={id}>{sc.name}</option>)}
          </select>
          <button className="btn copper lg" onClick={runSimulation} disabled={running}>
            {running ? <><Icon name="refresh" size={14}/> Running…</> : <><Icon name="play" size={14}/> Run simulation</>}
          </button>
        </div>
      </div>

      {running && (
        <div className="sim-running card card-pad-lg">
          <div className="sim-running-anim">
            <div className="sim-ring"/><div className="sim-ring d1"/><div className="sim-ring d2"/>
            <Icon name="play" size={28} style={{color:"var(--brand-copper)"}}/>
          </div>
          <div className="title" style={{marginTop:14}}>Replaying {s.n.toLocaleString()} cases…</div>
          <div className="muted text-13">Re-running 8 integrations per case in parallel.</div>
          <div className="sim-progress"><div className="sim-progress-fill"/></div>
        </div>
      )}

      {done && !running && <SimResults scenario={s} filter={filter} setFilter={setFilter} changedCases={changedCases}/>}
    </div>
  );
}

function SimResults({ scenario: s, filter, setFilter, changedCases }) {
  const delta = {
    stp: s.prop.stp - s.base.stp,
    review: s.prop.review - s.base.review,
    rej: s.prop.rej - s.base.rej,
  };
  const stpRateBase = (s.base.stp / s.n);
  const stpRateProp = (s.prop.stp / s.n);

  return (
    <>
      {/* Top KPIs */}
      <div className="sim-kpis">
        <SimKpi label="Cases replayed" value={s.n.toLocaleString()} icon="users"/>
        <SimKpi label="STP rate change" value={`${((stpRateProp - stpRateBase) * 100).toFixed(1)}pp`} sub={`${Math.round(stpRateBase * 100)}% → ${Math.round(stpRateProp * 100)}%`} kind="up"/>
        <SimKpi label="More auto-approved" value={`+${delta.stp.toLocaleString()}`} sub="citizens move to STP" kind="ok"/>
        <SimKpi label="Fewer rejections" value={delta.rej.toLocaleString()} sub="citizens un-blocked" kind="warn"/>
      </div>

      {/* Distribution comparison */}
      <div className="card card-pad-lg" style={{marginTop:18}}>
        <div className="between">
          <div>
            <div className="label-eyebrow">Outcome distribution</div>
            <div className="title" style={{marginTop:4, fontSize:16}}>Current (v4.2) vs Draft (v4.3)</div>
          </div>
          <div className="row" style={{gap:14}}>
            <LegendDot color="#1b4149" label="Eligible · STP"/>
            <LegendDot color="#eaa07a" label="Needs review"/>
            <LegendDot color="#a33028" label="Rejected"/>
          </div>
        </div>

        <div className="sim-bars">
          <DistBar label="Current · v4.2" stp={s.base.stp} review={s.base.review} rej={s.base.rej} total={s.n}/>
          <DistBar label="Draft · v4.3" stp={s.prop.stp} review={s.prop.review} rej={s.prop.rej} total={s.n} highlight/>
        </div>


      </div>

      {/* Changed cases table */}
      <div className="card card-pad-lg sim-table-card">
        <div className="between" style={{marginBottom:16}}>
          <div>
            <div className="label-eyebrow">Changed cases</div>
            <div className="title" style={{marginTop:4, fontSize:16}}>{changedCases.length} of {s.n.toLocaleString()} cases would route differently</div>
          </div>
          <div className="filter-chip-group">
            {[
              ["all", `All (${s.n.toLocaleString()})`],
              ["changed", `Changed (${Math.abs(delta.stp) + Math.abs(delta.rej)})`],
              ["newly-eligible", `Newly eligible (+${delta.stp})`],
              ["newly-rejected", `No longer rejected (${delta.rej})`],
            ].map(([id, label]) => (
              <button key={id} className={`chip ${filter === id ? "active" : ""}`} onClick={() => setFilter(id)}>{label}</button>
            ))}
          </div>
        </div>

        <div className="sim-table">
          <div className="sim-table-row sim-table-head">
            <span>Case</span>
            <span>Citizen</span>
            <span>Governorate</span>
            <span>Trigger rule</span>
            <span>v4.2 outcome</span>
            <span>v4.3 outcome</span>
            <span/>
          </div>
          {changedCases.map((c) => (
            <div key={c.id} className="sim-table-row">
              <span className="mono text-13">{c.id}</span>
              <span style={{fontWeight:600}}>{c.name}</span>
              <span className="muted text-13">{c.gov}</span>
              <span><span className="pill ghost tiny">{c.trigger}</span></span>
              <span><span className={`pill ${c.from === "stp" ? "ok" : c.from === "review" ? "warn" : "bad"}`}>{outcomeLabel(c.from)}</span></span>
              <span>
                <span className="row" style={{gap:4}}>
                  <Icon name="arrow_right" size={11} style={{color:"var(--muted)"}}/>
                  <span className={`pill ${c.to === "stp" ? "ok" : c.to === "review" ? "warn" : "bad"}`}>{outcomeLabel(c.to)}</span>
                </span>
              </span>
              <button className="btn ghost sm icon-only"><Icon name="eye" size={12}/></button>
            </div>
          ))}
        </div>

        <div className="sim-table-foot muted text-13">
          Showing {changedCases.length} cases · <button className="link">Export full diff (CSV)</button>
        </div>
      </div>
    </>
  );
}

function generateChangedCases(s, filter) {
  const seedNames = [
    ["Khalid Al-Busaidi", "Sohar", "DTI"],
    ["Aisha Al-Riyami", "Muscat", "DTI"],
    ["Said Al-Habsi", "Salalah", "Income band"],
    ["Noor Al-Hinai", "Sohar", "DTI"],
    ["Tariq Al-Saadi", "Muscat", "Income band"],
    ["Fatma Al-Lawati", "Nizwa", "Documents"],
    ["Hamed Al-Kindi", "Sohar", "DTI"],
    ["Sarah Al-Maamari", "Salalah", "DTI"],
    ["Yusuf Al-Hashimi", "Muscat", "Income band"],
    ["Mariam Al-Zadjali", "Sohar", "DTI"],
    ["Hassan Al-Mahrooqi", "Sur", "DTI"],
    ["Lubna Al-Ismaili", "Muscat", "Income band"],
  ];
  return seedNames.map((s2, i) => ({
    id: `C-${49100 + i * 17}`,
    name: s2[0],
    gov: s2[1],
    trigger: s2[2],
    from: i < 9 ? "review" : "rejected",
    to: i < 7 ? "stp" : "review",
  })).filter((c) =>
    filter === "all" ? true :
    filter === "changed" ? c.from !== c.to :
    filter === "newly-eligible" ? c.to === "stp" :
    filter === "newly-rejected" ? c.from === "rejected" && c.to !== "rejected" :
    true
  );
}

function outcomeLabel(o) {
  return o === "stp" ? "STP" : o === "review" ? "Review" : "Reject";
}

function SimKpi({ label, value, sub, kind, icon }) {
  return (
    <div className={`sim-kpi tone-${kind || ""}`}>
      <div className="sim-kpi-label">{label}</div>
      <div className="sim-kpi-value">{value}</div>
      {sub && <div className="sim-kpi-sub">{sub}</div>}
    </div>
  );
}

function LegendDot({ color, label }) {
  return (
    <span className="row" style={{gap:6}}>
      <span style={{width:8, height:8, borderRadius:2, background: color}}/>
      <span className="tiny" style={{color:"var(--ink-soft)"}}>{label}</span>
    </span>
  );
}

function DistBar({ label, stp, review, rej, total, highlight }) {
  const stpPct = (stp / total) * 100;
  const reviewPct = (review / total) * 100;
  const rejPct = (rej / total) * 100;
  return (
    <div className={`dist-bar-row ${highlight ? "highlight" : ""}`}>
      <div className="dist-bar-label">
        <span className="text-13" style={{fontWeight: highlight ? 700 : 500}}>{label}</span>
        <span className="tiny muted">{total.toLocaleString()} cases</span>
      </div>
      <div className="dist-bar">
        <div className="dist-seg stp" style={{width: `${stpPct}%`}} title={`STP: ${stp}`}>
          {stpPct > 8 && <span>{Math.round(stpPct)}%</span>}
        </div>
        <div className="dist-seg review" style={{width: `${reviewPct}%`}}>
          {reviewPct > 8 && <span>{Math.round(reviewPct)}%</span>}
        </div>
        <div className="dist-seg rej" style={{width: `${rejPct}%`}}>
          {rejPct > 5 && <span>{Math.round(rejPct)}%</span>}
        </div>
      </div>
    </div>
  );
}

function FlowDiagram({ base, prop, total }) {
  // Sankey-style flow showing where cases moved
  // Compute movements: review→stp, rejected→review, etc.
  const movedToStp = Math.max(0, prop.stp - base.stp);
  const movedToReview = Math.max(0, prop.review - base.review);
  const stillStp = base.stp;
  const stillReview = Math.min(base.review, prop.review);
  const stillRej = Math.min(base.rej, prop.rej);

  return (
    <div className="sim-flow">
      <div className="sim-flow-label">Where cases moved</div>
      <svg viewBox="0 0 720 160" className="sim-flow-svg" preserveAspectRatio="xMidYMid meet">
        {/* Left column (v4.2) */}
        <g>
          <rect x="0" y="10" width="160" height={base.stp / total * 130} fill="#1b4149"/>
          <rect x="0" y={20 + base.stp / total * 130} width="160" height={base.review / total * 130} fill="#eaa07a"/>
          <rect x="0" y={30 + (base.stp + base.review) / total * 130} width="160" height={base.rej / total * 130} fill="#a33028"/>
          <text x="80" y="155" fontSize="11" fontWeight="700" textAnchor="middle" fill="#6b6662">v4.2</text>
        </g>
        {/* Right column (v4.3) */}
        <g transform="translate(560, 0)">
          <rect x="0" y="10" width="160" height={prop.stp / total * 130} fill="#1b4149"/>
          <rect x="0" y={20 + prop.stp / total * 130} width="160" height={prop.review / total * 130} fill="#eaa07a"/>
          <rect x="0" y={30 + (prop.stp + prop.review) / total * 130} width="160" height={prop.rej / total * 130} fill="#a33028"/>
          <text x="80" y="155" fontSize="11" fontWeight="700" textAnchor="middle" fill="#6b6662">v4.3 (draft)</text>
        </g>
        {/* Sankey ribbons */}
        <g opacity="0.55">
          <path d={`M 160 ${10 + stillStp/total*65} C 360 ${10 + stillStp/total*65}, 360 ${10 + stillStp/total*65}, 560 ${10 + stillStp/total*65}`} stroke="#1b4149" strokeWidth={stillStp/total*130} fill="none" opacity="0.85"/>
          <path d={`M 160 ${50 + base.stp/total*130} C 360 ${50 + base.stp/total*130}, 360 ${30 + stillStp/total*130}, 560 ${30 + stillStp/total*130}`} stroke="#eaa07a" strokeWidth={movedToStp/total*130} fill="none"/>
          <path d={`M 160 ${60 + (base.stp+base.review)/total*130} C 360 ${60 + (base.stp+base.review)/total*130}, 360 ${80}, 560 ${80}`} stroke="#a33028" strokeWidth="6" fill="none"/>
        </g>
        {/* Center annotations */}
        <g transform="translate(360, 80)">
          <rect x="-80" y="-20" width="160" height="40" rx="20" fill="#fff" stroke="#e3ddd4"/>
          <text x="0" y="-2" textAnchor="middle" fontSize="11" fontWeight="700" fill="#1b4149">+{movedToStp.toLocaleString()} → STP</text>
          <text x="0" y="12" textAnchor="middle" fontSize="10" fill="#6b6662">From review queue</text>
        </g>
      </svg>
    </div>
  );
}

window.StudioSimulate = StudioSimulate;
