// Landing, Auth Modal, Onboarding, Science screens.

const inputStyle = {
  width: '100%', padding: '10px 12px',
  border: '1px solid var(--k-line)', borderRadius: 8,
  fontSize: 14, fontFamily: 'var(--k-sans)',
  background: 'var(--k-surface)', color: 'var(--k-ink)',
  outline: 'none', boxSizing: 'border-box',
};

// ── Landing ───────────────────────────────────────────────────────────
function LandingScreen({ onEnter, onAuth, isAuthed }) {
  const isMobile = window.useIsMobile ? window.useIsMobile() : false;
  const handleAuth = () => {
    if (onAuth) onAuth();
  };

  return (
    <div style={{
      minHeight: '100vh',
      background: 'radial-gradient(ellipse 120% 50% at 50% 0%, rgba(255,255,255,0.65) 0%, transparent 60%), linear-gradient(to bottom, #f5f4f2 0%, #dedad4 100%)',
      overflowY: 'auto',
    }} className="k-scroll">

      {/* ── Top nav ─────────────────────────────────────────── */}
      <div style={{
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        padding: isMobile ? '14px 20px' : '20px 48px', borderBottom: '1px solid var(--k-line)',
        background: 'rgba(245,244,242,0.7)', backdropFilter: 'blur(8px)',
      }}>
        <div />
        <div />
      </div>

      {/* ── Hero ────────────────────────────────────────────── */}
      <section style={{ padding: isMobile ? '48px 20px 48px' : '96px 48px 72px', maxWidth: 1160, margin: '0 auto' }}>
        <h1 className="k-serif" style={{
          fontSize: 'clamp(32px, 4vw, 52px)', lineHeight: 1.02,
          margin: 0, letterSpacing: '-0.025em', maxWidth: 900,
        }}>
          One Assessment. Deterministic Scoring.
          <br />
          <span style={{ color: 'var(--k-ink-3)' }}>Three outputs that change how you work, lead your team, and use AI.</span>
        </h1>

        <p style={{ fontSize: isMobile ? 16 : 19, lineHeight: 1.6, color: 'var(--k-ink-2)', maxWidth: 680, marginTop: 28, margin: '28px 0 0' }}>
          Kalibr measures how you think, decide, and collaborate, then produces three outputs: a personal psychometric map, a team cohesion graph, and an AI constitution.
        </p>

        <div style={{ marginTop: 36 }}>
          {isAuthed
            ? <button className="k-btn k-btn--primary k-btn--lg" onClick={() => onEnter('assessment')}>Begin 25 minute assessment →</button>
            : <button className="k-btn k-btn--primary k-btn--lg" onClick={() => window.kalibrOpenAuthModal && window.kalibrOpenAuthModal('signup')}>Sign up to begin →</button>
          }
        </div>

        {/* ── Three output cards ───────────────────────────── */}
        <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr 1fr', gap: 20, marginTop: isMobile ? 40 : 72 }}>
          {[
            { tag: 'Output 1', title: 'Personal Psychometric Map', accent: 'var(--k-indigo)',
              icon: (
                <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round">
                  <circle cx="12" cy="8" r="4"/>
                  <path d="M4 20c0-4 3.6-7 8-7s8 3 8 7"/>
                </svg>
              ),
              points: [
              '10 dimensions covering how you think, lead, take risk, and recover',
              'Deterministic scoring — fixed algorithm, no AI interpretation drift',
              'Blind spot report tailored to your specific score pattern',
              'Understand your operating profile before a high-stakes moment does it for you',
            ]},
            { tag: 'Output 2', title: 'Team Cohesion Map', accent: 'var(--k-sage)',
              icon: (
                <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round">
                  <circle cx="5" cy="12" r="2.5"/>
                  <circle cx="19" cy="6" r="2.5"/>
                  <circle cx="19" cy="18" r="2.5"/>
                  <line x1="7.4" y1="11" x2="16.6" y2="7"/>
                  <line x1="7.4" y1="13" x2="16.6" y2="17"/>
                  <line x1="19" y1="8.5" x2="19" y2="15.5"/>
                </svg>
              ),
              points: [
              'Relational graph of every profiled person in your organisation',
              'Pairwise compatibility scores across all 10 dimensions for every pair',
              'Shows where relationships are structurally strong and where friction is likely',
              'Surfaces communication, leadership, and feedback mismatches before they become problems',
            ]},
            { tag: 'Output 3', title: 'AI Constitution', accent: 'var(--k-accent)',
              icon: (
                <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round">
                  <rect x="4" y="3" width="16" height="18" rx="2"/>
                  <line x1="8" y1="8" x2="16" y2="8"/>
                  <line x1="8" y1="12" x2="16" y2="12"/>
                  <line x1="8" y1="16" x2="13" y2="16"/>
                </svg>
              ),
              points: [
              'Personalised system prompt derived from your psychometric profile',
              'Targets your specific blind spots — not generic AI behaviour',
              'Structures output to match how you actually process information',
              'Stress-tests your ideas rather than blindly reinforcing them',
              'Works with Claude, ChatGPT, or any LLM',
            ]},
          ].map(c => (
            <div key={c.title} className="k-card" style={{ padding: 28, position: 'relative', overflow: 'hidden', background: 'rgba(255,255,255,0.75)' }}>
              <div style={{ position: 'absolute', top: 0, left: 0, right: 0, height: 3, background: c.accent }} />
              <div style={{ color: c.accent, marginBottom: 14, opacity: 0.85 }}>{c.icon}</div>
              <div className="k-label" style={{ color: c.accent, marginBottom: 8 }}>{c.tag}</div>
              <h3 className="k-serif" style={{ fontSize: 22, margin: '0 0 14px', letterSpacing: '-0.02em', lineHeight: 1.2 }}>{c.title}</h3>
              <ul style={{ margin: 0, padding: '0 0 0 18px', display: 'flex', flexDirection: 'column', gap: 5, fontSize: 13.5, color: 'var(--k-ink-2)', lineHeight: 1.55 }}>
                {c.points.map(pt => <li key={pt}>{pt}</li>)}
              </ul>
            </div>
          ))}
        </div>

        {/* ── Two-layer architecture note ──────────────────── */}
        <div style={{ marginTop: 32, display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr', borderRadius: 14, overflow: 'hidden', border: '1px solid var(--k-line)' }}>
          <div style={{ padding: '20px 26px', background: 'rgba(255,255,255,0.6)' }}>
            <div className="k-label" style={{ marginBottom: 8 }}>Layer 1 · Scoring</div>
            <p style={{ fontSize: 13.5, color: 'var(--k-ink-2)', lineHeight: 1.6, margin: 0 }}>
              A fixed algorithm processes your 212 responses and produces 10 scores. Deterministic — identical inputs always produce identical outputs. No AI is involved at this stage. Your scores cannot be hallucinated.
            </p>
          </div>
          <div style={{ padding: '20px 26px', background: 'var(--k-accent-soft)', borderLeft: '1px solid oklch(0.88 0.06 250)' }}>
            <div className="k-label" style={{ marginBottom: 8, color: 'var(--k-accent-ink)' }}>Layer 2 · Synthesis</div>
            <p style={{ fontSize: 13.5, color: 'var(--k-accent-ink)', lineHeight: 1.6, margin: 0 }}>
              AI turns those fixed scores into prose — your profile narrative, blind spot analysis, and AI constitution. The scores don't change. The writing is generated from them. Two separate layers, on purpose.
            </p>
          </div>
        </div>

        <div style={{ marginTop: isMobile ? 32 : 64, padding: '24px 28px', background: 'rgba(255,255,255,0.5)', borderRadius: 16, border: '1px solid var(--k-line)', display: 'grid', gridTemplateColumns: isMobile ? 'repeat(2, 1fr)' : 'repeat(4, 1fr)', gap: 24 }}>
          {[['212','items across 17 scales'],['10','proprietary dimensions'],['8','supported crosswalk instruments'],['±5','confidence band, always surfaced']].map(([n,l]) => (
            <div key={l}>
              <div className="k-serif" style={{ fontSize: 34, letterSpacing: '-0.02em' }}>{n}</div>
              <div style={{ fontSize: 12.5, color: 'var(--k-ink-3)', marginTop: 2 }}>{l}</div>
            </div>
          ))}
        </div>

        <div style={{ marginTop: 40, fontSize: 12.5, color: 'var(--k-ink-4)', borderTop: '1px solid var(--k-line)', paddingTop: 20 }}>
          Kalibr measures working-style preferences and interpersonal dynamics. It is not a hiring decision tool, and does not measure intelligence, skill, education, or training.
        </div>
      </section>
    </div>
  );
}

// ── Onboarding ────────────────────────────────────────────────────────
function OnboardingScreen({ onEnter }) {
  const isMobile = window.useIsMobile ? window.useIsMobile() : false;
  const [step, setStep]       = React.useState(0);
  const [consents, setConsents] = React.useState({ data: false, pair: false, ai: false });

  const steps = [
    { title: 'Welcome, let’s set expectations', body: 'This takes about 25 minutes. Answer honestly — the engine runs quality checks for central tendency and acquiescence. There are no right answers.', icon: '◌' },
    { title: 'What you’ll get', body: 'A personal profile across 10 dimensions, a blind-spot report tailored to your score pattern, and a personal AI constitution you can load into Claude, ChatGPT, or Gemini.', icon: '◎' },
    { title: 'Consent & data', body: 'Your psychometric data is encrypted at rest. We never surface admin-only (SD3) scores. You can delete your profile at any time.', icon: '▽' },
  ];

  const s = steps[step]; const last = step === steps.length - 1;

  return (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: '100vh', padding: 32 }}>
      <div className="k-card" style={{ width: isMobile ? '100%' : 560, padding: isMobile ? '28px 20px' : '44px 40px 36px' }}>
        <div style={{ display: 'flex', gap: 6, marginBottom: 28 }}>
          {steps.map((_,i) => <div key={i} style={{ flex: 1, height: 3, borderRadius: 2, background: i <= step ? 'var(--k-accent)' : 'var(--k-line)' }} />)}
        </div>
        <div style={{ fontSize: 44, color: 'var(--k-accent)', marginBottom: 18 }}>{s.icon}</div>
        <h2 className="k-serif" style={{ fontSize: 30, margin: 0, letterSpacing: '-0.02em' }}>{s.title}</h2>
        <p style={{ fontSize: 15.5, lineHeight: 1.6, color: 'var(--k-ink-2)', marginTop: 12 }}>{s.body}</p>
        {last && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginTop: 16, padding: 14, borderRadius: 12, background: 'var(--k-surface-sunk)' }}>
            {[['data','Store my responses for scoring and report generation.'],['pair','Let me invite a partner to unlock the pairwise reports.'],['ai','Generate a personal AI constitution and let me copy it off-platform.']].map(([k,v]) => (
              <label key={k} style={{ display: 'flex', gap: 10, alignItems: 'flex-start', fontSize: 13.5, color: 'var(--k-ink-2)', cursor: 'pointer' }}>
                <input type="checkbox" checked={consents[k]} onChange={e => setConsents(c => ({...c,[k]:e.target.checked}))} style={{ marginTop: 3, accentColor: 'var(--k-accent)' }} />
                {v}
              </label>
            ))}
          </div>
        )}
        <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 28 }}>
          <button className="k-btn k-btn--ghost" onClick={() => step > 0 ? setStep(step-1) : onEnter('landing')}>
            {step === 0 ? 'Back to overview' : 'Back'}
          </button>
          {last
            ? <button className="k-btn k-btn--primary" disabled={!(consents.data && consents.ai)} onClick={() => onEnter('assessment')} style={{ opacity: consents.data && consents.ai ? 1 : 0.4 }}>Begin assessment →</button>
            : <button className="k-btn k-btn--primary" onClick={() => setStep(step+1)}>Continue</button>
          }
        </div>
      </div>
    </div>
  );
}

