// ML Studio — Predictive, Prescriptive, Time-Series, AutoML, Explainable AI.
const ML_MODELS = [
  { name: "Demand Forecast — GeM SKUs", algo: "Prophet + LGBM", target: "units_next_qtr", acc: 94.2, status: "Production", trained: "2h ago", drift: "ok" },
  { name: "Vendor Fraud Detection", algo: "XGBoost", target: "is_fraud", acc: 97.8, status: "Production", trained: "1d ago", drift: "ok" },
  { name: "Tender Volume Forecast", algo: "LSTM", target: "tenders_90d", acc: 91.4, status: "Production", trained: "6h ago", drift: "warn" },
  { name: "Transformer Failure Predict", algo: "Random Forest", target: "fail_24h", acc: 96.1, status: "Production", trained: "3h ago", drift: "ok" },
  { name: "Scheme Uptake — Churn", algo: "LightGBM", target: "will_lapse", acc: 88.6, status: "Staging", trained: "12h ago", drift: "warn" },
  { name: "Revenue Forecast (state)", algo: "Prophet", target: "rev_next_month", acc: 92.9, status: "Production", trained: "4h ago", drift: "ok" },
  { name: "Crop Yield Estimator", algo: "Ensemble + CNN", target: "yield_qtl_ha", acc: 89.3, status: "Staging", trained: "1d ago", drift: "ok" },
];

const ML_FEATURES = [
  { f: "Festival index", w: 0.28 },
  { f: "GST filings", w: 0.19 },
  { f: "Prev 90d demand", w: 0.15 },
  { f: "Rainfall dev.", w: 0.12 },
  { f: "Vendor lead time", w: 0.10 },
  { f: "Price index", w: 0.09 },
  { f: "Holiday count", w: 0.07 },
];

const AUTOML = [
  { model: "LightGBM", metric: "RMSE 41.2", score: 94.2, best: true },
  { model: "XGBoost", metric: "RMSE 44.8", score: 92.6 },
  { model: "Prophet", metric: "RMSE 48.1", score: 91.0 },
  { model: "ElasticNet", metric: "RMSE 61.4", score: 84.2 },
  { model: "ARIMA", metric: "RMSE 68.9", score: 80.1 },
];

function ForecastChart({ history, forecast, upper, lower, labels, w = 620, h = 250 }) {
  const pad = { t: 14, r: 14, b: 26, l: 44 };
  const iw = w - pad.l - pad.r, ih = h - pad.t - pad.b;
  const all = [...history, ...forecast, ...upper, ...lower];
  const min = Math.min(...all) * 0.94, max = Math.max(...all) * 1.02;
  const range = max - min || 1;
  const n = history.length + forecast.length;
  const xStep = iw / (n - 1);
  const X = (i) => pad.l + i * xStep;
  const Y = (v) => pad.t + ih - ((v - min) / range) * ih;
  const histPts = history.map((v, i) => [X(i), Y(v)]);
  const hIdx = history.length - 1;
  const fcPts = forecast.map((v, i) => [X(hIdx + i), Y(v)]);
  const upPts = [[X(hIdx), Y(history[hIdx])], ...upper.map((v, i) => [X(hIdx + 1 + i), Y(v)])];
  const loPts = [[X(hIdx), Y(history[hIdx])], ...lower.map((v, i) => [X(hIdx + 1 + i), Y(v)])];
  const bandD = [...upPts.map((p, i) => `${i ? 'L' : 'M'} ${p[0].toFixed(1)} ${p[1].toFixed(1)}`),
                 ...loPts.slice().reverse().map(p => `L ${p[0].toFixed(1)} ${p[1].toFixed(1)}`), 'Z'].join(' ');
  const line = (pts) => pts.map((p, i) => `${i ? 'L' : 'M'} ${p[0].toFixed(1)} ${p[1].toFixed(1)}`).join(' ');
  return (
    <svg width="100%" height={h} viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none" style={{ display: 'block', overflow: 'visible' }}>
      {Array.from({ length: 5 }).map((_, i) => {
        const y = pad.t + (ih / 4) * i;
        return <line key={i} x1={pad.l} x2={w - pad.r} y1={y} y2={y} stroke="var(--border)" strokeDasharray={i === 4 ? "" : "2 3"} />;
      })}
      {Array.from({ length: 5 }).map((_, i) => {
        const y = pad.t + (ih / 4) * i; const v = max - (range / 4) * i;
        return <text key={i} x={pad.l - 6} y={y + 3} fontSize="10" fill="var(--ink-3)" textAnchor="end" fontFamily="JetBrains Mono">{Math.round(v)}</text>;
      })}
      {labels.map((l, i) => (i % 3 === 0 || i === n - 1) ? <text key={i} x={X(i)} y={h - 8} fontSize="9.5" fill="var(--ink-3)" textAnchor="middle">{l}</text> : null)}
      <line x1={X(hIdx)} x2={X(hIdx)} y1={pad.t} y2={pad.t + ih} stroke="var(--accent-2)" strokeWidth="1" strokeDasharray="3 3" opacity=".6" />
      <text x={X(hIdx) + 4} y={pad.t + 10} fontSize="9" fill="var(--accent-2)" fontWeight="600">now</text>
      <path d={bandD} fill="var(--primary)" opacity=".12" />
      <path d={line(histPts)} fill="none" stroke="var(--primary)" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" />
      <path d={line(fcPts)} fill="none" stroke="var(--accent-2)" strokeWidth="2.2" strokeDasharray="5 4" strokeLinecap="round" strokeLinejoin="round" />
      {fcPts.map((p, i) => <circle key={i} cx={p[0]} cy={p[1]} r="2.4" fill="var(--panel)" stroke="var(--accent-2)" strokeWidth="1.5" />)}
    </svg>
  );
}

