/* Variation CTO — 10-question peer review for the technical director.
   Same warm-dark editorial language but framed as engineer-to-engineer.
   Uses ?role=cto to pull the technical question set + interactive widgets. */

// Inline ladder for {v, label} levels.
function CTOLadder({ levels, value, onChange }) {
  return (
    <div className="cto-ladder">
      {levels.map(lv => (
        <button
          key={lv.v}
          className="cto-ladder-step"
          data-level={lv.v}
          aria-pressed={value === lv.v}
          onClick={() => onChange(value === lv.v ? undefined : lv.v)}
        >
          <span className="cto-ladder-num cf-mono">{String(lv.v).padStart(2, '0')}</span>
          <span className="cto-ladder-label">{lv.label}</span>
          <span className="cto-ladder-mark" />
        </button>
      ))}
    </div>
  );
}

function makeCTOQuestions(t) {
  const c = t.cq;
  const slider = (key) => ({ key, kicker: c[key].kicker, title: c[key].title, lead: c[key].lead,
    render: (a, set, onAuto) => (
      <SliderScale value={a[key]} onChange={v => set(key, v)} lowLabel={c[key].low} highLabel={c[key].high} leftWord={c[key].low} rightWord={c[key].high} />
    ),
  });
  const ladder = (key) => ({ key, kicker: c[key].kicker, title: c[key].title, lead: c[key].lead,
    render: (a, set) => <CTOLadder levels={c[key].levels} value={a[key]} onChange={v => set(key, v)} />,
  });
  return [
    slider('summary'),
    { key: 'mood', kicker: c.mood.kicker, title: c.mood.title, lead: c.mood.lead,
      render: (a, set, onAuto) => <MoodPicker value={a.mood} onChange={v => set('mood', v)} onAutoAdvance={onAuto} t={{ ...t, q: { ...t.q, mood: { moods: c.mood.moods } } }} /> },
    { key: 'skills', kicker: c.skills.kicker, title: c.skills.title, lead: c.skills.lead,
      render: (a, set) => <SkillMatrix skills={c.skills.list} value={a.skills || {}} onChange={v => set('skills', v)} /> },
    { key: 'stack', kicker: c.stack.kicker, title: c.stack.title, lead: c.stack.lead,
      render: (a, set) => <StackPicker tags={c.stack.tags} value={a.stack || []} onChange={v => set('stack', v)} /> },
    { key: 'diff', kicker: c.diff.kicker, title: c.diff.title, lead: c.diff.lead,
      render: (a, set) => <CodeDiffPick samples={c.diff.samples} value={a.diff} onChange={v => set('diff', v)} t={t} /> },
    { key: 'pairs', kicker: c.pairs.kicker, title: c.pairs.title, lead: c.pairs.lead,
      render: (a, set) => <WordPair pairs={c.pairs.list} value={a.pairs || {}} onChange={v => set('pairs', v)} /> },
    { key: 'pr', kicker: c.pr.kicker, title: c.pr.title, lead: c.pr.lead,
      render: (a, set) => <WordPair pairs={c.pr.list} value={a.pr || {}} onChange={v => set('pr', v)} /> },
    slider('share'),
    ladder('grit'),
    { key: 'trust', kicker: c.trust.kicker, title: c.trust.title, lead: c.trust.lead,
      render: (a, set) => <TrustMeter items={c.trust.list.map(it => ({ ...it, levels: c.trust.levels }))} value={a.trust || {}} onChange={v => set('trust', v)} /> },
    { key: 'ship', kicker: c.ship.kicker, title: c.ship.title, lead: c.ship.lead,
      render: (a, set) => <YesNoWithReason value={a.ship || {}} onChange={v => set('ship', v)} yesLabel={c.ship.yes} noLabel={c.ship.no} reasonPlaceholder={c.ship.reasonPlaceholder} /> },
    { key: 'rhythm', kicker: c.rhythm.kicker, title: c.rhythm.title, lead: c.rhythm.lead,
      render: (a, set) => <RhythmGraph value={a.rhythm || []} onChange={v => set('rhythm', v)} weeks={8} /> },
    { key: 'points', kicker: c.points.kicker, title: c.points.title, lead: c.points.lead,
      render: (a, set) => <PointsAllocator buckets={c.points.buckets} value={a.points || {}} onChange={v => set('points', v)} total={100} /> },
    { key: 'flow', kicker: c.flow.kicker, title: c.flow.title, lead: c.flow.lead,
      render: (a, set) => <ProcessFlow stages={c.flow.stages} value={a.flow || {}} onChange={v => set('flow', v)} /> },
    slider('hire'),
    { key: 'steal', kicker: c.steal.kicker, title: c.steal.title, lead: c.steal.lead,
      render: (a, set) => <StealPicker tags={c.steal.tags} value={a.steal || []} onChange={v => set('steal', v)} max={3} /> },
    { key: 'sort', kicker: c.sort.kicker, title: c.sort.title, lead: c.sort.lead,
      render: (a, set) => <SortablePriorities items={c.sort.items} value={a.sort} onChange={v => set('sort', v)} /> },
    { key: 'risk', kicker: c.risk.kicker, title: c.risk.title, lead: c.risk.lead,
      render: (a, set) => <RiskFlag value={a.risk || {}} onChange={v => set('risk', v)} placeholder={c.risk.placeholder} severityLow={c.risk.sevLow} severityHigh={c.risk.sevHigh} /> },
    ladder('readiness'),
    { key: 'open', kicker: c.open.kicker, title: c.open.title, lead: c.open.lead,
      render: (a, set) => <OpenQuestion value={a.open} onChange={v => set('open', v)} t={{ ...t, q: { ...t.q, open: c.open } }} /> },
  ];
}

