/* Cloud / SaaS dashboard section — for managers */

function CloudDashboardMock() {
  const [tab, setTab] = React.useState('fleet');
  const [tick, setTick] = React.useState(0);

  React.useEffect(() => {
    const t = setInterval(() => setTick(x => x + 1), 1800);
    return () => clearInterval(t);
  }, []);

  // Fake but realistic line data
  const lines = [
    { id: 'BLR-A1', name: 'Bangalore · A1', status: 'ok', yield: 99.2, units: 12847, defects: 102, trend: '+0.3' },
    { id: 'BLR-A2', name: 'Bangalore · A2', status: 'ok', yield: 98.8, units: 11203, defects: 134, trend: '−0.1' },
    { id: 'CHI-B1', name: 'Chihuahua · B1', status: 'warn', yield: 96.4, units: 9482, defects: 341, trend: '−1.4' },
    { id: 'CHI-B2', name: 'Chihuahua · B2', status: 'ok', yield: 99.0, units: 8930, defects: 89, trend: '+0.2' },
    { id: 'PRG-C1', name: 'Prague · C1', status: 'ok', yield: 99.6, units: 14008, defects: 56, trend: '+0.4' },
    { id: 'PRG-C2', name: 'Prague · C2', status: 'down', yield: 0, units: 0, defects: 0, trend: '—' },
    { id: 'OSA-D1', name: 'Osaka · D1', status: 'ok', yield: 99.8, units: 16204, defects: 32, trend: '+0.1' },
    { id: 'OSA-D2', name: 'Osaka · D2', status: 'ok', yield: 99.4, units: 15870, defects: 95, trend: '+0.2' },
  ];

  // Sparkline data — 30 days of yield
  const yieldHistory = [98.4, 98.6, 98.5, 98.8, 99.0, 99.1, 98.9, 99.2, 99.0, 98.7,
                       98.9, 99.1, 99.3, 99.2, 99.0, 98.8, 98.5, 98.2, 98.4, 98.7,
                       99.0, 99.2, 99.4, 99.3, 99.1, 99.2, 99.4, 99.5, 99.4, 99.3];

  // Defect categories by type, last 7 days
  const defectMix = [
    { cat: 'Surface scratch', count: 412, pct: 34, color: '#ea4335' },
    { cat: 'Solder bridge',   count: 287, pct: 24, color: '#f9ab00' },
    { cat: 'Mold flash',      count: 198, pct: 16, color: '#fbbc04' },
    { cat: 'Low fill',        count: 142, pct: 12, color: '#a142f4' },
    { cat: 'Crack',           count: 98,  pct: 8,  color: '#1e8e3e' },
    { cat: 'Other',           count: 73,  pct: 6,  color: '#5f6368' },
  ];

  return (
    <div className="dash-mock">
      {/* Window chrome */}
      <div className="dash-chrome">
        <div className="dash-traffic">
          <span className="dot r"></span>
          <span className="dot y"></span>
          <span className="dot g"></span>
        </div>
        <div className="dash-url">
          <Icon name="lock" size={11} />
          <span>console.viai.io / fleet</span>
        </div>
        <div className="dash-user">
          <span style={{ width: 18, height: 18, borderRadius: '50%',
            background: 'linear-gradient(135deg, #2A6FDB, #1F8A5B)',
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
            color: '#fff', fontSize: 9, fontWeight: 700,
          }}>SR</span>
        </div>
      </div>

      {/* App body */}
      <div className="dash-body">
        {/* Sidebar */}
        <aside className="dash-side">
          <div className="dash-brand">
            <span className="dash-eye"></span>
            <span>VIAI</span>
          </div>
          <nav>
            {[
              ['fleet', 'dashboard', 'Fleet'],
              ['lines', 'precision_manufacturing', 'Lines'],
              ['defects', 'error_outline', 'Defects'],
              ['models', 'psychology', 'Models'],
              ['alerts', 'notifications', 'Alerts', 3],
              ['team', 'group', 'Team'],
              ['billing', 'receipt_long', 'Billing'],
            ].map(([k, ic, lbl, badge]) => (
              <button key={k} className={'dash-nav' + (tab === k ? ' active' : '')}
                      onClick={() => setTab(k)}>
                <Icon name={ic} size={14} />
                <span>{lbl}</span>
                {badge && <span className="dash-badge">{badge}</span>}
              </button>
            ))}
          </nav>
          <div className="dash-side-footer">
            <div className="dash-org">
              <div className="dash-org-name">Northwind MFG</div>
              <div className="dash-org-tier">Scale · 8 lines</div>
            </div>
          </div>
        </aside>

        {/* Main */}
        <main className="dash-main">
          {/* Top bar */}
          <div className="dash-top">
            <div>
              <div className="dash-top-eyebrow">CONSOLE</div>
              <h3 className="dash-top-title">Fleet overview</h3>
            </div>
            <div className="dash-top-actions">
              <button className="dash-pill">
                <Icon name="schedule" size={11} />
                <span>Last 24h</span>
                <Icon name="expand_more" size={12} />
              </button>
              <button className="dash-pill">
                <Icon name="filter_alt" size={11} />
                <span>All sites</span>
              </button>
              <button className="dash-pill primary">
                <Icon name="download" size={11} />
                <span>Export</span>
              </button>
            </div>
          </div>

          {/* KPI cards */}
          <div className="dash-kpis">
            <div className="dash-kpi">
              <div className="dash-kpi-label">Units inspected · 24h</div>
              <div className="dash-kpi-value">88,544</div>
              <div className="dash-kpi-delta up">
                <Icon name="trending_up" size={11} />
                <span>+4.2% vs yesterday</span>
              </div>
              {/* mini sparkline */}
              <svg className="dash-kpi-spark" viewBox="0 0 120 28" preserveAspectRatio="none">
                <polyline fill="none" stroke="#2A6FDB" strokeWidth="1.4"
                  points={yieldHistory.slice(0, 14).map((v, i) =>
                    `${i * (120/13)},${28 - (v - 98) * 16}`).join(' ')} />
                <polyline fill="rgba(42,111,219,0.12)" stroke="none"
                  points={yieldHistory.slice(0, 14).map((v, i) =>
                    `${i * (120/13)},${28 - (v - 98) * 16}`).join(' ') + ' 120,28 0,28'} />
              </svg>
            </div>

            <div className="dash-kpi">
              <div className="dash-kpi-label">First-pass yield</div>
              <div className="dash-kpi-value">
                99.<span style={{ color: 'var(--color-on-surface-tertiary)' }}>3</span>
                <span className="dash-kpi-unit">%</span>
              </div>
              <div className="dash-kpi-delta up">
                <Icon name="trending_up" size={11} />
                <span>+0.4 pts WoW</span>
              </div>
              <svg className="dash-kpi-spark" viewBox="0 0 120 28" preserveAspectRatio="none">
                <polyline fill="none" stroke="#1F8A5B" strokeWidth="1.4"
                  points={yieldHistory.map((v, i) =>
                    `${i * (120/29)},${28 - (v - 98) * 16}`).join(' ')} />
                <polyline fill="rgba(31,138,91,0.12)" stroke="none"
                  points={yieldHistory.map((v, i) =>
                    `${i * (120/29)},${28 - (v - 98) * 16}`).join(' ') + ' 120,28 0,28'} />
              </svg>
            </div>

            <div className="dash-kpi">
              <div className="dash-kpi-label">Defects caught</div>
              <div className="dash-kpi-value">
                849
              </div>
              <div className="dash-kpi-delta down">
                <Icon name="trending_down" size={11} />
                <span>−12% vs avg</span>
              </div>
              <svg className="dash-kpi-spark" viewBox="0 0 120 28" preserveAspectRatio="none">
                {Array.from({length: 14}).map((_, i) => {
                  const h = 4 + ((i * 7 + 13) % 18);
                  return <rect key={i} x={i * (120/14)} y={28 - h}
                               width={120/14 - 2} height={h} fill="#ea4335" opacity="0.7" />;
                })}
              </svg>
            </div>

            <div className="dash-kpi accent">
              <div className="dash-kpi-label">$ scrap saved · MTD</div>
              <div className="dash-kpi-value">
                <span style={{ fontSize: 16, color: 'var(--color-on-surface-tertiary)',
                               fontWeight: 600 }}>$</span>
                284K
              </div>
              <div className="dash-kpi-delta up">
                <Icon name="trending_up" size={11} />
                <span>vs $186K last month</span>
              </div>
              <div className="dash-kpi-roi">
                <span>ROI</span>
                <strong>14.2×</strong>
                <span style={{ color: 'var(--color-on-surface-tertiary)' }}>this quarter</span>
              </div>
            </div>
          </div>

          {/* Two-col grid */}
          <div className="dash-cols">
            {/* Lines table */}
            <div className="dash-card dash-card-lines">
              <div className="dash-card-head">
                <div>
                  <div className="dash-card-title">All lines</div>
                  <div className="dash-card-sub">8 active · 1 offline · live</div>
                </div>
                <button className="dash-pill ghost">
                  <Icon name="more_horiz" size={12} />
                </button>
              </div>
              <div className="dash-table">
                <div className="dash-thead">
                  <span>Line</span>
                  <span>Yield</span>
                  <span style={{ textAlign: 'right' }}>Units · 24h</span>
                  <span style={{ textAlign: 'right' }}>Defects</span>
                  <span style={{ textAlign: 'right' }}>Δ</span>
                </div>
                {lines.map(L => (
                  <div className={'dash-row dash-row-' + L.status} key={L.id}>
                    <span className="ln">
                      <span className={'sd sd-' + L.status}></span>
                      {L.name}
                    </span>
                    <span className="yi">
                      {L.status === 'down' ? '—' : L.yield.toFixed(1) + '%'}
                      {L.status !== 'down' && (
                        <span className="ybar">
                          <span style={{ width: ((L.yield - 95) / 5 * 100) + '%' }}></span>
                        </span>
                      )}
                    </span>
                    <span className="num">{L.status === 'down' ? '—' : L.units.toLocaleString()}</span>
                    <span className="num">
                      {L.status === 'down' ? '—' : (
                        <span style={{
                          color: L.defects > 200 ? 'var(--color-warning)' : 'var(--color-on-surface-secondary)',
                          fontWeight: L.defects > 200 ? 700 : 500,
                        }}>{L.defects}</span>
                      )}
                    </span>
                    <span className="num">
                      <span style={{
                        color: L.trend.startsWith('+') ? 'var(--color-pass)' :
                               L.trend.startsWith('−') ? 'var(--color-defect)' :
                               'var(--color-on-surface-tertiary)',
                        fontWeight: 600,
                      }}>{L.trend}</span>
                    </span>
                  </div>
                ))}
              </div>
            </div>

            {/* Right column: alerts + defect mix */}
            <div className="dash-rcol">
              {/* Alerts */}
              <div className="dash-card">
                <div className="dash-card-head">
                  <div>
                    <div className="dash-card-title">
                      Active alerts
                      <span className="dash-pill-mini" style={{
                        background: 'var(--color-warning-bg)',
                        color: 'var(--color-warning)',
                      }}>3</span>
                    </div>
                  </div>
                  <button className="dash-pill ghost">View all</button>
                </div>
                <div className="dash-alerts">
                  <div className="dash-alert warn">
                    <Icon name="warning" size={14} />
                    <div>
                      <div className="t">Yield drop on CHI-B1</div>
                      <div className="m">96.4% vs 98.7% baseline · 4h ago</div>
                    </div>
                    <span className="dash-alert-time">4h</span>
                  </div>
                  <div className="dash-alert err">
                    <Icon name="link_off" size={14} />
                    <div>
                      <div className="t">Edge offline · PRG-C2</div>
                      <div className="m">Last heartbeat 2h ago · check power</div>
                    </div>
                    <span className="dash-alert-time">2h</span>
                  </div>
                  <div className="dash-alert info">
                    <Icon name="psychology" size={14} />
                    <div>
                      <div className="t">Model retrained · pcb-solder-v3 → v3.1</div>
                      <div className="m">Recall +0.6pts on solder bridge · auto-deployed</div>
                    </div>
                    <span className="dash-alert-time">12h</span>
                  </div>
                </div>
              </div>

              {/* Defect mix */}
              <div className="dash-card">
                <div className="dash-card-head">
                  <div>
                    <div className="dash-card-title">Defect mix · 7d</div>
                    <div className="dash-card-sub">1,210 total · top 6 categories</div>
                  </div>
                </div>
                <div className="dash-mix">
                  <div className="dash-mix-bar">
                    {defectMix.map(d => (
                      <span key={d.cat} title={d.cat}
                            style={{ background: d.color, width: d.pct + '%' }}></span>
                    ))}
                  </div>
                  <div className="dash-mix-list">
                    {defectMix.map(d => (
                      <div key={d.cat} className="dash-mix-row">
                        <span className="sw" style={{ background: d.color }}></span>
                        <span className="ct">{d.cat}</span>
                        <span className="ct-num">{d.count}</span>
                        <span className="ct-pct">{d.pct}%</span>
                      </div>
                    ))}
                  </div>
                </div>
              </div>
            </div>
          </div>

          {/* Bottom row — defect trend chart */}
          <div className="dash-card">
            <div className="dash-card-head">
              <div>
                <div className="dash-card-title">Yield by site · 30 days</div>
                <div className="dash-card-sub">Hover any line to drill in</div>
              </div>
              <div style={{ display: 'flex', gap: 6 }}>
                {['Bangalore', 'Chihuahua', 'Prague', 'Osaka'].map((site, i) => (
                  <span key={site} className="dash-legend"
                        style={{ '--c': ['#2A6FDB', '#ea4335', '#1F8A5B', '#a142f4'][i] }}>
                    <span className="d"></span>{site}
                  </span>
                ))}
              </div>
            </div>
            <div className="dash-chart">
              <svg viewBox="0 0 800 160" preserveAspectRatio="none"
                   style={{ width: '100%', height: 160 }}>
                {/* grid */}
                {[0, 1, 2, 3, 4].map(i => (
                  <line key={i} x1="0" y1={i * 32 + 8} x2="800" y2={i * 32 + 8}
                        stroke="var(--color-divider)" strokeWidth="0.5"
                        strokeDasharray={i === 4 ? '0' : '2 4'} />
                ))}
                {/* y labels */}
                {['100%', '99%', '98%', '97%', '96%'].map((l, i) => (
                  <text key={l} x="6" y={i * 32 + 11} fill="var(--color-on-surface-tertiary)"
                        fontFamily="monospace" fontSize="8">{l}</text>
                ))}
                {/* lines */}
                {[
                  { color: '#2A6FDB', data: [99.0, 99.1, 98.9, 99.2, 99.0, 99.1, 99.2, 99.3, 99.0, 99.2, 99.3, 99.1, 99.0, 98.9, 99.1, 99.2, 99.4, 99.3, 99.2, 99.0, 99.1, 99.2, 99.3, 99.4, 99.2, 99.1, 99.3, 99.4, 99.2, 99.0] },
                  { color: '#ea4335', data: [98.6, 98.4, 98.2, 98.5, 98.6, 98.3, 98.0, 97.8, 97.5, 97.4, 97.6, 97.8, 98.0, 97.8, 97.6, 97.4, 97.2, 97.0, 96.8, 96.6, 96.8, 97.0, 97.2, 96.8, 96.4, 96.6, 96.4, 96.2, 96.4, 96.4] },
                  { color: '#1F8A5B', data: [99.4, 99.5, 99.3, 99.4, 99.6, 99.5, 99.4, 99.6, 99.5, 99.6, 99.7, 99.6, 99.5, 99.6, 99.7, 99.6, 99.5, 99.6, 99.4, 99.5, 99.6, 99.7, 99.6, 99.5, 99.6, 99.7, 99.5, 99.6, 99.6, 99.6] },
                  { color: '#a142f4', data: [99.2, 99.3, 99.4, 99.5, 99.6, 99.5, 99.4, 99.5, 99.6, 99.7, 99.6, 99.5, 99.6, 99.7, 99.8, 99.7, 99.6, 99.5, 99.6, 99.7, 99.5, 99.6, 99.7, 99.6, 99.4, 99.5, 99.6, 99.5, 99.4, 99.4] },
                ].map(L => (
                  <polyline key={L.color} fill="none" stroke={L.color} strokeWidth="1.5"
                    points={L.data.map((v, i) =>
                      `${i * (800/29)},${136 - (v - 96) * 32}`).join(' ')} />
                ))}
                {/* current value markers */}
                {[
                  { color: '#2A6FDB', y: 99.0 },
                  { color: '#ea4335', y: 96.4 },
                  { color: '#1F8A5B', y: 99.6 },
                  { color: '#a142f4', y: 99.4 },
                ].map((p, i) => (
                  <circle key={i} cx="800" cy={136 - (p.y - 96) * 32}
                          r="2.5" fill={p.color} />
                ))}
              </svg>
            </div>
          </div>
        </main>
      </div>
    </div>
  );
}

