/* global React, Icon, Btn */
/* ──────────────────────────────────────────────────────────────
   tech-demos.jsx — interactive "See demo" modal, one per solution
   ────────────────────────────────────────────────────────────── */
const { useState: useStateD, useEffect: useEffectD, useRef: useRefD } = React;

const DEMO_META = {
  modernize: { title: 'Legacy code translation', sub: 'Watch AI convert COBOL to production Java.' },
  qa:        { title: 'Self-healing test suite', sub: 'Run the suite and watch broken selectors repair themselves.' },
  mobile:    { title: 'Cross-platform code gen', sub: 'One definition compiles to Swift and Kotlin at once.' },
  ux:        { title: 'Wireframe to frontend', sub: 'Turn a sketch into accessible, shipped UI.' },
};

// ── Shared bits ──────────────────────────────────────────────────
const CodeLine = ({ children, color, delay = 0, animate }) => (
  <div className="mono" style={{ fontSize: 12.5, lineHeight: 1.95, whiteSpace: 'pre', color: color || 'inherit',
    animation: animate ? `tk-rise .35s var(--ease-out) both` : 'none', animationDelay: `${delay}s` }}>{children}</div>
);
const Pane = ({ dark, label, dotColor, children, style }) => (
  <div style={{ background: dark ? 'var(--bg-inverse)' : 'var(--bg-surface)', border: `1px solid ${dark ? 'rgba(255,255,255,0.08)' : 'var(--border-default)'}`,
    borderRadius: 'var(--radius-md)', overflow: 'hidden', display: 'flex', flexDirection: 'column', minHeight: 0, ...style }}>
    <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '10px 14px', borderBottom: `1px solid ${dark ? 'rgba(255,255,255,0.08)' : 'var(--border-subtle)'}` }}>
      <span style={{ width: 8, height: 8, borderRadius: 8, background: dotColor || '#3a4a63' }}/>
      <span className="mono" style={{ fontSize: 11, color: dark ? '#7e8ba3' : 'var(--fg-3)' }}>{label}</span>
    </div>
    <div className="code-scroll" style={{ padding: '12px 16px', overflow: 'auto', flex: 1 }}>{children}</div>
  </div>
);

// ── 1 · Modernize demo ───────────────────────────────────────────
const ModernizeDemo = () => {
  const cobol = ['IDENTIFICATION DIVISION.', 'PROGRAM-ID. LEDGER.', 'PROCEDURE DIVISION.', '  PERFORM CALC-INTEREST', '    UNTIL WS-DONE = "Y".', '  COMPUTE WS-BAL =', '    WS-BAL * WS-RATE.', '  MOVE WS-BAL TO OUT-REC.'];
  const java = ['@Service', 'class LedgerService {', '  BigDecimal accrue(Account a) {', '    var bal = a.balance();', '    while (!a.settled())', '      bal = bal.multiply(rate);', '    return bal;', '  }', '}'];
  const [phase, setPhase] = useStateD('idle'); // idle|running|done
  const [shown, setShown] = useStateD(0);
  const [pct, setPct] = useStateD(0);
  const timers = useRefD([]);
  const clearAll = () => { timers.current.forEach(clearTimeout); timers.current = []; };
  useEffectD(() => clearAll, []);
  const run = () => {
    clearAll(); setPhase('running'); setShown(0); setPct(0);
    let p = 0;
    const iv = setInterval(() => { p += 4; setPct(Math.min(100, p)); if (p >= 100) clearInterval(iv); }, 60);
    timers.current.push(iv);
    java.forEach((_, i) => timers.current.push(setTimeout(() => setShown(i + 1), 500 + i * 200)));
    timers.current.push(setTimeout(() => setPhase('done'), 600 + java.length * 200));
  };
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16, height: '100%' }}>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, flex: 1, minHeight: 0 }}>
        <Pane dark label="ledger.cob · COBOL" dotColor="#64748b">
          {cobol.map((l, i) => <CodeLine key={i} color="#94a3b8">{l}</CodeLine>)}
        </Pane>
        <Pane label="LedgerService.java · generated" dotColor={phase === 'done' ? 'var(--success)' : 'var(--primary-500)'} style={{ position: 'relative' }}>
          {phase === 'running' && <div style={{ position: 'absolute', left: 0, right: 0, top: 0, height: 28, background: 'linear-gradient(180deg, rgba(51,181,245,0.16), transparent)', animation: 'tk-scan 1.6s linear infinite', zIndex: 1 }}/>}
          {phase === 'idle' && <div style={{ color: 'var(--fg-4)', fontSize: 13, display: 'flex', alignItems: 'center', gap: 8, height: '100%' }}><Icon name="spark" size={16}/> Output appears here.</div>}
          {java.slice(0, shown).map((l, i) => <CodeLine key={i} animate delay={0} color={i === 0 ? 'var(--accent)' : 'var(--fg-2)'}>{l}</CodeLine>)}
        </Pane>
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
        <Btn icon={phase === 'running' ? undefined : 'bolt'} onClick={run} disabled={phase === 'running'}
          style={phase === 'running' ? { opacity: 0.7, cursor: 'default' } : null}>
          {phase === 'running' ? 'Translating…' : phase === 'done' ? 'Translate again' : 'Translate with AI'}
        </Btn>
        <div style={{ flex: 1, height: 6, background: 'var(--neutral-100)', borderRadius: 9999, overflow: 'hidden' }}>
          <div style={{ height: '100%', width: `${pct}%`, background: 'var(--accent)', borderRadius: 9999, transition: 'width .1s linear' }}/>
        </div>
        {phase === 'done'
          ? <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 12.5, fontWeight: 600, color: '#4ade80' }}><Icon name="check" size={15}/> 98.6% accuracy</span>
          : <span className="mono" style={{ fontSize: 12, color: 'var(--fg-4)', minWidth: 40, textAlign: 'right' }}>{pct}%</span>}
      </div>
    </div>
  );
};