function VariationCTO({ frameW = 1280, frameH = 820 }) {
  const { lang, id, setLang } = useRoute();
  const t = useT(lang, 'cto');
  const client = useClient(id);
  const questions = useMemo(() => makeCTOQuestions(t), [t]);
  const total = questions.length;
  const wiz = useWizard(id, total, 'vcto');
  const { state, setAnswer, next, back, start, finish } = wiz;
  const stepIdx = state.step;
  const isStart = !state.started;
  const isDone = state.done;
  const onLast = stepIdx === total - 1;

  return (
    <div style={vctoStyles.frame(frameW, frameH)}>
      <header style={vctoStyles.header}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
          <div style={vctoStyles.mark}>{`{ }`}</div>
          <div>
            <div style={{ fontSize: 12, letterSpacing: '0.18em', textTransform: 'uppercase', color: 'var(--text-2)' }}>{t.brand} · CTO TRACK</div>
            <div className="cf-mono" style={{ color: 'var(--text-3)', marginTop: 2 }}>{t.pill} · /{lang}/{id}?role=cto</div>
          </div>
        </div>
        <LangSwitcher lang={lang} onChange={setLang} />
      </header>

      {state.started && !isDone && (
        <div className="cf-progress"><span style={{ width: `${((stepIdx+1)/total)*100}%` }} /></div>
      )}

      <main style={vctoStyles.main}>
        {isStart ? (
          <div className="cf-step-enter" style={vctoStyles.grid}>
            <div>
              <div className="cf-mono" style={{ color: 'var(--accent-2)', marginBottom: 18 }}>{t.greetingKicker}</div>
              <h1 className="cf-serif" style={vctoStyles.h1}>{t.greetingTitle(client.contact || client.name)}</h1>
              <p style={vctoStyles.lead}>{t.greetingLead}</p>
              <div style={{ display: 'flex', gap: 18, alignItems: 'center', marginTop: 36, flexWrap: 'wrap' }}>
                <button className="cf-btn cf-btn--lg" onClick={start}>{t.cta} →</button>
                <span className="cf-mono" style={{ color: 'var(--text-3)' }}>{t.greetingMeta}</span>
              </div>
              <div style={{ display: 'flex', gap: 8, marginTop: 28, flexWrap: 'wrap' }}>
                {questions.map((q, i) => (
                  <span key={q.key} className="cf-mono" style={{
                    fontSize: 10, padding: '6px 10px', borderRadius: 999,
                    background: 'rgba(255,255,255,0.04)', color: 'var(--text-3)',
                    border: '1px solid var(--ink-line)',
                  }}>
                    {String(i + 1).padStart(2, '0')} {q.kicker.split('·')[1]?.trim() || ''}
                  </span>
                ))}
              </div>
            </div>
            <aside style={vctoStyles.aside}>
              <div className="cf-mono" style={{ color: 'var(--accent-2)' }}>// peer review</div>
              <pre style={vctoStyles.code}>{`function review(me) {
  return {
    strengths: [...],
    sloppiness: [...],
    nextLevel: '???',
  };
}`}</pre>
              <div className="cf-mono" style={{ color: 'var(--text-3)', marginTop: 18, lineHeight: 1.8 }}>
                10 questions<br/>
                · 1 slider<br/>
                · 1 mood<br/>
                · skill matrix<br/>
                · stack tags<br/>
                · code diff<br/>
                · ship gate<br/>
                · rhythm grid<br/>
                · 100-point split<br/>
                · drag to rank<br/>
                · open feedback
              </div>
            </aside>
          </div>
        ) : isDone ? (
          <div className="cf-step-enter" style={{ position: 'relative', textAlign: 'center', maxWidth: 620, margin: '0 auto' }}>
            <Confetti />
            <DoneCheckmark />
            <div className="cf-mono" style={{ color: 'var(--accent-2)', marginTop: 28 }}>{t.done.kicker}</div>
            <h2 className="cf-serif" style={{ ...vctoStyles.h2, marginTop: 14 }}>{t.done.title}</h2>
            <p style={vctoStyles.lead}>{t.done.lead}</p>
          </div>
        ) : (
          <div key={stepIdx} className="cf-step-enter" style={vctoStyles.stepGrid}>
            <div style={vctoStyles.stepLeft}>
              <div className="cf-mono" style={{ color: 'var(--accent-2)' }}>{questions[stepIdx].kicker}</div>
              <div className="cf-mono" style={{ color: 'var(--text-3)', marginTop: 'auto' }}>{t.progress(stepIdx + 1, total)}</div>
            </div>
            <div style={vctoStyles.stepRight}>
              <h2 className="cf-serif" style={vctoStyles.h2}>{questions[stepIdx].title}</h2>
              <p style={vctoStyles.lead}>{questions[stepIdx].lead}</p>
              <div style={{ marginTop: 32 }}>
                {questions[stepIdx].render(state.answers, setAnswer, onLast ? finish : next)}
              </div>
              <div style={{ display: 'flex', gap: 12, marginTop: 36 }}>
                {stepIdx > 0 && <button className="cf-btn cf-btn--ghost" onClick={back}>← {t.back}</button>}
                <button className="cf-btn" onClick={onLast ? finish : next}>
                  {onLast ? t.submit : t.next} →
                </button>
              </div>
            </div>
          </div>
        )}
      </main>
    </div>
  );
}