function WhatIf() {
  const [mkt, setMkt] = useState(40);
  const [price, setPrice] = useState(0);
  const [festival, setFestival] = useState(60);
  const base = 1290;
  const predicted = Math.round(base * (1 + (mkt - 40) / 220) * (1 - price / 140) * (1 + (festival - 60) / 260));
  const delta = ((predicted - base) / base) * 100;
  const rows = [
    { label: "Marketing spend", val: mkt, set: setMkt, min: 0, max: 100, unit: "₹ index" },
    { label: "Price change", val: price, set: setPrice, min: -20, max: 20, unit: "%" },
    { label: "Festival intensity", val: festival, set: setFestival, min: 0, max: 100, unit: "index" },
  ];
  return (
    <div className="card">
      <div className="card-head">
        <div><h3>What-if Simulation</h3><div className="sub">Prescriptive · scenario planning</div></div>
        <span className="tag primary"><Icon name="target" size={10}/>Live</span>
      </div>
      <div className="card-body">
        {rows.map((r, i) => (
          <div key={i} style={{ marginBottom: 14 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11.5, marginBottom: 5 }}>
              <span style={{ color: 'var(--ink-2)' }}>{r.label}</span>
              <span className="mono" style={{ color: 'var(--primary)', fontWeight: 600 }}>{r.val > 0 && r.unit === '%' ? '+' : ''}{r.val} <span style={{ color: 'var(--ink-3)', fontWeight: 400 }}>{r.unit}</span></span>
            </div>
            <input type="range" min={r.min} max={r.max} value={r.val} onChange={e => r.set(Number(e.target.value))}
              style={{ width: '100%', accentColor: 'var(--primary)' }}/>
          </div>
        ))}
        <div style={{ marginTop: 14, padding: 14, borderRadius: 10, background: 'linear-gradient(135deg, var(--primary-tint), var(--accent-tint) 130%)', border: '1px solid color-mix(in oklch, var(--primary), transparent 80%)' }}>
          <div style={{ fontSize: 10.5, textTransform: 'uppercase', letterSpacing: '.06em', color: 'var(--ink-3)', fontWeight: 600 }}>Predicted demand — next quarter</div>
          <div className="mono" style={{ fontSize: 30, fontWeight: 600, color: 'var(--ink)', marginTop: 4 }}>{fmtNum(predicted * 1000)}</div>
          <div style={{ fontSize: 12, marginTop: 2, color: delta >= 0 ? 'var(--ok)' : 'var(--danger)', fontWeight: 600, display: 'flex', alignItems: 'center', gap: 4 }}>
            <Icon name={delta >= 0 ? 'trending' : 'trendingDown'} size={13}/>{fmtPct(delta)} vs baseline · units
          </div>
        </div>
      </div>
    </div>
  );
}