// ── 2 · QA demo ──────────────────────────────────────────────────
const QADemo = () => {
  const base = [
    { n: 'checkout.spec.ts', heal: false }, { n: 'auth-flow.spec.ts', heal: true },
    { n: 'cart-merge.spec.ts', heal: false }, { n: 'search-rank.spec.ts', heal: false }, { n: 'profile.spec.ts', heal: false },
  ];
  const [st, setSt] = useStateD(base.map(() => 'idle')); // idle|running|fail|healing|pass
  const [running, setRunning] = useStateD(false);
  const timers = useRefD([]);
  const clearAll = () => { timers.current.forEach(clearTimeout); timers.current = []; };
  useEffectD(() => clearAll, []);
  const run = () => {
    clearAll(); setRunning(true);
    let next = base.map(() => 'idle'); setSt([...next]);
    let t = 0;
    base.forEach((test, i) => {
      t += 480;
      timers.current.push(setTimeout(() => setSt((s) => s.map((v, j) => j === i ? 'running' : v)), t));
      if (test.heal) {
        t += 520; timers.current.push(setTimeout(() => setSt((s) => s.map((v, j) => j === i ? 'fail' : v)), t));
        t += 520; timers.current.push(setTimeout(() => setSt((s) => s.map((v, j) => j === i ? 'healing' : v)), t));
        t += 720; timers.current.push(setTimeout(() => setSt((s) => s.map((v, j) => j === i ? 'pass' : v)), t));
      } else {
        t += 460; timers.current.push(setTimeout(() => setSt((s) => s.map((v, j) => j === i ? 'pass' : v)), t));
      }
    });
    timers.current.push(setTimeout(() => setRunning(false), t + 200));
  };
  const cfg = {
    idle:    { bg: 'var(--neutral-50)', fg: 'var(--fg-4)', ic: 'clock', label: 'queued' },
    running: { bg: 'var(--info-bg)', fg: 'var(--primary-700)', ic: 'refresh', label: 'running', spin: true },
    fail:    { bg: 'var(--error-bg)', fg: '#991B1B', ic: 'x', label: 'selector broken' },
    healing: { bg: 'var(--warning-bg)', fg: '#fbbf24', ic: 'refresh', label: 'AI healing selector', spin: true },
    pass:    { bg: 'var(--success-bg)', fg: '#4ade80', ic: 'check', label: 'passed' },
  };
  const passed = st.filter((s) => s === 'pass').length;
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16, height: '100%' }}>
      <div style={{ display: 'grid', gap: 8, flex: 1, alignContent: 'start' }}>
        {base.map((test, i) => {
          const c = cfg[st[i]];
          return (
            <div key={test.n} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 14px', borderRadius: 'var(--radius-md)',
              border: '1px solid var(--border-subtle)', background: 'var(--bg-surface)', transition: 'all var(--duration-base)' }}>
              <span style={{ width: 26, height: 26, borderRadius: 8, display: 'grid', placeItems: 'center', background: c.bg, color: c.fg }}>
                <Icon name={c.ic} size={15} style={c.spin ? { animation: 'tk-spin 1s linear infinite' } : null}/>
              </span>
              <span className="mono" style={{ fontSize: 13, color: 'var(--fg-1)' }}>{test.n}</span>
              <span style={{ marginLeft: 'auto', fontSize: 12, fontWeight: 600, color: c.fg }}>{c.label}</span>
            </div>
          );
        })}
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
        <Btn icon={running ? undefined : 'play'} onClick={run} disabled={running} style={running ? { opacity: 0.7, cursor: 'default' } : null}>
          {running ? 'Running suite…' : 'Run test suite'}
        </Btn>
        <div style={{ marginLeft: 'auto', display: 'flex', gap: 18, fontSize: 13 }}>
          <span style={{ color: 'var(--fg-2)' }}><b style={{ color: '#4ade80' }}>{passed}</b> / {base.length} passed</span>
          <span style={{ color: 'var(--fg-2)' }}><b style={{ color: 'var(--accent)' }}>1</b> auto-healed</span>
          <span style={{ color: 'var(--fg-2)' }}><b style={{ color: 'var(--fg-1)' }}>0</b> flaky</span>
        </div>
      </div>
    </div>
  );
};

