/* Quote, Problem (incidents + questions + Claude session), Numbers, HowItWorks, Decision-Support (VS Code + traces) */

function Reveal({ children, className = '', stagger = false, as: Tag = 'div', ...props }) {
  const ref = React.useRef(null);
  const [inView, setInView] = React.useState(false);
  React.useEffect(() => {
    if (!ref.current) return;
    const io = new IntersectionObserver(
      (entries) => entries.forEach((e) => { if (e.isIntersecting) { setInView(true); io.disconnect(); } }),
      { threshold: 0.18, rootMargin: '0px 0px -8% 0px' }
    );
    io.observe(ref.current);
    return () => io.disconnect();
  }, []);
  const cls = `${stagger ? 'reveal-stagger' : 'reveal'} ${inView ? 'in' : ''} ${className}`.trim();
  return <Tag ref={ref} className={cls} {...props}>{children}</Tag>;
}

/* Painful Quote — replaces "lookbook" placeholder with a real-feeling engineer review ─ */
function PainQuote() {
  return (
    <section className="quote-band">
      <div className="nh-container">
        <Reveal>
          <figure className="painquote">
            <blockquote className="painquote__body">
              "He passed every round. Then I spent two sprints rolling back the auth migration he shipped. Three prod incidents, one of them at 1&nbsp;a.m. on a Saturday. When I asked what he'd been thinking, he opened Claude and read me the explanation. I rewrote it in a day. He's not a bad engineer. He just <em>doesn't know what he doesn't know</em> when the model sounds confident."
            </blockquote>
            <figcaption className="painquote__attr">
              <span className="painquote__name">Senior eng lead</span>
              <span className="painquote__role">post-mortem retro · 40-person platform team · early 2026</span>
            </figcaption>
          </figure>
        </Reveal>
      </div>
    </section>
  );
}

/* Painful Unanswered Questions ─────────────────────────────── */
function UnansweredQuestions() {
  const qs = [
    {
      n: "01",
      q: "Can they tell when the AI is confidently wrong before the customer does?",
    },
    {
      n: "02",
      q: "Are they in charge of the system, or is the system in charge of them?",
    },
    { n: "03", q: "Would they save you from the prod bug, or be the cause of it?" },
    { n: "04", q: "Do they catch the silent regression before review does?" },
  ];
  return (
    <Reveal className="unanswered" stagger>
      {qs.map((x) => (
        <div key={x.n} className="unanswered__item">
          <span className="unanswered__num">{x.n}</span>
          <p className="unanswered__q">{x.q}</p>
        </div>
      ))}
    </Reveal>
  );
}

/* Claude Code Session Mockup — animated, with floating alert pills ─── */
const CC_LINES = [
  { kind: 'thought', text: 'Thought' },
  { kind: 'read',    text: 'Read', sub: '(config/pool.ts)' },
  { kind: 'update',  text: 'Update', sub: '(config/pool.ts)', diff: 'Added 4 lines, removed 2 lines' },
  { kind: 'msg',     text: 'Tuned retry backoff and pool size. Smoother now.' },
  { kind: 'prompt',  text: 'timing out again' },
  { kind: 'thought', text: 'Thought' },
  { kind: 'read',    text: 'Read', sub: '(services/gateway.ts)' },
  { kind: 'update',  text: 'Update', sub: '(services/gateway.ts)', diff: 'Added 6 lines, removed 1 line' },
  { kind: 'msg',     text: 'Raised timeout and added a circuit breaker.' },
];


/* Problem ─────────────────────────────────────────────────── */
function Problem() {
  return (
    <section className="section" id="problem">
      <div className="nh-container">
        <Reveal className="section__head">
          <p className="eyebrow">The problem</p>
          <h2 className="display-xl" style={{ maxWidth: '24ch', textWrap: 'balance' }}>
            Your hiring loop can't answer the questions that actually predict who breaks prod.
          </h2>
        </Reveal>

        <div className="problem__grid problem__grid--stack">
          <UnansweredQuestions />

          <Reveal style={{ marginTop: 32 }}>
            <p className="eyebrow">The cost of getting it wrong</p>
          </Reveal>

          <Reveal stagger>
            <ol className="incidents">
              <li className="incident">
                <p className="incident__tag">July 2025 · Replit</p>
                <p className="incident__head">AI agent deleted a live production database during a code freeze.</p>
              </li>
              <li className="incident">
                <p className="incident__tag">Feb 2024 · Air Canada</p>
                <p className="incident__head">Customer-service chatbot invented a refund policy. A tribunal made the airline pay it.</p>
              </li>
              <li className="incident">
                <p className="incident__tag">Apr 2025 · Cursor</p>
                <p className="incident__head">Support bot invented a fake one-device policy and told paying customers they were violating it.</p>
              </li>
            </ol>
          </Reveal>
        </div>
      </div>
    </section>
  );
}

