// Screens 1 + 2 — Overview + Role selection. The shell provides header/tabs.

function Screen1_Landing({ onNext, activeTab }) {
  const [tick, setTick] = React.useState(0);
  React.useEffect(() => {
    const id = setInterval(() => setTick(t => t + 1), 1600);
    return () => clearInterval(id);
  }, []);

  if (activeTab === 'topology') return <Overview_Topology tick={tick} />;
  if (activeTab === 'pipeline') return <Overview_Pipeline />;
  return <Overview_Summary tick={tick} onNext={onNext} />;
}

function Overview_Summary({ tick, onNext }) {
  const leftNodes = ['MS-0417','MS-2203','MS-0991','MS-1140','MS-0488','MS-3312'];
  const rightNodes = ['BU-2208','BU-0117','BU-4409','BU-1002','BU-3390','BU-0055'];
  const activeMatches = React.useMemo(() => {
    const pairs = [];
    for (let i = 0; i < 3; i++) {
      pairs.push([(tick*3+i*7+i) % leftNodes.length, (tick*5+i*3+2) % rightNodes.length, i]);
    }
    return pairs;
  }, [tick]);

  const kpis = [
    ['Participants (twin)', '12,478', '+342 today',  'ok'],
    ['Active matches',       '1,204',  '+14 last hr', 'info'],
    ['Pending reveals',      '86',      'bilateral',  'accent'],
    ['Deals assembled',      '312',    'this quarter','ok'],
    ['Avg. time-to-match',   '4.2h',   '−12% MoM',    'ok'],
    ['Rejection floor',      '41/100', 'policy.v2',   'ghost'],
  ];

  return (
    <div className="mf-screen-inner">
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(6, 1fr)', gap: 0, border: '1px solid var(--line)', marginBottom: 22 }}>
        {kpis.map((k, i) => (
          <div key={k[0]} style={{
            padding: '12px 14px',
            borderRight: i < 5 ? '1px solid var(--line)' : 'none',
            background: 'var(--paper)',
          }}>
            <div className="mono-lbl">{k[0]}</div>
            <div className="mono" style={{ fontSize: 20, fontWeight: 500, marginTop: 4 }}>{k[1]}</div>
            <span className={`chip ${k[3]}`} style={{ fontSize: 9, marginTop: 6 }}>{k[2]}</span>
          </div>
        ))}
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1.3fr 1fr', gap: 20 }}>
        <div style={{ background: 'var(--paper)', border: '1px solid var(--line)', padding: 18 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 12 }}>
            <span className="mono-lbl">Matching pulse · last 60 seconds</span>
            <span className="mono-lbl" style={{ color: 'var(--accent)' }}>● live · frame {String(tick).padStart(4,'0')}</span>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1.2fr 1fr', gap: 0, minHeight: 300 }}>
            <div>
              <div className="mono-lbl" style={{ marginBottom: 8 }}>SUPPLY · {leftNodes.length * 208}</div>
              {leftNodes.map((n,i) => {
                const hot = activeMatches.some(([l]) => l === i);
                return (
                  <div key={n} style={{
                    padding: '6px 10px', marginBottom: 6,
                    background: hot ? 'var(--accent-soft)' : 'var(--paper-2)',
                    border: `1px solid ${hot ? 'var(--accent)' : 'var(--line)'}`,
                    fontFamily: 'var(--mono)', fontSize: 11,
                    color: hot ? 'var(--accent-ink)' : 'var(--ink-2)',
                    transition: 'all 400ms ease',
                    display: 'flex', justifyContent: 'space-between',
                  }}>
                    <span>{n}</span>{hot && <span>●</span>}
                  </div>
                );
              })}
            </div>
            <div style={{ position: 'relative' }}>
              <svg width="100%" height="100%" style={{ position: 'absolute', inset: 0 }}>
                {activeMatches.map(([l, r, i]) => {
                  const y1 = 28 + l * 34;
                  const y2 = 28 + r * 34;
                  return (
                    <g key={`${tick}-${i}`}>
                      <line x1="0" y1={y1} x2="100%" y2={y2}
                        stroke="var(--accent)" strokeWidth="1.2" strokeDasharray="4 3"
                        style={{ opacity: 0.85 }} />
                      <circle cx="50%" cy={(y1+y2)/2} r="3" fill="var(--accent)">
                        <animate attributeName="r" values="2;5;2" dur="1.2s" repeatCount="indefinite" />
                      </circle>
                    </g>
                  );
                })}
              </svg>
            </div>
            <div>
              <div className="mono-lbl" style={{ marginBottom: 8, textAlign: 'right' }}>DEMAND · {rightNodes.length * 146}</div>
              {rightNodes.map((n,i) => {
                const hot = activeMatches.some(([_, r]) => r === i);
                return (
                  <div key={n} style={{
                    padding: '6px 10px', marginBottom: 6,
                    background: hot ? 'var(--accent-soft)' : 'var(--paper-2)',
                    border: `1px solid ${hot ? 'var(--accent)' : 'var(--line)'}`,
                    fontFamily: 'var(--mono)', fontSize: 11,
                    color: hot ? 'var(--accent-ink)' : 'var(--ink-2)',
                    display: 'flex', justifyContent: 'space-between',
                  }}>
                    {hot && <span>●</span>}<span style={{ marginLeft: 'auto' }}>{n}</span>
                  </div>
                );
              })}
            </div>
          </div>
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          <div style={{ background: 'var(--ink)', color: 'var(--paper)', padding: 18 }}>
            <div className="mono-lbl" style={{ color: 'rgba(247,245,239,0.5)' }}>CONTINUE</div>
            <div style={{ fontFamily: 'var(--serif)', fontSize: 18, margin: '6px 0 10px', lineHeight: 1.3 }}>
              You have 1 new mutual match with confidence 83/100.
            </div>
            <p style={{ fontSize: 12, color: 'rgba(247,245,239,0.7)', lineHeight: 1.6, marginTop: 0 }}>
              Identity remains confidential until both sides opt in.
            </p>
            <button className="mf-btn accent" style={{ width: '100%' }} onClick={onNext}>
              Step into your role →
            </button>
          </div>
          <div style={{ background: 'var(--paper)', border: '1px solid var(--line)', padding: 14 }}>
            <div className="mono-lbl" style={{ marginBottom: 10 }}>Pipeline stack</div>
            {[
              ['ClientSynth',   'v3.2', 'synthesises twin participants from market priors'],
              ['KnowledgeSlot', 'v2.1', 'grounds domain ontology · closes data gaps'],
              ['Cosolvent',     'v7.4', 'runs bidirectional evaluation & scoring'],
              ['MarketForge',   '—',    'orchestrates, gates identity, assembles deals'],
            ].map(([t, v, sub]) => (
              <div key={t} style={{ padding: '8px 0', borderBottom: '1px dashed var(--line)', display: 'grid', gridTemplateColumns: '110px 50px 1fr', gap: 10 }}>
                <div style={{ fontWeight: 500, fontSize: 12 }}>{t}</div>
                <div className="mono" style={{ fontSize: 10, color: 'var(--ink-3)' }}>{v}</div>
                <div style={{ fontSize: 11.5, color: 'var(--ink-2)' }}>{sub}</div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

function Overview_Topology({ tick }) {
  const segments = [
    ['Aerospace · tier-1/2',      480, 312,  84],
    ['Defense · ITAR required',   210, 188,  71],
    ['Medical device',             184, 162,  62],
    ['Energy · oil & gas',         118,  94,  54],
    ['Industrial · precision',     256, 240,  61],
  ];
  return (
    <div className="mf-screen-inner">
      <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 20 }}>
        <div>
          <div className="mono-lbl" style={{ marginBottom: 10 }}>Market segments · supply vs demand density</div>
          <div style={{ background: 'var(--paper)', border: '1px solid var(--line)' }}>
            {segments.map(([n, supply, demand, fill], i) => (
              <div key={n} style={{ padding: '14px 18px', borderTop: i > 0 ? '1px solid var(--line)' : 'none' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6, fontSize: 12 }}>
                  <span style={{ fontWeight: 500 }}>{n}</span>
                  <span className="mono" style={{ fontSize: 10, color: 'var(--ink-3)' }}>{supply}S · {demand}D · fill {fill}%</span>
                </div>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 2px 1fr', gap: 0 }}>
                  <div style={{ height: 10, background: 'var(--paper-3)', position: 'relative' }}>
                    <div style={{ position: 'absolute', right: 0, top: 0, height: '100%', width: `${supply / 5}%`, background: 'var(--info)' }} />
                  </div>
                  <div style={{ background: 'var(--ink-4)' }} />
                  <div style={{ height: 10, background: 'var(--paper-3)', position: 'relative' }}>
                    <div style={{ position: 'absolute', left: 0, top: 0, height: '100%', width: `${demand / 5}%`, background: 'var(--accent)' }} />
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
        <div style={{ background: 'var(--paper)', border: '1px solid var(--line)', padding: 16 }}>
          <div className="mono-lbl" style={{ marginBottom: 10 }}>Geographic distribution · US regions</div>
          {[
            ['Northeast',  41, 36],
            ['Midwest',    52, 58],
            ['South',      38, 44],
            ['West',       30, 37],
            ['Mountain',   12, 15],
          ].map(([r, s, d]) => (
            <div key={r} style={{ padding: '8px 0', borderBottom: '1px dashed var(--line)' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12 }}>
                <span>{r}</span>
                <span className="mono" style={{ fontSize: 10, color: 'var(--ink-3)' }}>{s}% supply · {d}% demand</span>
              </div>
            </div>
          ))}
          <div className="mono-lbl" style={{ marginTop: 16, color: 'var(--accent)' }}>
            ◆ Midwest over-supplied vs demand · surfacing adjacent-market opportunities
          </div>
        </div>
      </div>
    </div>
  );
}

function Overview_Pipeline() {
  return (
    <div className="mf-screen-inner">
      <div className="mono-lbl" style={{ marginBottom: 10 }}>Recent matches across all participants</div>
      <DashboardExtras_Candidates />
    </div>
  );
}

// --- Screen 2 — role selection --------------------------------

function Screen2_Role({ role, onSelect, onNext }) {
  const roles = [
    { key: 'shop',      label: 'Machine Shop', sub: 'Supply side',
      blurb: 'You hold capacity, tooling and certifications. You want buyer programs that load your cell without disclosing your book.',
      stats: [['Population','1,248'],['Avg. capacity','41%'],['Active matches','312']] },
    { key: 'buyer',     label: 'Buyer',        sub: 'Demand side',
      blurb: 'You have parts to make. You need qualified suppliers who clear AS9100, ITAR, tolerance and delivery — without spending three weeks on RFQs.',
      stats: [['Population','867'],['Open RFQs','2,140'],['Avg. time-to-match','4.2 h']] },
    { key: 'inspector', label: 'Inspector',    sub: 'Verification side',
      blurb: 'You operate an accredited lab. You want to be surfaced on matches where your scope clears the 10:1 rule and your turnaround fits.',
      stats: [['Population','312'],['Active FAIs','89'],['Accredited','100%']] },
  ];

  return (
    <div className="mf-screen-inner">
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 20 }}>
        {roles.map(r => {
          const active = role === r.key;
          return (
            <button key={r.key} onClick={() => onSelect(r.key)}
              style={{
                textAlign: 'left',
                background: active ? 'var(--ink)' : 'var(--paper)',
                color: active ? 'var(--paper)' : 'var(--ink)',
                border: `1px solid ${active ? 'var(--ink)' : 'var(--line-2)'}`,
                padding: '22px 22px', cursor: 'pointer',
                minHeight: 260, display: 'flex', flexDirection: 'column', gap: 14,
                fontFamily: 'inherit',
              }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
                <div>
                  <div className="mono-lbl" style={{ color: active ? 'rgba(247,245,239,0.6)' : 'var(--ink-3)' }}>{r.sub}</div>
                  <div style={{ fontSize: 22, fontFamily: 'var(--serif)', marginTop: 4 }}>{r.label}</div>
                </div>
                <div style={{ width: 18, height: 18, border: `1px solid ${active ? 'var(--paper)' : 'var(--ink-4)'}`, borderRadius: '50%', display:'flex', alignItems:'center', justifyContent:'center' }}>
                  {active && <div style={{ width: 8, height: 8, background: 'var(--accent)', borderRadius: '50%' }} />}
                </div>
              </div>
              <p style={{ fontSize: 13, lineHeight: 1.55, margin: 0, flex: 1, color: active ? 'rgba(247,245,239,0.82)' : 'var(--ink-2)' }}>
                {r.blurb}
              </p>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', borderTop: `1px solid ${active ? 'rgba(247,245,239,0.18)' : 'var(--line)'}`, paddingTop: 10 }}>
                {r.stats.map(([k,v], i) => (
                  <div key={k} style={{ borderRight: i < 2 ? `1px solid ${active ? 'rgba(247,245,239,0.12)' : 'var(--line)'}` : 'none', paddingRight: 8 }}>
                    <div className="mono" style={{ fontSize: 13, fontWeight: 500 }}>{v}</div>
                    <div className="mono-lbl" style={{ color: active ? 'rgba(247,245,239,0.55)' : 'var(--ink-3)', fontSize: 9, marginTop: 2 }}>{k}</div>
                  </div>
                ))}
              </div>
            </button>
          );
        })}
      </div>
      <div style={{ marginTop: 24, display: 'flex', alignItems: 'center', gap: 14 }}>
        <span className="mono-lbl">Selected role persists across the flow. Switch anytime via the sidebar.</span>
        <span style={{ flex: 1 }} />
        <button className="mf-btn primary" onClick={onNext} disabled={!role}>Continue to profile →</button>
      </div>
    </div>
  );
}

Object.assign(window, { Screen1_Landing, Screen2_Role });