// ── 3 · Mobile demo ──────────────────────────────────────────────
const MobileDemo = () => {
  const code = {
    Swift: ['struct ProfileView: View {', '  @State var user: User', '  var body: some View {', '    VStack(spacing: 12) {', '      Avatar(user.photo)', '      Text(user.name)', '        .font(.headline)', '      Button("Follow") {', '        store.follow(user)', '      }', '    }', '  }', '}'],
    Kotlin: ['@Composable', 'fun ProfileView(user: User) {', '  Column(', '    verticalArrangement =', '      Arrangement.spacedBy(12.dp)', '  ) {', '    Avatar(user.photo)', '    Text(user.name,', '      style = h6)', '    Button(onClick = {', '      store.follow(user)', '    }) { Text("Follow") }', '  }', '}'],
  };
  const [lang, setLang] = useStateD('Swift');
  const [gen, setGen] = useStateD(false);
  const [shown, setShown] = useStateD(0);
  const timers = useRefD([]);
  const clearAll = () => { timers.current.forEach(clearTimeout); timers.current = []; };
  useEffectD(() => clearAll, []);
  const reveal = (l) => {
    clearAll(); setShown(0);
    code[l].forEach((_, i) => timers.current.push(setTimeout(() => setShown(i + 1), 80 + i * 70)));
  };
  const generate = () => { setGen(true); reveal(lang); };
  const switchLang = (l) => { setLang(l); if (gen) reveal(l); };
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16, height: '100%' }}>
      <div style={{ background: 'var(--neutral-50)', border: '1px solid var(--border-default)', borderRadius: 'var(--radius-md)', padding: '12px 14px' }}>
        <span className="overline" style={{ color: 'var(--fg-4)' }}>Spec</span>
        <div style={{ fontSize: 14, color: 'var(--fg-1)', marginTop: 4 }}>“A profile screen with an avatar, the user's name, and a follow button.”</div>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 200px', gap: 14, flex: 1, minHeight: 0 }}>
        <Pane dark label={`${lang === 'Swift' ? 'ProfileView.swift' : 'ProfileView.kt'} · generated`} dotColor={gen ? 'var(--success)' : '#64748b'}
          style={{ position: 'relative' }}>
          <div style={{ display: 'flex', gap: 4, position: 'absolute', top: 8, right: 12, zIndex: 2 }}>
            {['Swift', 'Kotlin'].map((l) => (
              <button key={l} onClick={() => switchLang(l)} className="mono" style={{ fontSize: 11, fontWeight: 600, padding: '4px 10px', borderRadius: 7, cursor: 'pointer',
                border: '1px solid ' + (lang === l ? 'var(--primary-500)' : 'rgba(255,255,255,0.12)'),
                background: lang === l ? 'rgba(51,181,245,0.18)' : 'transparent', color: lang === l ? 'var(--primary-300)' : '#7e8ba3' }}>{l}</button>
            ))}
          </div>
          {!gen && <div style={{ color: 'var(--fg-4)', fontSize: 13, display: 'flex', alignItems: 'center', gap: 8, height: '100%' }}><Icon name="spark" size={16}/> Generate to see code.</div>}
          {gen && code[lang].slice(0, shown).map((l, i) => <CodeLine key={i} animate color={i === 0 ? 'var(--primary-300)' : '#cbd5e1'}>{l}</CodeLine>)}
        </Pane>
        {/* phone preview */}
        <div style={{ display: 'grid', placeItems: 'center' }}>
          <div style={{ width: 150, height: 300, borderRadius: 26, border: '3px solid var(--border-strong)', background: 'var(--bg-raised)', padding: 12, position: 'relative', boxShadow: 'var(--shadow-lg)' }}>
            <div style={{ height: 6, width: 40, borderRadius: 9, background: 'var(--neutral-300)', margin: '0 auto 16px' }}/>
            {gen ? (
              <div style={{ display: 'grid', justifyItems: 'center', gap: 10, animation: 'tk-rise .5s var(--ease-out) both' }}>
                <div style={{ width: 58, height: 58, borderRadius: 9999, background: 'linear-gradient(135deg,var(--primary-300),var(--accent))' }}/>
                <div style={{ height: 12, width: 84, borderRadius: 5, background: 'var(--fg-2)' }}/>
                <div style={{ height: 8, width: 56, borderRadius: 5, background: 'var(--neutral-200)' }}/>
                <div style={{ marginTop: 8, height: 30, width: 110, borderRadius: 9, background: 'var(--accent)', color: '#fff', display: 'grid', placeItems: 'center', fontSize: 12, fontWeight: 600 }}>Follow</div>
              </div>
            ) : <div style={{ color: 'var(--fg-4)', fontSize: 11, textAlign: 'center', marginTop: 80 }}>preview</div>}
            <span className="mono" style={{ position: 'absolute', bottom: 8, left: 0, right: 0, textAlign: 'center', fontSize: 9, color: 'var(--fg-4)' }}>{lang === 'Swift' ? 'iOS' : 'Android'}</span>
          </div>
        </div>
      </div>
      <div><Btn icon="bolt" onClick={generate}>{gen ? 'Regenerate' : 'Generate apps'}</Btn></div>
    </div>
  );
};

