// screens-check.jsx — SystemCheckScreen, RecordConsentScreen, FinalConsentScreen
const { useState: useStateC, useEffect: useEffectC, useRef: useRefC } = React;

function CheckRow({ icon, title, status, detail, children }) {
  const bgMap = { good: 'var(--success-soft)', testing: 'var(--accent-soft)', warn: 'var(--warn-soft)' };
  const fgMap = { good: 'var(--success)', testing: 'var(--accent)', warn: 'var(--warn)' };
  const borderMap = { good: 'rgba(14,138,79,.15)', testing: 'rgba(255,90,31,.15)', warn: 'rgba(182,121,10,.15)' };
  return (
    <div style={{ display: 'flex', gap: 14, padding: '18px 0', alignItems: 'flex-start' }}>
      <div style={{
        width: 42, height: 42, borderRadius: 12, flexShrink: 0, display: 'grid', placeItems: 'center',
        background: bgMap[status] || 'var(--surface-2)',
        color: fgMap[status] || 'var(--text-dim)',
        border: `1px solid ${borderMap[status] || 'var(--border)'}`,
        transition: 'all .2s',
      }}>
        <Icon name={icon} size={19} stroke={1.8} />
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10 }}>
          <span style={{ fontSize: 14.5, fontWeight: 600, color: 'var(--text)' }}>{title}</span>
          {status === 'good' && <StatusPill status="good" icon="check">Ready</StatusPill>}
          {status === 'testing' && <span style={{ fontSize: 12, color: 'var(--text-faint)', display: 'flex', alignItems: 'center', gap: 6 }}><Spinner /> Testing…</span>}
          {status === 'warn' && <StatusPill status="warn" icon="alert">Check</StatusPill>}
        </div>
        {detail && <div style={{ fontSize: 12.5, color: 'var(--text-faint)', marginTop: 3, lineHeight: 1.4 }}>{detail}</div>}
        {children}
      </div>
    </div>
  );
}

function MicMeter({ level }) {
  const bars = 16;
  const active = Math.round(level * bars);
  return (
    <div style={{ display: 'flex', gap: 2.5, alignItems: 'flex-end', marginTop: 10, height: 24 }}>
      {Array.from({ length: bars }).map((_, i) => (
        <span key={i} style={{
          flex: 1, borderRadius: 3,
          height: `${25 + (i / bars) * 75}%`,
          background: i < active ? (i > bars * 0.8 ? 'var(--warn)' : 'var(--success)') : 'var(--border)',
          transition: 'background .08s',
        }} />
      ))}
    </div>
  );
}