function CloudSection({ setRoute }) {
  const benefits = [
    {
      icon: 'dashboard',
      title: 'One pane of glass',
      desc: 'Every line, every site, one screen. Yield, defects, throughput — live and side by side.',
    },
    {
      icon: 'notifications_active',
      title: 'Alerts that find you',
      desc: 'Yield drift, model regressions, offline edges. Slack, email, PagerDuty — pick your channel.',
    },
    {
      icon: 'auto_graph',
      title: 'Drift detection',
      desc: 'We watch the model watching your line. Confidence drops trigger an audit before throughput does.',
    },
    {
      icon: 'group',
      title: 'Role-based access',
      desc: 'QA leads see their line. Plant managers see the plant. The COO sees everything. SSO + SCIM included.',
    },
    {
      icon: 'history',
      title: 'Audit trail · 365 days',
      desc: 'Every verdict, every image, every model version — replayable. ISO 9001 / IATF 16949 ready.',
    },
    {
      icon: 'cloud_off',
      title: 'Optional, never required',
      desc: 'Inference runs on the edge. The cloud is for visibility, not operation. Pull the plug — the line keeps going.',
    },
  ];

  return (
    <section className="section cloud-section">
      <div className="container">
        <div style={{ display: 'flex', alignItems: 'baseline',
                      justifyContent: 'space-between', flexWrap: 'wrap', gap: 16 }}>
          <div style={{ maxWidth: 720 }}>
            <Eyebrow color="var(--color-primary)">For managers</Eyebrow>
            <h2 className="section-title">A console that turns inspection into decisions.</h2>
            <p className="section-sub">
              The edge catches defects in 42ms. The cloud tells you which line, which shift,
              which die — and what's about to drift before it costs you scrap. Built for QA
              leads, plant managers, and the people they report to.
            </p>
          </div>
          <button className="btn btn-outline btn-lg" onClick={() => setRoute('product')}>
            <Icon name="open_in_new" size={16} />
            Tour the console
          </button>
        </div>

        <div className="dash-shell">
          <CloudDashboardMock />
        </div>

        <div className="cloud-benefits">
          {benefits.map(b => (
            <div key={b.title} className="cloud-benefit">
              <div className="cloud-benefit-ic">
                <Icon name={b.icon} size={18} />
              </div>
              <div className="cloud-benefit-title">{b.title}</div>
              <div className="cloud-benefit-desc">{b.desc}</div>
            </div>
          ))}
        </div>

        <div className="cloud-roi-band">
          <div className="cloud-roi-stat">
            <div className="v">3.4<span>×</span></div>
            <div className="l">faster root-cause vs spreadsheets</div>
          </div>
          <div className="cloud-roi-stat">
            <div className="v">$186K<span>/mo</span></div>
            <div className="l">avg scrap reduction · per plant</div>
          </div>
          <div className="cloud-roi-stat">
            <div className="v">14<span>min</span></div>
            <div className="l">avg time to detect a yield drift</div>
          </div>
          <div className="cloud-roi-stat">
            <div className="v">100<span>%</span></div>
            <div className="l">audit coverage on every shipped unit</div>
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { CloudSection, CloudDashboardMock });