/* Numbers ────────────────────────────────────────────────── */
function useCountUp(target, durationMs = 1200) {
  const ref = React.useRef(null);
  const [val, setVal] = React.useState(0);
  React.useEffect(() => {
    if (!ref.current) return;
    let started = false;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting && !started) {
          started = true;
          const t0 = performance.now();
          const tick = (now) => {
            const p = Math.min(1, (now - t0) / durationMs);
            const eased = 1 - Math.pow(1 - p, 3);
            setVal(target * eased);
            if (p < 1) requestAnimationFrame(tick);
          };
          requestAnimationFrame(tick);
          io.disconnect();
        }
      });
    }, { threshold: 0.4 });
    io.observe(ref.current);
    return () => io.disconnect();
  }, [target, durationMs]);
  return [ref, val];
}

function Stat({ value, suffix = '', decimals = 0, prefix = '', label, source }) {
  const [ref, v] = useCountUp(value);
  return (
    <div ref={ref}>
      <p className="stat">{prefix}{v.toFixed(decimals)}{suffix}</p>
      <p className="stat-desc">{label}</p>
      <p className="mono-s stat-src">{source}</p>
    </div>
  );
}

function Numbers() {
  return (
    <section className="section section--alt" id="numbers">
      <div className="nh-container">
        <Reveal className="section__head" style={{ marginBottom: 56 }}>
          <p className="eyebrow">Why now</p>
          <h2 className="display-xl">The cost of a mishire is no longer abstract.</h2>
          <p className="body-l" style={{ maxWidth: '54ch', marginTop: 16 }}>
            Three numbers. Each one a reason your hiring loop produces high-confidence wrong predictions.
          </p>
        </Reveal>
        <Reveal className="numbers__inner">
          <Stat
            value={6.3}
            decimals={1}
            suffix="M"
            label={<>Amazon orders lost in the <strong>March 2026 outage</strong>, traced to an AI-assisted code change deployed without proper review.</>}
            source="Public reporting · March 2026"
          />
          <Stat
            value={1.7}
            decimals={1}
            suffix="×"
            label="bug rate of AI-generated code vs human-written code."
            source="CodeRabbit · 2025"
          />
          <Stat
            value={23.5}
            decimals={1}
            suffix="%"
            label="rise in production incidents per pull request, year-over-year."
            source="Apiiro · 2025"
          />
        </Reveal>
      </div>
    </section>
  );
}

/* How it works ────────────────────────────────────────────── */
function HowItWorks() {
  const steps = [
    { n: '01', t: 'You provide the JD',     d: 'Stack, responsibilities. Our agent finds bug-fix that matches or bring your own.' },
    { n: '02', t: 'Senior eng signs off',   d: 'Your senior engineer approves before any candidate sees it.' },
    { n: '03', t: 'Candidate takes the assessment',      d: 'On their own machine. Their IDE, their browser, their AI tools. One consent at session start.' },
    { n: '04', t: 'We capture trajectory',  d: 'Every discrete action: prompts, edits, commands, runs, reverts, searches.' },
    { n: '05', t: 'You read the scorecard', d: '5-minute read. Per-area bands. You make the call.' },
  ];

  return (
    <section className="section" id="how">
      <div className="nh-container">
        <Reveal className="section__head">
          <p className="eyebrow">How it works</p>
          <h2 className="display-xl">Five steps. You send a link. We capture how they think.</h2>
        </Reveal>
        <Reveal className="how__steps" stagger>
          {steps.map((s) => (
            <div key={s.n} className="how__step">
              <span className="how__step__num">{s.n}</span>
              <h4>{s.t}</h4>
              <p>{s.d}</p>
            </div>
          ))}
        </Reveal>
      </div>
    </section>
  );
}

/* Radar — original 11-cluster data from uploads/radar-chart.tsx, ported 1:1.
   Only delta is colour clarity: tick labels go ink-900 instead of muted grey,
   candidate stroke a touch thicker, fill a touch fuller. Same shape, same data,
   same "Agent" / "Developer" series. */
const CLUSTER_NAMES = {
  navigation_exploration: 'Navigation & Exploration',
  hypothesis_testing:     'Hypothesis Formation',
  mental_model:           'Mental Model Construction',
  process_discipline:     'Process Discipline',
  tool_metacognition:     'Tool Mastery & Metacognition',
  fix_design:             'Fix Design & Planning',
  implementation_quality: 'Implementation Quality',
  testing_verification:   'Testing & Verification',
  safety_robustness:      'Safety & Robustness',
  code_review:            'Code Review & Self-Review',
  process_metacognition:  'Process & Metacognition',
};

function valueToLabel(value) {
  if (value === 1.0)  return 'Strong';
  if (value === 0.75) return 'Competent';
  if (value === 0.5)  return 'Developing';
  if (value === 0.25) return 'Weak';
  if (value === 0.0)  return 'Absent';
  return 'N/A';
}