// ── 4 · UX demo ──────────────────────────────────────────────────
const UXDemo = () => {
  const [gen, setGen] = useStateD(false);
  const checks = ['Color contrast 4.8:1 — AA', 'All controls keyboard-reachable', 'Labels bound to inputs', 'Focus order is logical'];
  const [ticked, setTicked] = useStateD(0);
  const timers = useRefD([]);
  const clearAll = () => { timers.current.forEach(clearTimeout); timers.current = []; };
  useEffectD(() => clearAll, []);
  const generate = () => {
    clearAll(); setGen(true); setTicked(0);
    checks.forEach((_, i) => timers.current.push(setTimeout(() => setTicked(i + 1), 600 + i * 350)));
  };
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16, height: '100%' }}>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, flex: 1, minHeight: 0 }}>
        {/* wireframe */}
        <Pane label="signup.wireframe" dotColor="var(--neutral-400)">
          <div style={{ border: '1.5px dashed var(--border-strong)', borderRadius: 10, padding: 16, display: 'grid', gap: 12, background: 'var(--neutral-50)', height: '100%' }}>
            <div style={{ height: 18, background: 'var(--neutral-200)', borderRadius: 4, width: '60%' }}/>
            <div style={{ height: 36, background: 'var(--neutral-200)', borderRadius: 6 }}/>
            <div style={{ height: 36, background: 'var(--neutral-200)', borderRadius: 6 }}/>
            <div style={{ height: 10, background: 'var(--neutral-200)', borderRadius: 4, width: '80%' }}/>
            <div style={{ height: 38, background: 'var(--neutral-300)', borderRadius: 6, width: '55%' }}/>
          </div>
        </Pane>
        {/* rendered */}
        <Pane label="Signup.tsx · rendered" dotColor={gen ? 'var(--success)' : 'var(--primary-500)'} style={{ position: 'relative' }}>
          {gen ? (
            <div style={{ padding: 4, display: 'grid', gap: 12, animation: 'tk-rise .5s var(--ease-out) both' }}>
              <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 18, color: 'var(--brand-ink)' }}>Create your account</div>
              <input placeholder="Work email" style={{ height: 38, borderRadius: 8, border: '1px solid var(--border-default)', padding: '0 12px', fontSize: 13, fontFamily: 'var(--font-sans)' }}/>
              <input placeholder="Password" type="password" style={{ height: 38, borderRadius: 8, border: '1px solid var(--border-default)', padding: '0 12px', fontSize: 13, fontFamily: 'var(--font-sans)' }}/>
              <div style={{ fontSize: 11.5, color: 'var(--fg-3)' }}>By continuing you agree to the terms.</div>
              <button className="tbtn tbtn-primary tbtn-md" style={{ width: 'fit-content' }}>Get started</button>
            </div>
          ) : <div style={{ color: 'var(--fg-4)', fontSize: 13, display: 'flex', alignItems: 'center', gap: 8, height: '100%' }}><Icon name="spark" size={16}/> Generate to render UI.</div>}
        </Pane>
      </div>
      {/* a11y checklist */}
      <div style={{ background: 'var(--neutral-50)', border: '1px solid var(--border-default)', borderRadius: 'var(--radius-md)', padding: '12px 14px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '6px 18px' }}>
        {checks.map((c, i) => (
          <div key={c} style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12.5, color: i < ticked ? 'var(--fg-1)' : 'var(--fg-4)', transition: 'color var(--duration-base)' }}>
            <span style={{ width: 18, height: 18, borderRadius: 6, display: 'grid', placeItems: 'center', background: i < ticked ? 'var(--success-bg)' : 'var(--neutral-200)', color: '#4ade80' }}>
              {i < ticked && <Icon name="check" size={12}/>}
            </span>{c}
          </div>
        ))}
      </div>
      <div><Btn icon="bolt" onClick={generate}>{gen ? 'Regenerate UI' : 'Generate UI'}</Btn></div>
    </div>
  );
};