function SystemCheckScreen({ go, cfg }) {
  const { status: camStatus, stream, request } = useMediaStream(true);
  const videoRef = useVideoRef(stream);
  // simulate=false — a candidate whose mic genuinely failed to grant access must see a flat,
  // unmoving meter (an honest "no signal"), not fake bars swaying on their own. The old
  // default simulated motion here specifically so the meter didn't look "dead" while waiting
  // — but that's indistinguishable from "your mic is actually being read", which is actively
  // misleading right before a real interview.
  const hasRealAudio = !!(stream && stream.getAudioTracks().length);
  const micLevel = useMicLevel(stream, camStatus === 'granted' || camStatus === 'denied', false);
  const browser = detectBrowser();

  const [speed, setSpeed] = useStateC({ phase: 'testing', mbps: 0 });
  const [spkTested, setSpkTested] = useStateC(false);
  const [spkPlaying, setSpkPlaying] = useStateC(false);
  const [consent, setConsent] = useStateC(false);
  const [showNoBack, setShowNoBack] = useStateC(false);

  useEffectC(() => {
    let n = 0; const target = 58 + Math.floor(Math.random() * 20);
    const iv = setInterval(() => {
      n += target / 22 + Math.random() * 4;
      if (n >= target) { n = target; clearInterval(iv); setSpeed({ phase: 'done', mbps: Math.round(target) }); }
      else setSpeed({ phase: 'testing', mbps: Math.round(n) });
    }, 90);
    return () => clearInterval(iv);
  }, []);

  const playTone = () => {
    setSpkPlaying(true);
    try {
      const ctx = new (window.AudioContext || window.webkitAudioContext)();
      const osc = ctx.createOscillator(); const g = ctx.createGain();
      osc.connect(g); g.connect(ctx.destination);
      osc.type = 'sine'; osc.frequency.value = 523;
      g.gain.setValueAtTime(0.0001, ctx.currentTime);
      g.gain.exponentialRampToValueAtTime(0.18, ctx.currentTime + 0.05);
      g.gain.exponentialRampToValueAtTime(0.0001, ctx.currentTime + 1.0);
      osc.start(); osc.stop(ctx.currentTime + 1.05);
    } catch (e) {}
    setTimeout(() => { setSpkPlaying(false); setSpkTested(true); }, 1100);
  };

  const camReady = camStatus === 'granted';
  const allReady = speed.phase === 'done' && spkTested && (camStatus === 'granted' || camStatus === 'denied' || camStatus === 'unsupported');

  return (
    <div style={{ width: '100%' }}>
      <TopBar right={null} />
      <Screen max={920} style={{ padding: '12px 24px 60px' }}>
        <div style={{ textAlign: 'center', marginBottom: 26, width: '100%' }}>
          <h1 style={{ fontSize: 'clamp(24px,4vw,32px)', fontFamily: 'var(--font-display)', fontWeight: 400, letterSpacing: '-0.01em', width: '100%', color: 'var(--text)', margin: 0 }}>Let's check your setup</h1>
          <p style={{ fontSize: 16, color: 'var(--text-dim)', marginTop: 10 }}>A quick test so nothing interrupts your interview.</p>
        </div>

        <div className="check-grid" style={{ display: 'grid', gridTemplateColumns: 'minmax(300px, 1fr) minmax(300px, 1fr)', gap: 20, width: '100%', alignItems: 'start' }}>
          {/* Camera preview */}
          <div>
            <div style={{
              position: 'relative', aspectRatio: '4/3', borderRadius: 18, overflow: 'hidden',
              background: 'var(--video-bg)', border: '1px solid var(--border)', boxShadow: 'var(--shadow-md)',
            }}>
              {camReady ? (
                <video ref={videoRef} autoPlay playsInline muted style={{ width: '100%', height: '100%', objectFit: 'cover', transform: 'scaleX(-1)' }} />
              ) : (
                <CameraPlaceholder status={camStatus} onRetry={request} />
              )}
              <div style={{ position: 'absolute', left: 12, bottom: 12, display: 'flex', alignItems: 'center', gap: 8, background: 'oklch(0.2 0.02 60 / 0.6)', backdropFilter: 'blur(8px)', padding: '6px 11px', borderRadius: 999 }}>
                <Icon name="camera" size={14} stroke={2} style={{ color: '#fff' }} />
                <span style={{ fontSize: 12, color: '#fff', fontWeight: 600 }}>{camReady ? 'Camera live' : 'Preview'}</span>
              </div>
            </div>
            <div style={{ marginTop: 12, padding: '12px 16px', background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 13 }}>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <span style={{ fontSize: 13.5, fontWeight: 600, color: 'var(--text)', display: 'flex', alignItems: 'center', gap: 7 }}><Icon name="mic" size={15} stroke={2} style={{ color: 'var(--accent)' }} /> Microphone level</span>
                <span style={{ fontSize: 12, color: 'var(--text-faint)' }}>{hasRealAudio ? 'Say a few words' : 'Mic access needed to test'}</span>
              </div>
              <MicMeter level={micLevel} />
            </div>
          </div>

          {/* Checks list */}
          <Card pad={8} style={{ width: '100%' }}>
            <div style={{ padding: '6px 22px' }}>
              <CheckRow icon="camera" title="Camera"
                status={camReady ? 'good' : (camStatus === 'requesting' ? 'testing' : 'warn')}
                detail={camReady ? '720p · front camera detected' : (camStatus === 'denied' ? 'Access blocked — you can still continue' : camStatus === 'unsupported' ? 'Not available in this preview' : 'Requesting access…')} />
              <div style={{ height: 1, background: 'var(--border)' }} />
              <CheckRow icon="mic" title="Microphone"
                status={(camReady) ? 'good' : (camStatus === 'denied' || camStatus === 'unsupported' ? 'warn' : 'testing')}
                detail={camReady ? 'Default input · levels look healthy' : 'Will use system default input'} />
              <div style={{ height: 1, background: 'var(--border)' }} />
              <CheckRow icon="speaker" title="Speakers"
                status={spkTested ? 'good' : 'warn'}
                detail={spkTested ? 'Test tone played successfully' : 'Play a tone to confirm you can hear'}>
                {!spkTested && <div style={{ marginTop: 10 }}><Button size="sm" variant="secondary" icon={spkPlaying ? undefined : 'play'} onClick={playTone} disabled={spkPlaying}>{spkPlaying ? 'Playing…' : 'Play test sound'}</Button></div>}
              </CheckRow>
              <div style={{ height: 1, background: 'var(--border)' }} />
              <CheckRow icon="wifi" title="Internet speed"
                status={speed.phase === 'done' ? 'good' : 'testing'}
                detail={speed.phase === 'done' ? `${speed.mbps} Mbps · excellent for video` : `Measuring… ${speed.mbps} Mbps`} />
              <div style={{ height: 1, background: 'var(--border)' }} />
              <CheckRow icon="shield" title="Browser"
                status="good"
                detail={`${browser.name} · fully supported`} />
            </div>
          </Card>
        </div>

        {/* Consent — inline on the test screen (no separate step) */}
        <div style={{ width: '100%', marginTop: 18, padding: '16px 18px', background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 14, display: 'flex', flexDirection: 'column', gap: 12 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
            <Icon name="record" size={15} fill="var(--accent)" />
            <span style={{ fontSize: 14.5, fontWeight: 600, color: 'var(--text)' }}>Recording consent</span>
          </div>
          <Checkbox checked={consent} onChange={setConsent}>
            I consent to this interview being recorded and transcribed for evaluation, and confirm I'm in a private space. <span style={{ color: 'var(--accent)', fontWeight: 600 }}>Privacy notice</span>.
          </Checkbox>
        </div>

        <div style={{ display: 'flex', gap: 12, marginTop: 18, width: '100%', maxWidth: 480 }}>
          <Button variant="ghost" icon="arrowLeft" onClick={() => go('landing')}>Back</Button>
          <Button full disabled={!allReady || !consent} icon="record" onClick={() => setShowNoBack(true)}>
            {!allReady ? 'Running checks…' : !consent ? 'Accept consent to continue' : 'Start interview'}
          </Button>
        </div>
      </Screen>

      {showNoBack && (
        <Modal onClose={() => setShowNoBack(false)} width={420}>
          <div style={{ fontWeight: 700, fontSize: 16, color: 'var(--text)', marginBottom: 8 }}>Ready? There's no starting over</div>
          <div style={{ fontSize: 13.5, color: 'var(--text-dim)', lineHeight: 1.6, marginBottom: 22 }}>
            Once you begin, this is your <strong style={{ color: 'var(--text)' }}>one attempt — it cannot be restarted from scratch</strong>. If you get disconnected, reopening this same link will pick up right where you left off. Leaving the tab while connected is recorded and flagged.
          </div>
          <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end' }}>
            <Button variant="secondary" onClick={() => setShowNoBack(false)}>Not yet</Button>
            <Button icon="record" onClick={() => go('interview')}>Begin now</Button>
          </div>
        </Modal>
      )}
    </div>
  );
}

function CameraPlaceholder({ status, onRetry }) {
  return (
    <div style={{ position: 'absolute', inset: 0, display: 'grid', placeItems: 'center', background: 'repeating-linear-gradient(135deg, oklch(0.3 0.015 60) 0 12px, oklch(0.32 0.015 60) 12px 24px)' }}>
      <div style={{ textAlign: 'center', color: 'oklch(0.85 0.01 60)' }}>
        <Icon name="camera" size={40} stroke={1.6} style={{ opacity: 0.7 }} />
        <div style={{ fontSize: 13.5, marginTop: 10, fontFamily: 'var(--font-mono)', opacity: 0.85 }}>
          {status === 'requesting' ? 'requesting camera…' : status === 'denied' ? 'camera access blocked' : 'camera preview'}
        </div>
        {(status === 'denied' || status === 'idle') && (
          <div style={{ marginTop: 14 }}>
            <button onClick={onRetry} style={{ background: 'oklch(0.95 0.01 60 / 0.15)', border: '1px solid oklch(0.9 0.01 60 / 0.3)', color: '#fff', padding: '7px 14px', borderRadius: 9, fontSize: 13, fontFamily: 'var(--font)', fontWeight: 600, cursor: 'pointer' }}>Enable camera</button>
          </div>
        )}
      </div>
    </div>
  );
}

function RecordConsentScreen({ go, cfg }) {
  const [consent, setConsent] = useStateC(false);
  return (
    <div style={{ width: '100%' }}>
      <TopBar right={null} />
      <Screen max={540} style={{ padding: '24px 24px 60px' }}>
        <div style={{ width: 60, height: 60, borderRadius: 15, background: 'var(--accent-soft)', color: 'var(--accent)', display: 'grid', placeItems: 'center', marginBottom: 20 }}>
          <Icon name="record" size={26} fill="currentColor" />
        </div>
        <h1 style={{ fontSize: 'clamp(24px,4vw,30px)', fontFamily: 'var(--font-display)', fontWeight: 400, letterSpacing: '-0.01em', width: '100%', color: 'var(--text)', margin: 0, textAlign: 'center' }}>Consent to record</h1>
        <p style={{ fontSize: 16, color: 'var(--text-dim)', marginTop: 12, marginBottom: 24, textAlign: 'center', textWrap: 'pretty' }}>
          To evaluate your interview fairly, we record and transcribe the session. Here's exactly what that means.
        </p>
        <Card style={{ width: '100%' }} pad={8}>
          <div style={{ padding: '6px 20px' }}>
            {[
              { icon: 'camera', t: 'Video & audio are recorded', d: 'Your camera and microphone are captured for the duration of the interview.' },
              { icon: 'sparkle', t: 'A live transcript is generated', d: 'Your spoken answers are transcribed in real time and reviewed by our hiring team.' },
              { icon: 'shieldCheck', t: 'Stored securely, used only for hiring', d: 'Recordings are encrypted, access-controlled, and never shared outside the evaluation.' },
            ].map((x, i, arr) => (
              <div key={x.t}>
                <div style={{ display: 'flex', gap: 13, padding: '14px 0' }}>
                  <Icon name={x.icon} size={20} stroke={2} style={{ color: 'var(--accent)', flexShrink: 0, marginTop: 1 }} />
                  <div>
                    <div style={{ fontSize: 14.5, fontWeight: 600, color: 'var(--text)' }}>{x.t}</div>
                    <div style={{ fontSize: 13, color: 'var(--text-faint)', marginTop: 2, lineHeight: 1.45 }}>{x.d}</div>
                  </div>
                </div>
                {i < arr.length - 1 && <div style={{ height: 1, background: 'var(--border)' }} />}
              </div>
            ))}
          </div>
        </Card>
        <div style={{ width: '100%', marginTop: 18, padding: '16px 18px', background: 'var(--surface-2)', borderRadius: 13, border: '1px solid var(--border)' }}>
          <Checkbox checked={consent} onChange={setConsent}>
            I consent to this interview being recorded and transcribed, and I confirm I'm in a private space. <span style={{ color: 'var(--accent)', fontWeight: 600 }}>Read the privacy notice</span>.
          </Checkbox>
        </div>
        <div style={{ display: 'flex', gap: 12, marginTop: 22, width: '100%' }}>
          <Button variant="ghost" icon="arrowLeft" onClick={() => go('check')}>Back</Button>
          <Button full disabled={!consent} iconRight="arrowRight" onClick={() => go('final')}>I consent — continue</Button>
        </div>
      </Screen>
    </div>
  );
}

function FinalConsentScreen({ go, cfg }) {
  const [ack, setAck] = useStateC(false);
  return (
    <div style={{ width: '100%' }}>
      <TopBar right={null} />
      <Screen max={540} style={{ padding: '24px 24px 60px' }}>
        <div style={{ width: 60, height: 60, borderRadius: 15, background: 'var(--warn-soft)', color: 'var(--warn)', display: 'grid', placeItems: 'center', marginBottom: 20 }}>
          <Icon name="alert" size={28} stroke={2.2} />
        </div>
        <h1 style={{ fontSize: 'clamp(24px,4vw,30px)', fontFamily: 'var(--font-display)', fontWeight: 400, letterSpacing: '-0.01em', width: '100%', color: 'var(--text)', margin: 0, textAlign: 'center', textWrap: 'balance' }}>One last thing before you begin</h1>
        <p style={{ fontSize: 16, color: 'var(--text-dim)', marginTop: 12, marginBottom: 24, textAlign: 'center', textWrap: 'pretty' }}>
          This is a single, continuous attempt. Please read these carefully — they cannot be undone once you start.
        </p>
        <div style={{ width: '100%', display: 'flex', flexDirection: 'column', gap: 10 }}>
          {[
            { icon: 'lock', t: 'No going back', d: 'Once the interview starts, you cannot pause, restart, or return to a previous step.' },
            { icon: 'eye', t: 'Stay on this tab', d: 'Switching tabs or windows is recorded and flagged to the hiring team as a possible integrity concern.' },
            { icon: 'shield', t: 'Copy, paste, and screenshots are blocked', d: 'Text selection and copy/paste are disabled during the call, and screenshot attempts are recorded and flagged. Please don’t use a second device, virtual camera/mic, or an AI assistant during the interview — unusual signals like these are logged for the hiring team’s review.' },
            { icon: 'clock', t: 'One attempt only', d: `You have a single ${cfg.duration}-minute session. Ending the call concludes your interview.` },
          ].map((x) => (
            <div key={x.t} style={{ display: 'flex', gap: 13, padding: '14px 16px', background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 13 }}>
              <div style={{ width: 34, height: 34, borderRadius: 9, background: 'var(--warn-soft)', color: 'var(--warn)', display: 'grid', placeItems: 'center', flexShrink: 0 }}>
                <Icon name={x.icon} size={17} stroke={2} />
              </div>
              <div>
                <div style={{ fontSize: 14.5, fontWeight: 600, color: 'var(--text)' }}>{x.t}</div>
                <div style={{ fontSize: 13, color: 'var(--text-faint)', marginTop: 2, lineHeight: 1.45 }}>{x.d}</div>
              </div>
            </div>
          ))}
        </div>
        <div style={{ width: '100%', marginTop: 16, padding: '16px 18px', background: 'var(--surface-2)', borderRadius: 13, border: '1px solid var(--border)' }}>
          <Checkbox checked={ack} onChange={setAck}>I understand I can't go back, and that leaving this tab may be flagged. I'm ready to begin.</Checkbox>
        </div>
        <div style={{ display: 'flex', gap: 12, marginTop: 22, width: '100%' }}>
          <Button variant="ghost" icon="arrowLeft" onClick={() => go('consent')}>Back</Button>
          <Button full disabled={!ack} iconRight="arrowRight" onClick={() => go('interview')} icon="record">Begin interview</Button>
        </div>
      </Screen>
    </div>
  );
}

Object.assign(window, { SystemCheckScreen, RecordConsentScreen, FinalConsentScreen, Spinner });