const DECISION_RADAR_DATA = [
  { cluster: 'navigation_exploration',  agent: 1.0,  developer: 0.75 },
  { cluster: 'hypothesis_testing',      agent: 1.0,  developer: 0.75 },
  { cluster: 'mental_model',            agent: 1.0,  developer: 0.5  },
  { cluster: 'process_discipline',      agent: 0.75, developer: 0.75 },
  { cluster: 'tool_metacognition',      agent: 1.0,  developer: 0.5  },
  { cluster: 'fix_design',              agent: 0.75, developer: 0.75 },
  { cluster: 'implementation_quality',  agent: 0.75, developer: 0.75 },
  { cluster: 'testing_verification',    agent: 0.5,  developer: 0.5  },
  { cluster: 'safety_robustness',       agent: 0.5,  developer: 0.5  },
  { cluster: 'code_review',             agent: 0.75, developer: 0.5  },
  { cluster: 'process_metacognition',   agent: 0.75, developer: 0.5  },
];

function RadarTick({ payload, x, y, cx, cy }) {
  if (!payload || x === undefined || y === undefined) return null;
  const fullName = CLUSTER_NAMES[payload.value] ?? payload.value;
  const words    = fullName.split(/\s+/);
  const mid      = Math.ceil(words.length / 2);
  const lines    = [words.slice(0, mid).join(' '), words.slice(mid).join(' ')].filter(Boolean);
  const isRight  = x > (cx ?? 0) + 5;
  const isLeft   = x < (cx ?? 0) - 5;
  const anchor   = isRight ? 'start' : isLeft ? 'end' : 'middle';
  const dx       = isRight ? 4 : isLeft ? -4 : 0;
  const lineH    = 12;
  const startDy  = -(lines.length * lineH) / 2 + lineH / 2;
  return (
    <g>
      {lines.map((line, i) => (
        <text
          key={i}
          x={x + dx}
          y={y + startDy + i * lineH}
          textAnchor={anchor}
          fontSize={11}
          fill="#0E1116"
          fontWeight={500}
          style={{ fontFamily: 'Inter, sans-serif', letterSpacing: '-0.005em' }}
        >
          {line}
        </text>
      ))}
    </g>
  );
}

function DecisionRadar() {
  const R = window.Recharts;
  if (!R) return <div className="radar-loading">Loading evidence chart…</div>;
  const { RadarChart, PolarGrid, PolarAngleAxis, PolarRadiusAxis, Radar, ResponsiveContainer, Legend, Tooltip } = R;
  return (
    <ResponsiveContainer width="100%" height={440}>
      <RadarChart data={DECISION_RADAR_DATA} cx="50%" cy="50%" outerRadius="62%">
        <PolarGrid stroke="#B8BEC8" strokeOpacity={0.6} />
        <PolarAngleAxis dataKey="cluster" tick={(p) => <RadarTick {...p} />} />
        <PolarRadiusAxis angle={90} domain={[0, 1]} tick={{ fontSize: 9, fill: '#5A6270' }} tickCount={4} axisLine={false} />
        <Radar name="Developer Profile" dataKey="developer" stroke="#2A2F38" fill="#2A2F38" fillOpacity={0.10} strokeWidth={1.5} />
        <Radar name="Agent Profile"     dataKey="agent"     stroke="#FF6A00" fill="#FF6A00" fillOpacity={0.22} strokeWidth={2.25} />
        <Legend
          wrapperStyle={{
            fontSize: 12,
            paddingTop: 24,
            fontFamily: 'JetBrains Mono, monospace',
            letterSpacing: '0.04em',
            color: '#0E1116',
          }}
        />
        <Tooltip
          contentStyle={{
            fontSize: 12,
            borderRadius: 8,
            border: '1px solid #D8D5CD',
            background: 'rgba(251,249,244,0.96)',
            fontFamily: 'Inter, sans-serif',
          }}
          formatter={(value, name) => [valueToLabel(Number(value)), String(name ?? '')]}
          labelFormatter={(label) => CLUSTER_NAMES[String(label)] ?? String(label)}
        />
      </RadarChart>
    </ResponsiveContainer>
  );
}

function DecisionSupport() {
  return (
    <section className="section section--alt" id="decision">
      <div className="nh-container">
        <div className="decision-grid">
          <Reveal className="decision-copy">
            <p className="eyebrow">What you get</p>
            <h2 className="display-xl decision-copy__h">
              A detailed 5-minute read scorecard.
            </h2>
            <p className="body-l decision-copy__lead">
              The scorecard gives you per-area bands and an events trace of the evidence behind each one.
            </p>
          </Reveal>

          <Reveal className="decision-chart">
            <DecisionRadar />
          </Reveal>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, {
  Reveal, PainQuote, UnansweredQuestions,
  Problem, Numbers, HowItWorks, DecisionSupport, DecisionRadar,
});
