// Digital Twin — live virtual replica of an industrial asset (Bhopal 220kV substation).
const TWIN_ASSETS = [
  { id: "sub-bhopal", name: "Substation — Bhopal 220kV", type: "Power", health: 94, warn: true },
  { id: "plant-vindhya", name: "NTPC Vindhyachal — Unit 3", type: "Thermal", health: 97, warn: false },
  { id: "wtp-indore", name: "Water Treatment — Indore", type: "Water", health: 91, warn: false },
  { id: "smartcity-nagpur", name: "Smart City Grid — Nagpur", type: "City", health: 88, warn: true },
];

const TWIN_TELEMETRY = [
  { k: "Bus Voltage", v: "218.4 kV", st: "ok", spark: [216,217,218,219,218,218,218] },
  { k: "Line Current", v: "1,284 A", st: "ok", spark: [1180,1220,1250,1240,1270,1284,1284] },
  { k: "Transformer Oil Temp", v: "68 °C", st: "warn", spark: [58,60,62,64,66,68,68] },
  { k: "Load Factor", v: "94 %", st: "ok", spark: [82,84,88,92,89,94,94] },
  { k: "Frequency", v: "49.98 Hz", st: "ok", spark: [49.9,50.0,49.98,49.99,49.97,49.98,49.98] },
  { k: "Power Factor", v: "0.97", st: "ok", spark: [0.95,0.96,0.96,0.97,0.97,0.97,0.97] },
];

const TWIN_COMPONENTS = [
  { c: "Incoming Line 220kV", health: 98, next: "Sep 2026", st: "ok" },
  { c: "Transformer T-118", health: 76, next: "Overdue · 18h", st: "warn" },
  { c: "Busbar A", health: 96, next: "Nov 2026", st: "ok" },
  { c: "Feeder CB-1/2/3", health: 93, next: "Oct 2026", st: "ok" },
  { c: "Battery Storage 40MWh", health: 89, next: "Dec 2026", st: "ok" },
  { c: "SCADA / RTU", health: 99, next: "—", st: "ok" },
];

function Hotspot({ x, y, label, value, warn }) {
  const c = warn ? "var(--danger)" : "var(--ok)";
  const bw = Math.max(label.length, value.length) * 5.6 + 16;
  const bx = Math.max(2, x - bw / 2);
  return (
    <g>
      <circle cx={x} cy={y} r="16" fill={c} opacity=".12"><animate attributeName="r" values="10;18;10" dur="2s" repeatCount="indefinite"/><animate attributeName="opacity" values="0.2;0.02;0.2" dur="2s" repeatCount="indefinite"/></circle>
      <circle cx={x} cy={y} r="5" fill={c} stroke="var(--panel)" strokeWidth="2"/>
      <line x1={x} y1={y - 3} x2={x} y2={y - 14} stroke={c} strokeWidth="1.3"/>
      <g transform={`translate(${bx} ${y - 42})`}>
        <rect width={bw} height="28" rx="5" fill="var(--panel)" stroke={warn ? 'var(--danger)' : 'var(--border-strong)'} strokeWidth={warn ? 1.4 : 1}/>
        <text x="8" y="12" fontSize="8.5" fill="var(--ink-3)" fontFamily="Inter" fontWeight="600">{label}</text>
        <text x="8" y="22" fontSize="10" fill={warn ? 'var(--danger)' : 'var(--ink)'} fontFamily="JetBrains Mono" fontWeight="700">{value}</text>
      </g>
    </g>
  );
}

function TwinSim() {
  const [load, setLoad] = useState(94);
  const oil = Math.round(68 + (load - 94) * 0.9);
  const risk = oil >= 78 ? "High" : oil >= 72 ? "Elevated" : "Nominal";
  const riskColor = risk === "High" ? "var(--danger)" : risk === "Elevated" ? "var(--accent-2)" : "var(--ok)";
  return (
    <div className="card">
      <div className="card-head"><div><h3>Simulate — Load Scenario</h3><div className="sub">Physics-informed · what-if on the twin</div></div><Icon name="beaker" size={14} style={{ color: 'var(--primary)' }}/></div>
      <div className="card-body">
        <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11.5, marginBottom: 5 }}>
          <span style={{ color: 'var(--ink-2)' }}>Feeder load</span><span className="mono" style={{ color: 'var(--primary)', fontWeight: 600 }}>{load}%</span>
        </div>
        <input type="range" min={70} max={110} value={load} onChange={e => setLoad(Number(e.target.value))} style={{ width: '100%', accentColor: load > 100 ? 'var(--danger)' : 'var(--primary)' }}/>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginTop: 14 }}>
          <div style={{ padding: 10, borderRadius: 8, background: 'var(--panel-2)', border: '1px solid var(--border)' }}>
            <div style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '.06em', color: 'var(--ink-4)', fontWeight: 600 }}>Predicted oil temp</div>
            <div className="mono" style={{ fontSize: 22, fontWeight: 600, marginTop: 3, color: oil >= 75 ? 'var(--danger)' : 'var(--ink)' }}>{oil}°C</div>
          </div>
          <div style={{ padding: 10, borderRadius: 8, background: 'var(--panel-2)', border: '1px solid var(--border)' }}>
            <div style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '.06em', color: 'var(--ink-4)', fontWeight: 600 }}>Failure risk</div>
            <div style={{ fontSize: 18, fontWeight: 700, marginTop: 5, color: riskColor }}>{risk}</div>
          </div>
        </div>
        <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 10 }}>Threshold 75°C. At {load}% load the thermal model {oil >= 75 ? 'breaches limit — shed load or start cooling.' : 'stays within safe envelope.'}</div>
      </div>
    </div>
  );
}