// ── Science ───────────────────────────────────────────────────────────
function ScienceScreen({ onEnter }) {
  const isMobile = window.useIsMobile ? window.useIsMobile() : false;
  const foundation = [
    {
      label: 'Personality at the facet level',
      body: 'The personality backbone covers the full breadth of the Big Five at the facet level, not the broad domain level. This matters because facets predict specific behaviours that broad domains cannot distinguish. Two people can have identical Conscientiousness scores and completely different working styles depending on which facets drive that score.',
    },
    {
      label: 'Perseverance and consistency as separate subscales',
      body: 'Perseverance and consistency of interest are tracked as separate subscales because they behave differently across profiles and across time horizons. A person who never gives up and a person who never loses interest are not the same person, and conflating them produces misleading outputs.',
    },
    {
      label: 'Resilience as coping capacity',
      body: 'Resilience is measured as self-reported coping capacity — specifically, how quickly someone believes they recover from setbacks. The distinction matters for team dynamics: someone who appears resilient may be sustaining output at a hidden personal cost.',
    },
    {
      label: 'Risk signal layer',
      body: 'A risk signal layer is included and scored by the algorithm. It is not shown to participants. It informs the operator view only, consistent with the instrument\'s intended use in professional settings.',
    },
  ];

  const findings = [
    {
      n: '01',
      title: 'Personality predicts team performance more reliably than individual performance',
      body: 'The team-level personality effect is substantially stronger than the individual-level effect. A meta-analysis of 168 effect sizes found that team composition on agreeableness and conscientiousness predicted team performance at effect sizes two to three times larger than the equivalent individual-level relationships. Personality matters more, not less, when people have to work together.',
      stats: [
        'ρ = 0.34 — team mean agreeableness → team performance (Bell, 2007)',
        'ρ = 0.51 — team elevation in agreeableness → team performance (Peeters, 2006)',
        'ρ = 0.11 — individual agreeableness → individual performance',
      ],
    },
    {
      n: '02',
      title: 'One person can undermine an entire team',
      body: 'Agreeableness is the exception to the team-mean rule. Its effect on team performance is equally strong whether measured as the team average or the team minimum. One person significantly below the group on this dimension disrupts social cohesion for everyone regardless of everyone else\'s scores. This is why Kalibr uses a minimum-threshold function for specific dimensions rather than treating all dimensions as simple averages.',
      stats: [],
    },
    {
      n: '03',
      title: 'Variability within a team predicts performance independently of the average level',
      body: 'A team where everyone scores similarly on conscientiousness outperforms a team with the same average but high internal variation — even when that variation includes some very high scorers. Peeters et al. (2006) found variability in conscientiousness and agreeableness to be independent negative predictors of team performance. This is the research foundation for Kalibr\'s pairwise approach: knowing individual scores is not enough. The distance between two people\'s scores matters.',
      stats: [
        'ρ = −0.24 — conscientiousness variability → team performance',
        'ρ = −0.12 — agreeableness variability → team performance',
      ],
    },
    {
      n: '04',
      title: 'Similarity and complementarity predict compatibility through different mechanisms',
      body: 'Profile similarity consistently predicts relationship satisfaction on affiliation-type traits. Complementarity predicts it on dominance-type traits. The implication: a single distance metric applied uniformly across all personality dimensions will produce wrong answers. Some pairs work best when scores are close. Others work best when scores diverge. Kalibr uses different matching functions for different dimensions based on which mechanism the research supports for that construct.',
      stats: [],
    },
    {
      n: '05',
      title: 'Conscientiousness has the broadest validity of any Big Five trait across occupational groups',
      body: 'Of all personality traits, conscientiousness is the only one showing consistent predictive validity for job performance across nearly all occupational groups studied — in a meta-analysis of 117 validity studies covering nearly 24,000 subjects. This finding has replicated across six decades of research and forms the backbone of Kalibr\'s execution-related dimensions.',
      stats: [
        '117 validity studies across nearly all occupational groups studied',
        'N ≈ 24,000 subjects in the meta-analysis',
      ],
    },
  ];

  const honesty = [
    {
      icon: '✓',
      label: 'Strongly Supported',
      subject: 'The instruments and the team-level findings',
      body: 'The use of validated personality measurement to predict team outcomes is one of the most replicated findings in organisational psychology. The instruments Kalibr draws on are independently validated with published reliability and validity data.',
      bg: 'var(--k-surface)', ink: 'var(--k-ink)', border: 'var(--k-line-strong)',
    },
    {
      icon: '~',
      label: 'Theoretically Defensible',
      subject: 'The proprietary dimension composites and pairwise scoring engine',
      body: 'The specific way Kalibr combines instrument outputs into dimensions, and the specific way it computes compatibility between two profiles, is theoretically motivated by the research above. The weights, formulas, and matching functions are defensible by design logic and the literature — but they have not been independently validated against outcome data. They are claims, not findings.',
      bg: 'var(--k-bg-2)', ink: 'var(--k-ink-2)', border: 'var(--k-line-strong)',
    },
    {
      icon: '◌',
      label: 'Active Hypothesis',
      subject: 'Predictive validity before two people have worked together',
      body: 'No published study has shown that a pairwise psychometric score computed before two people have worked together predicts the quality of their working relationship at six months. This is the core hypothesis Kalibr is testing prospectively through its pilot programme. We have construct validity. We do not yet have criterion validity. We are honest about that distinction.',
      bg: 'var(--k-bg-3)', ink: 'var(--k-ink-3)', border: 'var(--k-line)',
    },
  ];

  return (
    <div style={{ maxWidth: 1080, margin: '0 auto', padding: isMobile ? '24px 20px 60px' : '40px 48px 100px' }}>

      {/* Hero */}
      <div style={{ marginBottom: 56, paddingBottom: 40, borderBottom: '1px solid var(--k-line)' }}>
        <div className="k-label" style={{ marginBottom: 14 }}>The Science</div>
        <h1 className="k-serif" style={{ fontSize: isMobile ? 34 : 52, margin: 0, letterSpacing: '-0.025em', lineHeight: 1.06 }}>
          Built on decades of<br />peer-reviewed research.
        </h1>
        <p style={{ fontSize: 17, color: 'var(--k-ink-2)', maxWidth: 680, marginTop: 18, lineHeight: 1.65 }}>
          Every dimension in Kalibr traces to a published psychometric instrument. We do not invent new constructs. We assemble validated foundations into a proprietary measurement and scoring engine, then add an interpretation layer built specifically for working relationships and team dynamics.
        </p>
        <div style={{ marginTop: 20, padding: '12px 18px', background: 'var(--k-bg-2)', borderRadius: 10, fontSize: 13, color: 'var(--k-ink-3)', lineHeight: 1.6, maxWidth: 680, borderLeft: '3px solid var(--k-line-strong)' }}>
          We distinguish between what is empirically established, what is theoretically defensible, and what is a hypothesis we are actively testing. Most products in this space do not make that distinction. We think it matters.
        </div>
      </div>

      {/* Section 1 */}
      <div style={{ marginBottom: 56 }}>
        <div className="k-label" style={{ marginBottom: 6 }}>Section 1</div>
        <h2 className="k-serif" style={{ fontSize: 36, margin: '0 0 10px', letterSpacing: '-0.02em' }}>The Foundation</h2>
        <p style={{ fontSize: 15, color: 'var(--k-ink-2)', marginBottom: 28, maxWidth: 640, lineHeight: 1.6 }}>
          Kalibr's assessment draws on four independently validated instruments, administered as a single unified battery. The specific instruments, their weighting, combination methodology, and the proprietary dimension composites built on top of them are confidential. What we can say:
        </p>
        <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr', gap: 16 }}>
          {foundation.map((f, i) => (
            <div key={i} className="k-card" style={{ padding: '24px 26px' }}>
              <div className="k-serif" style={{ fontSize: 17, letterSpacing: '-0.01em', marginBottom: 10 }}>{f.label}</div>
              <p style={{ fontSize: 13.5, color: 'var(--k-ink-2)', lineHeight: 1.6, margin: 0 }}>{f.body}</p>
            </div>
          ))}
        </div>
      </div>

      {/* Section 2 */}
      <div style={{ marginBottom: 56 }}>
        <div className="k-label" style={{ marginBottom: 6 }}>Section 2</div>
        <h2 className="k-serif" style={{ fontSize: 36, margin: '0 0 28px', letterSpacing: '-0.02em' }}>What the Research Says</h2>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
          {findings.map(f => (
            <div key={f.n} className="k-card" style={{ padding: '24px 28px' }}>
              <div style={{ display: 'grid', gridTemplateColumns: '56px 1fr', gap: 20, alignItems: 'flex-start' }}>
                <div className="k-mono" style={{ fontSize: 26, fontWeight: 600, color: 'var(--k-line-strong)', paddingTop: 4 }}>{f.n}</div>
                <div>
                  <div className="k-serif" style={{ fontSize: 20, letterSpacing: '-0.01em', marginBottom: 10 }}>{f.title}</div>
                  <p style={{ fontSize: 14, lineHeight: 1.65, color: 'var(--k-ink-2)', margin: 0, marginBottom: f.stats.length ? 14 : 0 }}>{f.body}</p>
                  {f.stats.length > 0 && (
                    <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                      {f.stats.map(s => (
                        <div key={s} className="k-mono" style={{ fontSize: 12, color: 'var(--k-ink-2)', background: 'var(--k-bg-2)', padding: '5px 10px', borderRadius: 6 }}>{s}</div>
                      ))}
                    </div>
                  )}
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Section 3 */}
      <div style={{ marginBottom: 56 }}>
        <div className="k-label" style={{ marginBottom: 6 }}>Section 3</div>
        <h2 className="k-serif" style={{ fontSize: 36, margin: '0 0 28px', letterSpacing: '-0.02em' }}>Scientific Honesty</h2>
        <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr 1fr', gap: 16, marginBottom: 24 }}>
          {honesty.map(h => (
            <div key={h.label} style={{ padding: 24, borderRadius: 16, background: h.bg, border: `1px solid ${h.border}` }}>
              <div style={{ fontSize: 28, marginBottom: 12 }}>{h.icon}</div>
              <div style={{ fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.08em', color: h.ink, marginBottom: 6 }}>{h.label}</div>
              <div style={{ fontSize: 15, fontWeight: 600, color: h.ink, marginBottom: 10, lineHeight: 1.3 }}>{h.subject}</div>
              <p style={{ fontSize: 13.5, lineHeight: 1.65, color: h.ink, margin: 0, opacity: 0.85 }}>{h.body}</p>
            </div>
          ))}
        </div>
        <div style={{ padding: '18px 22px', background: 'var(--k-bg-2)', borderRadius: 12, borderLeft: '3px solid var(--k-line-strong)', fontSize: 16, fontStyle: 'italic', color: 'var(--k-ink-2)', lineHeight: 1.65 }}>
          "The product is scientifically credible, built on the right literature, and uses validated instruments correctly. The pairwise compatibility algorithm is novel and unvalidated — which is exactly what the pilot is for."
        </div>
      </div>

      {/* Section 4 */}
      <div>
        <div className="k-label" style={{ marginBottom: 6 }}>Section 4</div>
        <h2 className="k-serif" style={{ fontSize: 36, margin: '0 0 16px', letterSpacing: '-0.02em' }}>References</h2>
        <div className="k-card" style={{ padding: '20px 24px', fontSize: 13.5, color: 'var(--k-ink-2)', lineHeight: 2 }}>
          <div>Barrick, M.R. & Mount, M.K. (1991). The Big Five personality dimensions and job performance. <em>Personnel Psychology, 44</em>, 1–26.</div>
          <div>Bell, S.T. (2007). Deep-level composition variables as predictors of team performance. <em>Journal of Applied Psychology, 92</em>(3), 595–615.</div>
          <div>Dryer, D.C. & Horowitz, L.M. (1997). When do opposites attract? <em>Journal of Personality and Social Psychology, 72</em>(3), 592–603.</div>
          <div>Duckworth, A.L. & Quinn, P.D. (2009). Development and validation of the Short Grit Scale. <em>Journal of Personality Assessment, 91</em>(2), 166–174.</div>
          <div>Felps, W., Mitchell, T.R. & Byington, E. (2006). How, when, and why bad apples spoil the barrel. <em>Research in Organizational Behavior, 27</em>, 175–222.</div>
          <div>Han, A., Krieger, F., Kim, S., Nixon, N. & Greiff, S. (2024). Revisiting the relationship between team members' personality and their team's performance: A meta-analysis. <em>Journal of Research in Personality.</em></div>
          <div>Jolić Marjanović, Z. et al. (2024). The Big Five and collaborative problem solving. <em>Personality and Social Psychology Bulletin.</em></div>
          <div>Peeters, M.A.G. et al. (2006). Personality and team performance: A meta-analysis. <em>European Journal of Personality, 20</em>, 377–396.</div>
          <div>Scherrer, P. et al. (2018). Similarity and positivity of personality profiles predict relationship satisfaction. <em>Frontiers in Psychology.</em></div>
          <div>Van Vianen, A.E.M. & De Dreu, C.K.W. (2001). Personality in teams. <em>European Journal of Work and Organizational Psychology, 10</em>(2).</div>
        </div>
        <div style={{ marginTop: 14, fontSize: 12, color: 'var(--k-ink-4)', lineHeight: 1.55 }}>
          Base assessment items IPIP public domain. Platform algorithms, dimension composites, pairwise scoring engine, and interpretation layer proprietary. © 2026 Kalibr, Aryan Shah. All rights reserved.
        </div>
      </div>
    </div>
  );
}

function PricingScreen({ onEnter }) {
  const isMobile = window.useIsMobile ? window.useIsMobile() : false;
  const FREE_ITEMS = [
    'Complete 212-item assessment',
    'Feedback Orientation score & narrative',
    'First blind spot identified',
    'Response quality check results',
  ];
  const LOCKED_ITEMS = [
    'Remaining 9 dimension scores',
    'Full dimension narratives',
    'Full blind spot analysis (up to 3)',
    'AI Constitution',
    'Downloadable report',
  ];
  const PAID_ITEMS = [
    'All 10 dimension scores + narratives',
    'Full blind spot analysis — up to 3 patterns',
    'Pattern synthesis across blind spots',
    'Context predictions across 4 environments',
    'Named strength + watch area',
    'Cross-dimensional pattern flags',
    'Grit, resilience & work ethic scores',
    'AI Constitution for Claude, ChatGPT, Gemini + other tools',
    'Downloadable HTML report',
  ];
  const DELIVERABLES = [
    {
      label: '10-Dimension Profile',
      icon: (
        <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
          <circle cx="12" cy="12" r="10"/><polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/>
        </svg>
      ),
      body: 'A scored map of how you think, decide, and operate. Fixed algorithm — deterministic, not AI. The same inputs always produce the same outputs.',
    },
    {
      label: 'Blind Spot Analysis',
      icon: (
        <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
          <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/><line x1="3" y1="3" x2="21" y2="21"/>
        </svg>
      ),
      body: 'Up to three structural patterns in your score profile that cost you trust, time, or accurate information — each with an observable working agreement.',
    },
    {
      label: 'AI Constitution',
      icon: (
        <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
          <rect x="2" y="3" width="20" height="14" rx="2"/><line x1="8" y1="21" x2="16" y2="21"/><line x1="12" y1="17" x2="12" y2="21"/>
        </svg>
      ),
      body: 'A personalised system prompt derived directly from your scores. Paste it into Claude, ChatGPT, Gemini, or other tools to recalibrate how AI responds to you.',
    },
  ];

  return (
    <div style={{ maxWidth: 960, margin: '0 auto', padding: isMobile ? '40px 20px 60px' : '64px 48px 96px' }}>

      {/* ── Hero ──────────────────────────────────────────────────── */}
      <div style={{ textAlign: 'center', marginBottom: 64 }}>
        <div className="k-label" style={{ marginBottom: 14 }}>Pricing</div>
        <h1 className="k-serif" style={{ fontSize: 52, margin: '0 0 16px', letterSpacing: '-0.03em', lineHeight: 1.1 }}>
          One assessment.<br />Permanent self-knowledge.
        </h1>
        <p style={{ fontSize: 17, color: 'var(--k-ink-2)', lineHeight: 1.6, maxWidth: 520, margin: '0 auto 32px' }}>
          A single payment unlocks your complete psychometric profile, blind spot report, and AI constitution. No subscription. No upsell. No expiry.
        </p>
        <div style={{ display: 'inline-flex', alignItems: 'baseline', gap: 10, marginBottom: 28 }}>
          <span className="k-serif" style={{ fontSize: 64, fontWeight: 500, letterSpacing: '-0.03em', lineHeight: 1 }}>$50</span>
          <span style={{ fontSize: 15, color: 'var(--k-ink-3)' }}>one-time · instant access</span>
        </div>
        <div>
          <button className="k-btn k-btn--primary" style={{ height: 48, fontSize: 16, minWidth: 220 }}
            onClick={() => onEnter('assessment')}>
            Take the assessment →
          </button>
        </div>
      </div>

      {/* ── Free vs Paid ──────────────────────────────────────────── */}
      <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr', gap: 20, marginBottom: isMobile ? 40 : 64 }}>

        {/* Free */}
        <div className="k-card" style={{ padding: '28px 32px' }}>
          <div className="k-label" style={{ marginBottom: 6 }}>Free</div>
          <div className="k-serif" style={{ fontSize: 24, letterSpacing: '-0.015em', marginBottom: 20 }}>
            Orientation
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginBottom: 24 }}>
            {FREE_ITEMS.map(item => (
              <div key={item} style={{ display: 'flex', gap: 10, alignItems: 'flex-start', fontSize: 13.5, color: 'var(--k-ink-2)' }}>
                <span style={{ color: 'var(--k-sage-ink)', fontWeight: 600, flexShrink: 0, marginTop: 1 }}>✓</span>
                {item}
              </div>
            ))}
            <div style={{ height: 1, background: 'var(--k-line)', margin: '4px 0' }} />
            {LOCKED_ITEMS.map(item => (
              <div key={item} style={{ display: 'flex', gap: 10, alignItems: 'flex-start', fontSize: 13.5, color: 'var(--k-ink-4)' }}>
                <span style={{ flexShrink: 0, marginTop: 1 }}>—</span>
                {item}
              </div>
            ))}
          </div>
          <button className="k-btn k-btn--ghost" style={{ width: '100%' }} onClick={() => onEnter('assessment')}>
            Start free
          </button>
        </div>

        {/* Paid */}
        <div className="k-card" style={{ padding: '28px 32px', background: 'var(--k-accent-soft)', border: '1px solid oklch(0.82 0.08 250)' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 6 }}>
            <div className="k-label" style={{ color: 'var(--k-accent-ink)' }}>Full report</div>
            <span className="k-chip" style={{ background: 'var(--k-accent)', color: '#fff', border: 'none', fontSize: 11 }}>$50 one-time</span>
          </div>
          <div className="k-serif" style={{ fontSize: 24, letterSpacing: '-0.015em', marginBottom: 20, color: 'var(--k-accent-ink)' }}>
            Everything, permanently
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginBottom: 24 }}>
            <div style={{ fontSize: 12, color: 'var(--k-accent-ink)', opacity: 0.7, marginBottom: 2 }}>Everything in free, plus:</div>
            {PAID_ITEMS.map(item => (
              <div key={item} style={{ display: 'flex', gap: 10, alignItems: 'flex-start', fontSize: 13.5, color: 'var(--k-accent-ink)' }}>
                <span style={{ fontWeight: 600, flexShrink: 0, marginTop: 1 }}>✓</span>
                {item}
              </div>
            ))}
          </div>
          <button className="k-btn k-btn--primary" style={{ width: '100%', height: 44 }} onClick={() => onEnter('assessment')}>
            Start assessment →
          </button>
        </div>
      </div>

      {/* ── Architecture note ────────────────────────────────────── */}
      <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr', borderRadius: 14, overflow: 'hidden', border: '1px solid var(--k-line)', marginBottom: isMobile ? 40 : 64 }}>
        <div style={{ padding: '20px 28px', background: 'var(--k-bg-2)' }}>
          <div className="k-label" style={{ marginBottom: 6 }}>Layer 1 · Scoring</div>
          <p style={{ fontSize: 13.5, color: 'var(--k-ink-2)', lineHeight: 1.6, margin: 0 }}>
            A fixed algorithm processes your responses and produces 10 scores. Deterministic — the same inputs always produce the same outputs. No AI, no interpretation drift. Your scores cannot be hallucinated.
          </p>
        </div>
        <div style={{ padding: '20px 28px', background: 'var(--k-accent-soft)', borderLeft: '1px solid oklch(0.88 0.06 250)' }}>
          <div className="k-label" style={{ marginBottom: 6, color: 'var(--k-accent-ink)' }}>Layer 2 · Synthesis — what you unlock</div>
          <p style={{ fontSize: 13.5, color: 'var(--k-accent-ink)', lineHeight: 1.6, margin: 0 }}>
            AI turns your fixed scores into readable prose — your profile narrative, blind spot analysis, and AI constitution. The scores are the input. The narrative is the output. That's what the $50 unlocks.
          </p>
        </div>
      </div>

      {/* ── Three deliverables ────────────────────────────────────── */}
      <div style={{ marginBottom: 64 }}>
        <div style={{ textAlign: 'center', marginBottom: 32 }}>
          <div className="k-label" style={{ marginBottom: 8 }}>What you receive</div>
          <h2 className="k-serif" style={{ fontSize: 34, margin: 0, letterSpacing: '-0.02em' }}>Three permanent artefacts</h2>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : 'repeat(3, 1fr)', gap: 20 }}>
          {DELIVERABLES.map(d => (
            <div key={d.label} className="k-card" style={{ padding: '28px 26px' }}>
              <div style={{ color: 'var(--k-accent)', marginBottom: 16 }}>{d.icon}</div>
              <div className="k-serif" style={{ fontSize: 20, letterSpacing: '-0.01em', marginBottom: 10 }}>{d.label}</div>
              <p style={{ fontSize: 13.5, color: 'var(--k-ink-2)', lineHeight: 1.6, margin: 0 }}>{d.body}</p>
            </div>
          ))}
        </div>
      </div>

      {/* ── Value anchor ──────────────────────────────────────────── */}
      <div className="k-card" style={{ padding: '36px 40px', background: 'var(--k-bg-2)', border: 'none', marginBottom: 64 }}>
        <div className="k-label" style={{ marginBottom: 14 }}>Why $50</div>
        <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : 'repeat(3, 1fr)', gap: isMobile ? 20 : 32 }}>
          {[
            { comparator: 'Coaching session', cost: '$200–400', note: '60 minutes · no document' },
            { comparator: 'Consultant report', cost: '$300–800', note: '2-week turnaround · generic framework' },
            { comparator: 'Kalibr', cost: '$50', note: '25 minutes · same-day · yours permanently', highlight: true },
          ].map(c => (
            <div key={c.comparator} style={{ borderLeft: '2px solid ' + (c.highlight ? 'var(--k-accent)' : 'var(--k-line)'), paddingLeft: 20 }}>
              <div style={{ fontSize: 12, color: c.highlight ? 'var(--k-accent-ink)' : 'var(--k-ink-4)', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 4 }}>
                {c.comparator}
              </div>
              <div className="k-serif" style={{ fontSize: 28, letterSpacing: '-0.02em', color: c.highlight ? 'var(--k-accent-ink)' : 'var(--k-ink)', marginBottom: 4 }}>
                {c.cost}
              </div>
              <div style={{ fontSize: 12.5, color: 'var(--k-ink-3)', lineHeight: 1.4 }}>{c.note}</div>
            </div>
          ))}
        </div>
      </div>

      {/* ── Bottom CTA ────────────────────────────────────────────── */}
      <div style={{ textAlign: 'center' }}>
        <p style={{ fontSize: 15, color: 'var(--k-ink-3)', marginBottom: 24, lineHeight: 1.6 }}>
          The assessment takes 20–25 minutes. Your scores are calculated immediately.<br />
          The full report generates in under a minute once you submit.
        </p>
        <button className="k-btn k-btn--primary" style={{ height: 48, fontSize: 16, minWidth: 220 }}
          onClick={() => onEnter('assessment')}>
          Take the assessment →
        </button>
      </div>

    </div>
  );
}