const vctoStyles = {
  frame: (w, h) => ({
    width: w, height: h, background: 'var(--ink-bg)', color: 'var(--text)',
    fontFamily: "'Geist', system-ui, sans-serif",
    display: 'flex', flexDirection: 'column', overflow: 'hidden', position: 'relative',
  }),
  header: {
    display: 'flex', justifyContent: 'space-between', alignItems: 'center',
    padding: '24px 56px', borderBottom: '1px solid var(--ink-line)',
    flexShrink: 0,
  },
  mark: {
    width: 36, height: 36, borderRadius: 8,
    background: 'var(--accent-2)', color: 'var(--accent-ink)',
    display: 'flex', alignItems: 'center', justifyContent: 'center',
    fontFamily: 'JetBrains Mono, monospace', fontWeight: 600, fontSize: 14,
  },
  main: { flex: 1, padding: '48px 56px', display: 'flex', alignItems: 'flex-start', justifyContent: 'center', overflowY: 'auto', minHeight: 0 },
  grid: { display: 'grid', gridTemplateColumns: '1.5fr 1fr', gap: 60, width: '100%', maxWidth: 1100, alignItems: 'center' },
  h1: { fontSize: 56, lineHeight: 1.05, fontWeight: 400, letterSpacing: '-0.02em' },
  h2: { fontSize: 38, lineHeight: 1.1, fontWeight: 400, letterSpacing: '-0.015em' },
  lead: { fontSize: 17, lineHeight: 1.55, color: 'var(--text-2)', marginTop: 16, maxWidth: 640 },
  aside: { borderLeft: '1px solid var(--ink-line)', paddingLeft: 36, display: 'flex', flexDirection: 'column' },
  code: {
    fontFamily: 'JetBrains Mono, monospace', fontSize: 13, lineHeight: 1.6,
    color: 'var(--text-2)', marginTop: 18, whiteSpace: 'pre',
    background: 'rgba(255,255,255,0.03)', padding: 18, borderRadius: 12,
    border: '1px solid var(--ink-line)',
  },
  stepGrid: { display: 'grid', gridTemplateColumns: '160px 1fr', gap: 56, width: '100%', maxWidth: 1100 },
  stepLeft: { display: 'flex', flexDirection: 'column', paddingTop: 8, minHeight: 280 },
  stepRight: { borderLeft: '1px solid var(--ink-line)', paddingLeft: 56 },
};

window.VariationCTO = VariationCTO;
window.makeCTOQuestions = makeCTOQuestions;