function TwinScreen() {
  const [asset, setAsset] = useState("sub-bhopal");
  return (
    <div className="screen">
      <div className="screen-head">
        <div>
          <div className="screen-title" style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            Digital Twin
            <span className="tag ok"><span className="live-dot"/>SYNCED · 42ms</span>
          </div>
          <div className="screen-sub">Real-time virtual replica · physics-informed simulation · predictive maintenance · fed by 2,148 sensors</div>
        </div>
        <div className="screen-actions">
          <select value={asset} onChange={e => setAsset(e.target.value)} style={{ height: 32, borderRadius: 8, border: '1px solid var(--border-strong)', background: 'var(--panel)', color: 'var(--ink)', fontFamily: 'inherit', fontSize: 12.5, padding: '0 10px' }}>
            {TWIN_ASSETS.map(a => <option key={a.id} value={a.id}>{a.name}</option>)}
          </select>
          <button className="btn"><Icon name="refresh"/>Re-sync</button>
          <button className="btn primary"><Icon name="beaker"/>Run scenario</button>
        </div>
      </div>

      <div className="grid g-4" style={{ marginBottom: 14 }}>
        <div className="card kpi" style={{ padding: 13 }}><div className="label"><Icon name="heart" size={12}/>Twin health</div><div className="value">94<span className="unit">%</span></div><div className="delta" style={{ color: 'var(--accent-2)' }}><Icon name="alert" size={12}/>1 component at risk</div></div>
        <div className="card kpi" style={{ padding: 13 }}><div className="label"><Icon name="zap" size={12}/>Efficiency</div><div className="value">96.8<span className="unit">%</span></div><div className="delta up"><Icon name="trending" size={12}/>+0.4% vs model</div></div>
        <div className="card kpi" style={{ padding: 13 }}><div className="label"><Icon name="thermometer" size={12}/>Predicted maint.</div><div className="value" style={{ color: 'var(--danger)' }}>18<span className="unit">hrs</span></div><div className="delta" style={{ color: 'var(--danger)' }}>Transformer T-118</div></div>
        <div className="card kpi" style={{ padding: 13 }}><div className="label"><Icon name="activity" size={12}/>Throughput</div><div className="value">218<span className="unit">MW</span></div><div className="delta up" style={{ color: 'var(--ink-3)' }}>94% of capacity</div></div>
      </div>

      <div className="grid" style={{ gridTemplateColumns: '1.7fr 1fr', marginBottom: 14 }}>
        <div className="card">
          <div className="card-head"><div><h3>Live Twin — 220kV Substation</h3><div className="sub">Bhopal · sensor overlay · click a hotspot for detail</div></div><span className="tag ok"><span className="live-dot"/>Streaming</span></div>
          <div className="card-body" style={{ background: 'var(--panel-2)', borderRadius: '0 0 var(--radius) var(--radius)' }}>
            <svg viewBox="0 0 620 320" width="100%">
              <defs><marker id="flow" markerWidth="7" markerHeight="7" refX="5" refY="3" orient="auto"><path d="M0 0 L5 3 L0 6 Z" fill="var(--accent-2)"/></marker></defs>
              {/* flow line */}
              {[[60, 90, 180, 90], [230, 90, 230, 160], [230, 200, 350, 200], [400, 200, 520, 130], [400, 200, 520, 260]].map((e, i) => (
                <path key={i} d={`M ${e[0]} ${e[1]} L ${e[2]} ${e[3]}`} stroke="var(--accent)" strokeWidth="2.4" fill="none" strokeDasharray="6 5" opacity=".7" markerEnd="url(#flow)"><animate attributeName="stroke-dashoffset" values="22;0" dur="0.8s" repeatCount="indefinite"/></path>
              ))}
              {/* equipment */}
              {[
                { x: 20, y: 74, w: 60, h: 32, t: "GRID", s: "220kV" },
                { x: 180, y: 66, w: 100, h: 48, t: "TRANSFORMER", s: "T-118" },
                { x: 200, y: 176, w: 60, h: 26, t: "BUSBAR A", s: "" },
                { x: 350, y: 180, w: 56, h: 40, t: "BREAKER", s: "CB-1" },
                { x: 522, y: 108, w: 76, h: 34, t: "FEEDER 1", s: "City-N" },
                { x: 522, y: 244, w: 76, h: 34, t: "FEEDER 2", s: "Ind-Zone" },
              ].map((b, i) => (
                <g key={i}>
                  <rect x={b.x} y={b.y} width={b.w} height={b.h} rx="6" fill="var(--panel)" stroke={b.s === 'T-118' ? 'var(--danger)' : 'var(--border-strong)'} strokeWidth={b.s === 'T-118' ? 2 : 1.2}/>
                  <text x={b.x + b.w / 2} y={b.y + (b.s ? b.h / 2 - 2 : b.h / 2 + 3)} fontSize="8.5" fontWeight="700" fill="var(--ink-2)" textAnchor="middle" fontFamily="Inter">{b.t}</text>
                  {b.s && <text x={b.x + b.w / 2} y={b.y + b.h / 2 + 10} fontSize="9" fill="var(--primary)" textAnchor="middle" fontFamily="JetBrains Mono" fontWeight="600">{b.s}</text>}
                </g>
              ))}
              {/* solar inject */}
              <g><rect x="180" y="250" width="70" height="30" rx="6" fill="var(--ok-tint)" stroke="var(--ok)"/><text x="215" y="269" fontSize="8.5" fontWeight="700" fill="var(--ok)" textAnchor="middle">SOLAR 8.4MW</text><path d="M215 250 L 230 210" stroke="var(--ok)" strokeWidth="2" strokeDasharray="5 4" opacity=".7"/></g>
              {/* hotspots — labels float above the equipment they annotate */}
              <Hotspot x={230} y={66} label="Oil Temp" value="68°C ⚠" warn/>
              <Hotspot x={50} y={74} label="Bus V" value="218.4kV"/>
              <Hotspot x={230} y={176} label="Load" value="94%"/>
            </svg>
          </div>
        </div>

        <div className="vstack">
          <div className="card">
            <div className="card-head" style={{ padding: '10px 12px' }}><h3 style={{ fontSize: 12 }}>Live Telemetry</h3><span className="tag ok" style={{ fontSize: 10 }}><span className="live-dot"/>2,148 tags</span></div>
            <div className="card-body" style={{ padding: 0 }}>
              {TWIN_TELEMETRY.map((t, i) => (
                <div key={i} style={{ padding: '8px 12px', borderTop: i ? '1px solid var(--border)' : 0, display: 'flex', alignItems: 'center', gap: 10 }}>
                  <span className={`live-dot ${t.st === 'warn' ? 'warn' : ''}`} style={{ width: 6, height: 6 }}/>
                  <span style={{ flex: 1, fontSize: 12, color: 'var(--ink-2)' }}>{t.k}</span>
                  <Sparkline data={t.spark} w={54} h={18} stroke={t.st === 'warn' ? 'var(--accent-2)' : 'var(--ok)'}/>
                  <span className="mono" style={{ fontSize: 12, fontWeight: 600, minWidth: 62, textAlign: 'right', color: t.st === 'warn' ? 'var(--accent-2)' : 'var(--ink)' }}>{t.v}</span>
                </div>
              ))}
            </div>
          </div>
          <TwinSim/>
        </div>
      </div>

      <div className="grid" style={{ gridTemplateColumns: '1.4fr 1fr' }}>
        <div className="card">
          <div className="card-head"><div><h3>Component Health &amp; Maintenance</h3><div className="sub">Predictive · remaining useful life</div></div><button className="btn sm"><Icon name="download" size={11}/>Work orders</button></div>
          <div className="card-body" style={{ padding: 0 }}>
            <table className="data">
              <thead><tr><th>Component</th><th className="num">Health</th><th>Next maintenance</th><th>Status</th></tr></thead>
              <tbody>
                {TWIN_COMPONENTS.map((c, i) => (
                  <tr key={i}>
                    <td style={{ fontWeight: 500 }}>{c.c}</td>
                    <td className="num">
                      <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6, justifyContent: 'flex-end' }}>
                        <div style={{ width: 40, height: 4, background: 'var(--panel-3)', borderRadius: 2, overflow: 'hidden' }}><div style={{ width: `${c.health}%`, height: '100%', background: c.health >= 90 ? 'var(--ok)' : c.health >= 80 ? 'var(--accent)' : 'var(--danger)' }}/></div>
                        <span style={{ fontWeight: 600 }}>{c.health}%</span>
                      </div>
                    </td>
                    <td className="small mono" style={{ color: c.st === 'warn' ? 'var(--danger)' : 'var(--ink-2)' }}>{c.next}</td>
                    <td>{c.st === 'ok' ? <span className="tag ok">Healthy</span> : <span className="tag danger">At risk</span>}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
        <div className="ai-strip" style={{ alignSelf: 'start' }}>
          <div className="glyph"><Icon name="sparkles"/></div>
          <div style={{ flex: 1 }}>
            <div className="title">Predictive maintenance alert</div>
            <div className="body" style={{ fontSize: 12 }}>The twin's thermal model projects <b>Transformer T-118</b> oil temperature will cross 75°C within <b>18–24 hours</b> at current load. Recommend load-shed of 6% or start forced cooling.</div>
            <div className="actions">
              <button className="btn sm"><Icon name="checkSquare" size={12}/>Create work order</button>
              <button className="btn sm"><Icon name="wind" size={12}/>Start cooling</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

window.TwinScreen = TwinScreen;