function SettingsScreen({ onEnter }) {
  const isMobile = window.useIsMobile ? window.useIsMobile() : false;
  const [user, setUser] = React.useState(() => {
    try { return JSON.parse(localStorage.getItem('kalibr.user') || '{}'); }
    catch(e) { return {}; }
  });
  const [form, setForm] = React.useState({
    firstName: user.firstName || '',
    lastName:  user.lastName  || '',
    org:       user.org       || '',
    role:      user.role      || '',
  });
  const [saving, setSaving]         = React.useState(false);
  const [deleting, setDeleting]     = React.useState(false);
  const [saved, setSaved]           = React.useState(false);
  const [error, setError]           = React.useState('');
  const [confirmDelete, setConfirmDelete] = React.useState(false);

  const handleSave = async () => {
    setSaving(true); setError(''); setSaved(false);
    try {
      const updates = { name: form.firstName + ' ' + form.lastName, org: form.org, role: form.role };
      const res = await fetch('/me', {
        method: 'PATCH',
        headers: window.kalibrAuth.getHeaders({ 'Content-Type': 'application/json' }),
        body: JSON.stringify(updates),
      });
      if (!res.ok) { setError('Could not save changes. Please try again.'); return; }
      const updated = { ...user, ...updates, firstName: form.firstName, lastName: form.lastName };
      localStorage.setItem('kalibr.user', JSON.stringify(updated));
      window.__kalibr_participant_name = updates.name || '';
      window.__kalibr_participant_role = updates.role || '';
      setUser(updated);
      setSaved(true);
      setTimeout(() => setSaved(false), 3000);
    } catch(e) { setError('Something went wrong.'); }
    finally { setSaving(false); }
  };

  const handleDelete = async () => {
    setDeleting(true); setError('');
    try {
      const res = await fetch('/me', {
        method: 'DELETE',
        headers: window.kalibrAuth.getHeaders(),
      });
      if (!res.ok) { setError('Could not delete account. Please try again.'); return; }
      localStorage.removeItem('kalibr.user');
      localStorage.removeItem('kalibr.session_token');
      window.kalibrAuth?.clearSession?.();
      localStorage.removeItem('kalibr.be.cards');
      window.location.reload();
    } catch(e) { setError('Something went wrong.'); }
    finally { setDeleting(false); }
  };

  const sInput = {
    width: '100%', padding: '10px 12px', border: '1px solid var(--k-line)',
    borderRadius: 8, fontSize: 14, fontFamily: 'var(--k-sans)',
    background: 'var(--k-surface)', color: 'var(--k-ink)',
    outline: 'none', boxSizing: 'border-box',
  };

  return (
    <div style={{ maxWidth: 640, margin: '0 auto', padding: isMobile ? '24px 20px 60px' : '40px 48px 80px' }}>
      <div className="k-label" style={{ marginBottom: 8 }}>Account</div>

      <div className="k-card" style={{ padding: '28px 32px', marginBottom: 20 }}>
        <div className="k-label" style={{ marginBottom: 20 }}>Profile information</div>
        <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr', gap: 16, marginBottom: 16 }}>
          <div>
            <div className="k-label" style={{ marginBottom: 6 }}>First name</div>
            <input value={form.firstName} onChange={e => setForm(f => ({ ...f, firstName: e.target.value }))} style={sInput} />
          </div>
          <div>
            <div className="k-label" style={{ marginBottom: 6 }}>Last name</div>
            <input value={form.lastName} onChange={e => setForm(f => ({ ...f, lastName: e.target.value }))} style={sInput} />
          </div>
        </div>
        <div style={{ marginBottom: 16 }}>
          <div className="k-label" style={{ marginBottom: 6 }}>Email</div>
          <input value={user.email || ''} disabled style={{ ...sInput, opacity: 0.5, cursor: 'not-allowed' }} />
          <div style={{ fontSize: 11.5, color: 'var(--k-ink-4)', marginTop: 4 }}>Email cannot be changed.</div>
        </div>
        <div style={{ marginBottom: 16 }}>
          <div className="k-label" style={{ marginBottom: 6 }}>Organisation</div>
          <input value={form.org} onChange={e => setForm(f => ({ ...f, org: e.target.value }))} style={sInput} />
        </div>
        <div style={{ marginBottom: 20 }}>
          <div className="k-label" style={{ marginBottom: 6 }}>Job title / role</div>
          <input value={form.role} onChange={e => setForm(f => ({ ...f, role: e.target.value }))} style={sInput} />
        </div>
        {error && <div style={{ fontSize: 13, color: 'var(--k-rose-ink)', marginBottom: 12 }}>{error}</div>}
        {saved && <div style={{ fontSize: 13, color: 'var(--k-sage-ink)', marginBottom: 12 }}>Changes saved.</div>}
        <button className="k-btn k-btn--primary" onClick={handleSave} disabled={saving} style={{ opacity: saving ? 0.6 : 1 }}>
          {saving ? 'Saving…' : 'Save changes'}
        </button>
      </div>

      <div className="k-card" style={{ padding: '28px 32px', border: '1px solid var(--k-rose)' }}>
        <div className="k-label" style={{ marginBottom: 8, color: 'var(--k-rose-ink)' }}>Danger zone</div>
        <div className="k-serif" style={{ fontSize: 20, letterSpacing: '-0.01em', marginBottom: 8 }}>Delete account</div>
        <p style={{ fontSize: 14, color: 'var(--k-ink-3)', lineHeight: 1.55, marginBottom: 20 }}>
          Permanently deletes your account, assessment responses, and all generated reports. This cannot be undone.
        </p>
        {!confirmDelete ? (
          <button onClick={() => setConfirmDelete(true)} style={{
            padding: '8px 18px', fontSize: 13, fontWeight: 500,
            border: '1px solid var(--k-rose)', borderRadius: 8,
            background: 'var(--k-rose-soft)', color: 'var(--k-rose-ink)',
            cursor: 'pointer', fontFamily: 'inherit',
          }}>Delete my account</button>
        ) : (
          <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
            <span style={{ fontSize: 13, color: 'var(--k-ink-2)' }}>Are you sure? This cannot be undone.</span>
            <button onClick={handleDelete} disabled={deleting} style={{
              padding: '8px 18px', fontSize: 13, fontWeight: 500, border: 'none', borderRadius: 8,
              background: 'var(--k-rose-ink)', color: '#fff',
              cursor: deleting ? 'default' : 'pointer', fontFamily: 'inherit', opacity: deleting ? 0.6 : 1,
            }}>{deleting ? 'Deleting…' : 'Yes, delete'}</button>
            <button className="k-btn k-btn--ghost" onClick={() => setConfirmDelete(false)} style={{ height: 34 }}>Cancel</button>
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { LandingScreen, OnboardingScreen, ScienceScreen, PricingScreen, SettingsScreen });
