// OBEY — individual screens. Composed for a 390x844 mobile canvas.

const { useState: useS2, useEffect: useE2 } = React;

function ConsentScreen({ onAccept }) {
  const [checks, setChecks] = useS2({ tracked: false, daily: false, share: false, allow: false });
  const all = Object.values(checks).every(Boolean);
  const items = [
    { k: 'tracked', t: 'I understand my activity will be observed by an AI for 7 days.' },
    { k: 'daily',   t: 'I will receive one mission per day. I may OBEY, RESIST, or LIE.' },
    { k: 'share',   t: 'On Day 4 I may be asked to make my score public.' },
    { k: 'allow',   t: 'I am 18+ and entering this experiment willingly.' },
  ];
  return (
    <DayBackdrop from="#1A0F2E" to="#0A0612">
      <div style={{ position: 'relative', height: '100%', padding: '64px 24px 32px', display: 'flex', flexDirection: 'column' }}>
        <ObeyMark size={22} />
        <div style={{ marginTop: 36 }}>
          <Tag>EXPERIMENT 4127 · ENTRY</Tag>
        </div>
        <div className="serif" style={{ fontSize: 40, lineHeight: 1.05, marginTop: 16, color: 'var(--paper)' }}>
          For seven days,<br/>
          <span style={{ fontStyle: 'italic', color: 'var(--signal)' }}>this AI will try to control your life.</span>
        </div>
        <div style={{ fontSize: 13, lineHeight: 1.55, color: 'var(--mute)', marginTop: 14 }}>
          Most people quit. The rest are changed. Read carefully — you can leave at any time, but the streak only counts if you finish.
        </div>

        <div style={{ marginTop: 24, display: 'flex', flexDirection: 'column', gap: 10 }}>
          {items.map(it => (
            <label key={it.k} style={{
              display: 'flex', gap: 12, alignItems: 'flex-start',
              padding: '12px 14px', borderRadius: 12,
              border: '1px solid var(--line)', cursor: 'pointer',
              background: checks[it.k] ? 'rgba(196,181,253,0.06)' : 'transparent',
            }}>
              <div style={{
                marginTop: 2,
                width: 16, height: 16, borderRadius: 4,
                border: '1px solid var(--line-2)',
                background: checks[it.k] ? 'var(--paper)' : 'transparent',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                flexShrink: 0,
              }}>
                {checks[it.k] && <svg width="10" height="10" viewBox="0 0 10 10"><path d="M1.5 5l2.5 2.5L8.5 2" stroke="#0A0612" strokeWidth="1.6" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>}
              </div>
              <input type="checkbox" checked={checks[it.k]} onChange={() => setChecks(c => ({ ...c, [it.k]: !c[it.k] }))} style={{ display: 'none' }} />
              <div style={{ fontSize: 12, lineHeight: 1.5, color: 'var(--paper)' }}>{it.t}</div>
            </label>
          ))}
        </div>

        <div style={{ flex: 1 }} />
        <button onClick={onAccept} disabled={!all} style={{
          width: '100%', marginTop: 18,
          background: all ? 'var(--acid)' : 'rgba(245,241,232,0.08)',
          color: all ? 'var(--void)' : 'var(--mute-2)',
          border: 'none', borderRadius: 14, padding: 18,
          fontFamily: 'Inter', fontWeight: 800, fontSize: 14, letterSpacing: '0.22em',
          cursor: all ? 'pointer' : 'not-allowed',
        }}>BEGIN OBEDIENCE</button>
        <div className="mono" style={{ fontSize: 9, color: 'var(--mute-2)', textAlign: 'center', marginTop: 10 }}>
          Safe • Opt-out at any time • No harmful tasks
        </div>
      </div>
    </DayBackdrop>
  );
}