const DEMOS = { modernize: ModernizeDemo, qa: QADemo, mobile: MobileDemo, ux: UXDemo };

// ── Modal shell ──────────────────────────────────────────────────
const DemoModal = ({ solId, onClose }) => {
  useEffectD(() => {
    if (!solId) return undefined;
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', onKey);
    document.body.style.overflow = 'hidden';
    return () => { document.removeEventListener('keydown', onKey); document.body.style.overflow = ''; };
  }, [solId]);
  if (!solId) return null;
  const meta = DEMO_META[solId];
  const Demo = DEMOS[solId];
  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, zIndex: 100, background: 'rgba(15,23,42,0.40)',
      backdropFilter: 'blur(2px)', WebkitBackdropFilter: 'blur(2px)', display: 'grid', placeItems: 'center', padding: 'clamp(12px, 4vw, 40px)', animation: 'tk-rise .2s var(--ease-out)' }}>
      <div onClick={(e) => e.stopPropagation()} style={{ width: 'min(880px, 100%)', maxHeight: '88vh', background: 'var(--bg-raised)',
        borderRadius: 'var(--radius-lg)', boxShadow: 'var(--shadow-xl)', display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
        <div style={{ display: 'flex', alignItems: 'flex-start', gap: 16, padding: '20px 24px', borderBottom: '1px solid var(--border-subtle)' }}>
          <div style={{ width: 40, height: 40, borderRadius: 11, background: 'var(--primary-50)', border: '1px solid var(--primary-100)', color: 'var(--accent)', display: 'grid', placeItems: 'center', flexShrink: 0 }}>
            <Icon name="play" size={18}/>
          </div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div className="overline" style={{ color: 'var(--accent)' }}>Live demo</div>
            <h3 style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 21, color: 'var(--fg-1)', margin: '3px 0 2px' }}>{meta.title}</h3>
            <p style={{ fontSize: 13.5, color: 'var(--fg-3)', margin: 0 }}>{meta.sub}</p>
          </div>
          <button onClick={onClose} className="tbtn tbtn-ghost tbtn-sm" style={{ padding: 9 }} aria-label="Close"><Icon name="x" size={18}/></button>
        </div>
        <div style={{ padding: 24, overflow: 'auto', flex: 1, minHeight: 0, background: 'var(--bg-canvas)' }}>
          <div style={{ height: 'min(440px, 60vh)' }}><Demo/></div>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { DemoModal });