function MLStudioScreen() {
  const months = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec","Jan","Feb","Mar","Apr","May","Jun"];
  const history = [820,845,910,880,940,1010,1060,1040,1120,1180,1210,1290];
  const forecast = [1330,1370,1420,1460,1500,1560];
  const upper = [1370,1440,1520,1600,1680,1780];
  const lower = [1300,1310,1330,1350,1360,1380];

  return (
    <div className="screen">
      <div className="screen-head">
        <div>
          <div className="screen-title">ML Studio &amp; Forecasting</div>
          <div className="screen-sub">24 models · <span style={{ color: 'var(--ok)' }}>19 in production</span> · AutoML + Explainable AI · MLflow registry · Predictive &amp; prescriptive</div>
        </div>
        <div className="screen-actions">
          <button className="btn"><Icon name="beaker"/>Notebooks</button>
          <button className="btn"><Icon name="sparkles"/>AutoML run</button>
          <button className="btn primary"><Icon name="rocket"/>Train &amp; deploy</button>
        </div>
      </div>

      <div className="grid g-4" style={{ marginBottom: 14 }}>
        <div className="card kpi"><div className="label"><Icon name="brain" size={12}/>Models in production</div><div className="value">19<span className="unit">/24</span></div><div className="delta up"><Icon name="trending" size={13}/>+3 this month</div></div>
        <div className="card kpi"><div className="label"><Icon name="target" size={12}/>Avg accuracy</div><div className="value">94.2<span className="unit">%</span></div><div className="delta up"><Icon name="trending" size={13}/>+1.4% vs baseline</div></div>
        <div className="card kpi"><div className="label"><Icon name="zap" size={12}/>Predictions today</div><div className="value">2.4<span className="unit">M</span></div><div className="delta up" style={{ color: 'var(--ink-3)' }}>GPU · 42ms p95</div></div>
        <div className="card kpi"><div className="label"><Icon name="alert" size={12}/>Drift alerts</div><div className="value" style={{ color: 'var(--accent-2)' }}>3</div><div className="delta" style={{ color: 'var(--accent-2)' }}><Icon name="alert" size={12}/>2 models need retrain</div></div>
      </div>

      <div className="grid" style={{ gridTemplateColumns: '2fr 1fr', marginBottom: 14 }}>
        <div className="card">
          <div className="card-head">
            <div><h3>Demand Forecast — GeM SKUs</h3><div className="sub">Prophet + LightGBM · 6-month horizon · 92% confidence band</div></div>
            <div className="card-actions">
              <div className="hstack" style={{ fontSize: 11, color: 'var(--ink-3)' }}>
                <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}><span style={{ width: 8, height: 8, borderRadius: 2, background: 'var(--primary)' }}/>Actual</span>
                <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}><span style={{ width: 12, height: 3, borderRadius: 2, background: 'var(--accent-2)' }}/>Forecast</span>
              </div>
              <button className="icon-btn"><Icon name="moreH"/></button>
            </div>
          </div>
          <div className="card-body"><ForecastChart history={history} forecast={forecast} upper={upper} lower={lower} labels={months}/></div>
        </div>
        <WhatIf/>
      </div>

      <div className="grid" style={{ gridTemplateColumns: '1.55fr 1fr', marginBottom: 14 }}>
        <div className="card">
          <div className="card-head">
            <div><h3>Model Registry</h3><div className="sub">MLflow · versioned · auto-monitored for drift</div></div>
            <button className="btn sm"><Icon name="plus" size={11}/>Register</button>
          </div>
          <div className="card-body" style={{ padding: 0 }}>
            <table className="data">
              <thead><tr><th>Model</th><th>Algorithm</th><th className="num">Accuracy</th><th>Status</th><th>Trained</th></tr></thead>
              <tbody>
                {ML_MODELS.map((m, i) => (
                  <tr key={i}>
                    <td>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                        <span className={`live-dot ${m.drift === 'ok' ? '' : 'warn'}`} title={m.drift === 'ok' ? 'No drift' : 'Drift detected'}/>
                        <div style={{ fontWeight: 500 }}>{m.name}</div>
                      </div>
                      <div className="mono" style={{ fontSize: 10.5, color: 'var(--ink-4)', marginLeft: 16 }}>{m.target}</div>
                    </td>
                    <td><span className="tag" style={{ fontSize: 10.5 }}>{m.algo}</span></td>
                    <td className="num">
                      <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6, justifyContent: 'flex-end' }}>
                        <div style={{ width: 34, height: 4, background: 'var(--panel-3)', borderRadius: 2, overflow: 'hidden' }}><div style={{ width: `${m.acc}%`, height: '100%', background: m.acc >= 95 ? 'var(--ok)' : m.acc >= 90 ? 'var(--primary)' : 'var(--accent)' }}/></div>
                        <span style={{ fontWeight: 600 }}>{m.acc}%</span>
                      </div>
                    </td>
                    <td><span className={`tag ${m.status === 'Production' ? 'ok' : 'warn'}`}>{m.status}</span></td>
                    <td className="small mono" style={{ color: 'var(--ink-3)' }}>{m.trained}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>

        <div className="vstack">
          <div className="card">
            <div className="card-head"><div><h3>Feature Importance</h3><div className="sub">SHAP · Demand Forecast</div></div><span className="tag primary" style={{ fontSize: 10 }}><Icon name="eye" size={10}/>XAI</span></div>
            <div className="card-body"><BarChart data={ML_FEATURES.map(f => f.w)} labels={ML_FEATURES.map(f => f.f)} horizontal w={300} h={170} format={v => v.toFixed(2)} color="var(--primary)" accent="var(--accent)"/></div>
          </div>
          <div className="card">
            <div className="card-head"><div><h3>AutoML Leaderboard</h3><div className="sub">42 candidates · 5-fold CV</div></div></div>
            <div className="card-body" style={{ padding: 0 }}>
              {AUTOML.map((a, i) => (
                <div key={i} style={{ padding: '9px 12px', borderTop: i ? '1px solid var(--border)' : 0, display: 'flex', alignItems: 'center', gap: 10 }}>
                  <span className="mono" style={{ fontSize: 11, color: 'var(--ink-4)', width: 16 }}>{i + 1}</span>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 12, fontWeight: 500, display: 'flex', alignItems: 'center', gap: 6 }}>{a.model}{a.best && <span className="tag ok" style={{ fontSize: 9.5 }}><Icon name="star" size={9}/>Best</span>}</div>
                    <div className="mono" style={{ fontSize: 10.5, color: 'var(--ink-3)' }}>{a.metric}</div>
                  </div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <div style={{ width: 46, height: 4, background: 'var(--panel-3)', borderRadius: 2, overflow: 'hidden' }}><div style={{ width: `${a.score}%`, height: '100%', background: a.best ? 'var(--ok)' : 'var(--primary)' }}/></div>
                    <span className="mono" style={{ fontSize: 11.5, fontWeight: 600 }}>{a.score}</span>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>

      <div className="ai-strip">
        <div className="glyph"><Icon name="sparkles"/></div>
        <div style={{ flex: 1 }}>
          <div className="title">Prescriptive recommendations <span className="tag primary">Optimizer</span></div>
          <div className="body">
            • <b>Increase safety stock 8%</b> for medical &amp; electronics SKUs before the festival window — forecast shows a ₹42 Cr demand surge in Oct–Nov.<br/>
            • <b>Retrain "Tender Volume Forecast"</b> — feature drift on <span className="mono" style={{ color: 'var(--primary)' }}>bid_lead_time</span> exceeds 0.15 PSI threshold.<br/>
            • <b>Shift ₹6 Cr procurement</b> from Q3 to Q2 to smooth the predicted supply bottleneck in Karnataka.
          </div>
          <div className="actions">
            <button className="btn sm"><Icon name="check" size={12}/>Apply plan</button>
            <button className="btn sm"><Icon name="beaker" size={12}/>Simulate</button>
            <button className="btn sm"><Icon name="refresh" size={12}/>Retrain now</button>
          </div>
        </div>
      </div>
    </div>
  );
}

window.MLStudioScreen = MLStudioScreen;