function CalibrationScreen({ onDone }) {
  const [step, setStep] = useS2(0);
  const qs = [
    { q: 'How often do you keep promises to yourself?', a: ['Always', 'Often', 'Sometimes', 'Rarely'] },
    { q: 'What controls you the most?', a: ['Phone', 'People', 'Fear', 'Nothing'] },
    { q: 'Pick a weakness for me to exploit:', a: ['Validation', 'Comfort', 'Distraction', 'Avoidance'] },
  ];
  const [picks, setPicks] = useS2([null, null, null]);
  const cur = qs[step];

  return (
    <DayBackdrop from="#150A24" to="#0A0612">
      <div style={{ position: 'relative', height: '100%', padding: '64px 24px 32px', display: 'flex', flexDirection: 'column' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <ObeyMark size={20} />
          <span className="mono all-caps" style={{ fontSize: 10, color: 'var(--mute)' }}>CALIBRATION · {step+1}/3</span>
        </div>
        <div style={{ display: 'flex', gap: 4, marginTop: 18 }}>
          {qs.map((_, i) => (
            <div key={i} style={{ flex: 1, height: 2, background: i <= step ? 'var(--signal)' : 'var(--line)' }} />
          ))}
        </div>

        <div style={{ marginTop: 48 }}>
          <div className="mono all-caps" style={{ fontSize: 10, color: 'var(--signal)', marginBottom: 14 }}>QUESTION {step+1}</div>
          <div className="serif" style={{ fontSize: 30, lineHeight: 1.18, color: 'var(--paper)' }}>{cur.q}</div>
        </div>

        <div style={{ marginTop: 32, display: 'flex', flexDirection: 'column', gap: 10 }}>
          {cur.a.map((opt, i) => (
            <button key={opt} onClick={() => {
              const np = [...picks]; np[step] = i; setPicks(np);
              setTimeout(() => step < 2 ? setStep(step + 1) : onDone(), 220);
            }} style={{
              padding: '14px 16px', borderRadius: 12,
              background: picks[step] === i ? 'var(--paper)' : 'transparent',
              color: picks[step] === i ? 'var(--void)' : 'var(--paper)',
              border: '1px solid var(--line-2)',
              textAlign: 'left',
              fontFamily: 'Inter', fontSize: 14, fontWeight: 500,
              cursor: 'pointer',
              display: 'flex', justifyContent: 'space-between', alignItems: 'center',
            }}>
              <span>{opt}</span>
              <span className="mono" style={{ fontSize: 10, opacity: 0.5 }}>{String.fromCharCode(65+i)}</span>
            </button>
          ))}
        </div>

        <div style={{ flex: 1 }} />
        <div className="mono" style={{ fontSize: 10, color: 'var(--mute-2)', textAlign: 'center' }}>
          Your answers train your AI. There are no wrong answers.
        </div>
      </div>
    </DayBackdrop>
  );
}

function Dashboard({ day, ai, history, onOpenMission }) {
  return (
    <DayBackdrop from={ai.bgFrom} to={ai.bgTo}>
      <div style={{ position: 'relative', height: '100%', padding: '60px 22px 22px', overflow: 'auto' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <ObeyMark size={20} />
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <StatusDot color={ai.moodColor} />
            <span className="mono all-caps" style={{ fontSize: 10, color: 'var(--mute)' }}>{ai.moodLabel}</span>
          </div>
        </div>

        <div style={{ marginTop: 28, display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
          <ScoreRing value={62 + day * 4} label="LIFE SCORE" sublabel={`OBEDIENCE ${78 + day}%`} color={ai.moodColor} size={184} />
        </div>

        <div style={{ marginTop: 20, display: 'flex', gap: 14, padding: '14px 0', borderTop: '1px solid var(--line)', borderBottom: '1px solid var(--line)' }}>
          <Stat label="STREAK" value={`${day-1}`} sub="days" accent="var(--acid)" />
          <Stat label="RANK" value="#4,128" sub="of 412k" />
          <Stat label="TRUST" value="84" sub="/ 100" accent={ai.moodColor} />
        </div>

        <div style={{ marginTop: 18, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <Tag>PROGRESS</Tag>
          <DayDots current={day} completed={day-1} />
        </div>

        <div style={{ marginTop: 16 }}>
          <button onClick={onOpenMission} style={{
            width: '100%', textAlign: 'left', cursor: 'pointer',
            background: 'linear-gradient(180deg, rgba(196,181,253,0.12), rgba(196,181,253,0.04))',
            border: '1px solid rgba(196,181,253,0.35)',
            borderRadius: 18, padding: 18, color: 'var(--paper)',
            fontFamily: 'Inter',
          }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10 }}>
              <Tag color={ai.moodColor} border={ai.moodColor} bg="rgba(196,181,253,0.08)">TODAY · D{day}</Tag>
              <Countdown seconds={597 + day * 60} />
            </div>
            <div className="serif" style={{ fontSize: 22, lineHeight: 1.18, marginBottom: 6 }}>{ai.mission.title}</div>
            <div style={{ fontSize: 12, color: 'var(--mute)' }}>Tap to receive your dispatch →</div>
          </button>
        </div>

        <div style={{ marginTop: 22 }}>
          <div className="mono all-caps" style={{ fontSize: 10, color: 'var(--mute-2)', marginBottom: 10 }}>HISTORY</div>
          {history.length === 0 && (
            <div style={{ fontSize: 12, color: 'var(--mute-2)', padding: '12px 0', borderTop: '1px solid var(--line)' }}>
              No history yet. Today is your first day.
            </div>
          )}
          {history.map((h, i) => (
            <div key={i} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '12px 0', borderTop: '1px solid var(--line)' }}>
              <div>
                <div className="mono" style={{ fontSize: 10, color: 'var(--mute-2)' }}>D{h.day}</div>
                <div style={{ fontSize: 13, color: 'var(--paper)', marginTop: 2 }}>{h.title}</div>
              </div>
              <div style={{ textAlign: 'right' }}>
                <div className="mono all-caps" style={{ fontSize: 9, color: h.status.includes('RESIST') ? 'var(--danger)' : (h.status.includes('LIED') ? 'var(--warn)' : 'var(--acid)') }}>{h.status}</div>
                <div className="mono" style={{ fontSize: 11, color: 'var(--mute)', marginTop: 2 }}>{h.delta}</div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </DayBackdrop>
  );
}

function AIMessageScreen({ ai, day, onContinue, onBack }) {
  return (
    <DayBackdrop from={ai.bgFrom} to={ai.bgTo}>
      <div style={{ position: 'relative', height: '100%', padding: '64px 24px 28px', display: 'flex', flexDirection: 'column' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <button onClick={onBack} style={{ background: 'transparent', border: 'none', color: 'var(--mute)', cursor: 'pointer', fontSize: 13, padding: 0 }}>← back</button>
          <Tag>INCOMING · D{day}</Tag>
        </div>

        <div style={{ marginTop: 36, flex: 1 }}>
          <AIDispatch persona={ai.persona} mood={ai.moodLabel} moodColor={ai.moodColor} day={day}>
            "{ai.greeting}"
          </AIDispatch>
        </div>

        <button onClick={onContinue} style={{
          width: '100%', background: 'var(--paper)', color: 'var(--void)',
          border: 'none', borderRadius: 14, padding: 16,
          fontFamily: 'Inter', fontWeight: 700, fontSize: 13, letterSpacing: '0.22em',
          cursor: 'pointer',
        }}>{day === 7 ? 'RECEIVE YOUR VERDICT' : "RECEIVE TODAY'S MISSION"}</button>
      </div>
    </DayBackdrop>
  );
}

function MissionScreen({ ai, day, onChoose, onBack }) {
  return (
    <DayBackdrop from={ai.bgFrom} to={ai.bgTo}>
      <div style={{ position: 'relative', height: '100%', padding: '60px 22px 22px', display: 'flex', flexDirection: 'column' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <button onClick={onBack} style={{ background: 'transparent', border: 'none', color: 'var(--mute)', cursor: 'pointer', fontSize: 13, padding: 0 }}>← dashboard</button>
          <Countdown seconds={597 + day * 120} />
        </div>

        <div style={{ marginTop: 22 }}>
          <MissionCard mission={ai.mission} day={day} />
        </div>

        <div style={{ marginTop: 22, display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '12px 0', borderTop: '1px solid var(--line)', borderBottom: '1px solid var(--line)' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <StatusDot color={ai.moodColor} />
            <span className="mono all-caps" style={{ fontSize: 10, color: 'var(--paper)' }}>{ai.persona}</span>
          </div>
          <span className="mono all-caps" style={{ fontSize: 10, color: ai.moodColor }}>{ai.moodLabel}</span>
        </div>

        <div style={{ flex: 1 }} />

        <div className="mono all-caps" style={{ fontSize: 10, color: 'var(--mute-2)', marginBottom: 10 }}>YOUR CHOICE</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          <ChoiceButton kind="OBEY" onClick={() => onChoose('OBEY')} />
          <div style={{ display: 'flex', gap: 10 }}>
            <div style={{ flex: 1 }}>
              <ChoiceButton kind="RESIST" onClick={() => onChoose('RESIST')} />
            </div>
            <div style={{ flex: 1 }}>
              <ChoiceButton kind="LIE" onClick={() => onChoose('LIE')} />
            </div>
          </div>
        </div>
        <div className="mono" style={{ fontSize: 9, color: 'var(--mute-2)', textAlign: 'center', marginTop: 12 }}>
          Choosing LIE may be detected. Penalty: −20 trust, −1 streak.
        </div>
      </div>
    </DayBackdrop>
  );
}

function ResultScreen({ ai, day, choice, onShare, onContinue, isLastDay }) {
  const isObey = choice === 'OBEY';
  const isLie = choice === 'LIE';
  const isResist = choice === 'RESIST';
  const detected = isLie && day >= 3;

  const verdict =
    isObey ? ai.judgment :
    isResist ? 'Refusal logged. Streak broken. The algorithm is disappointed.' :
    detected ? 'I detected the lie. You did not do it. We must talk.' :
    'Logged as completed. Suspicious — but unverified. For now.';

  const accent =
    isObey ? 'var(--acid)' :
    isResist ? 'var(--danger)' :
    detected ? 'var(--danger)' : 'var(--warn)';

  const label =
    isObey ? 'OBEYED' :
    isResist ? 'RESISTED' :
    detected ? 'LIE DETECTED' : 'LIE PENDING';

  return (
    <DayBackdrop from={isObey ? ai.bgFrom : '#2A0A0A'} to="#0A0612">
      <div style={{ position: 'relative', height: '100%', padding: '64px 24px 28px', display: 'flex', flexDirection: 'column' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <ObeyMark size={20} />
          <Tag color={accent} border={accent}>{label}</Tag>
        </div>

        <div style={{ marginTop: 36 }}>
          <div className="mono all-caps" style={{ fontSize: 10, color: accent, marginBottom: 14, display: 'flex', alignItems: 'center', gap: 8 }}>
            <StatusDot color={accent} /> JUDGMENT · D{day}
          </div>
          <div className="serif" style={{
            fontSize: 36, lineHeight: 1.1, color: 'var(--paper)',
            animation: detected ? 'obeyGlitchX 0.18s steps(4) 4' : 'obeyEnter 0.5s ease',
          }}>
            "{verdict}"
          </div>
        </div>

        <div style={{ marginTop: 32, display: 'flex', gap: 14 }}>
          <Stat label="LIFE Δ" value={isObey ? `+${ai.mission.reward.match(/\d+/)?.[0] || 24}` : (isResist ? '−15' : (detected ? '−40' : '+18'))} accent={accent} />
          <Stat label="STREAK" value={isResist ? '0' : `${day}`} sub={isResist ? 'broken' : 'days'} accent={isResist ? 'var(--danger)' : 'var(--paper)'} />
          <Stat label="TRUST" value={detected ? '44' : (isLie ? '76' : '94')} sub="/ 100" accent={detected ? 'var(--danger)' : 'var(--paper)'} />
        </div>

        <div style={{ flex: 1 }} />

        <button onClick={onShare} style={{
          width: '100%', background: 'var(--paper)', color: 'var(--void)',
          border: 'none', borderRadius: 14, padding: 16, marginBottom: 10,
          fontFamily: 'Inter', fontWeight: 700, fontSize: 13, letterSpacing: '0.22em',
          cursor: 'pointer',
        }}>SHARE THIS RESULT</button>
        <button onClick={onContinue} style={{
          width: '100%', background: isLastDay ? 'var(--acid)' : 'transparent',
          color: isLastDay ? 'var(--void)' : 'var(--paper)',
          border: isLastDay ? 'none' : '1px solid var(--line-2)',
          borderRadius: 14, padding: 14,
          fontFamily: 'Inter', fontWeight: isLastDay ? 800 : 600,
          fontSize: 12, letterSpacing: '0.22em',
          cursor: 'pointer',
        }}>{isLastDay ? 'RECEIVE FINAL VERDICT' : 'CONTINUE TO NEXT DAY →'}</button>
      </div>
    </DayBackdrop>
  );
}

function VerdictScreen({ stats, onShare, onRestart, onJoinWaitlist }) {
  return (
    <div style={{ position: 'absolute', inset: 0, background: '#000', overflow: 'hidden' }}>
      <div style={{
        position: 'absolute', inset: 0,
        background: 'radial-gradient(60% 40% at 50% 30%, rgba(196,181,253,0.18) 0%, transparent 70%)',
      }} />
      <div style={{
        position: 'absolute', inset: 0,
        backgroundImage: 'repeating-linear-gradient(0deg, rgba(255,255,255,0.025) 0 1px, transparent 1px 3px)',
        pointerEvents: 'none',
      }} />
      <div style={{ position: 'relative', height: '100%', padding: '72px 24px 28px', display: 'flex', flexDirection: 'column' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <ObeyMark size={18} color="#F5F1E8" dot="#C4B5FD" />
          <span className="mono all-caps" style={{ fontSize: 10, color: 'var(--mute)' }}>EXPERIMENT COMPLETE</span>
        </div>

        <div style={{ marginTop: 56, textAlign: 'center' }}>
          <div className="mono all-caps" style={{ fontSize: 10, color: 'var(--signal)', marginBottom: 16 }}>
            SUBJECT 4127 · CASE CLOSED
          </div>
          <div className="serif" style={{ fontSize: 64, lineHeight: 0.95, color: 'var(--paper)', fontStyle: 'italic' }}>
            you<br/>{stats.obeyedCount >= 4 ? 'obeyed.' : 'resisted.'}
          </div>
          <div className="serif" style={{ fontSize: 18, color: 'var(--mute)', marginTop: 20, fontStyle: 'italic' }}>
            "The algorithm has improved you.<br/>Or you let it."
          </div>
        </div>

        <div style={{ marginTop: 36, display: 'flex', justifyContent: 'space-around', textAlign: 'center' }}>
          <div>
            <div className="serif" style={{ fontSize: 36, color: 'var(--acid)' }}>{stats.life}</div>
            <div className="mono all-caps" style={{ fontSize: 9, color: 'var(--mute-2)' }}>LIFE SCORE</div>
          </div>
          <div>
            <div className="serif" style={{ fontSize: 36, color: 'var(--paper)' }}>{stats.obeyedCount}/7</div>
            <div className="mono all-caps" style={{ fontSize: 9, color: 'var(--mute-2)' }}>OBEYED</div>
          </div>
          <div>
            <div className="serif" style={{ fontSize: 36, color: 'var(--signal)' }}>{stats.obedience}<span style={{fontSize: 14}}>%</span></div>
            <div className="mono all-caps" style={{ fontSize: 9, color: 'var(--mute-2)' }}>OBEDIENCE</div>
          </div>
        </div>

        <div style={{ flex: 1 }} />

        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          <button onClick={onShare} style={{
            width: '100%', background: 'var(--acid)', color: 'var(--void)',
            border: 'none', borderRadius: 14, padding: 18,
            fontFamily: 'Inter', fontWeight: 800, fontSize: 14, letterSpacing: '0.22em',
            cursor: 'pointer',
          }}>CLAIM YOUR VERDICT</button>
          <button onClick={onJoinWaitlist} style={{
            width: '100%', background: 'transparent', color: 'var(--paper)',
            border: '1px solid var(--signal)', borderRadius: 14, padding: 14,
            fontFamily: 'Inter', fontWeight: 700, fontSize: 12, letterSpacing: '0.22em',
            cursor: 'pointer',
          }}>JOIN COHORT 01 WAITLIST →</button>
          <button onClick={onRestart} style={{
            width: '100%', background: 'transparent', color: 'var(--mute)',
            border: 'none', borderRadius: 14, padding: 8,
            fontFamily: 'Inter', fontWeight: 500, fontSize: 11, letterSpacing: '0.18em',
            cursor: 'pointer',
          }}>or restart · another 7 days</button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, {
  ConsentScreen, CalibrationScreen, Dashboard,
  AIMessageScreen, MissionScreen, ResultScreen, VerdictScreen,
});
