// results.jsx — the editorial results page

const RadarChart = ({ categories, size = 320 }) => {
  const cx = size / 2, cy = size / 2;
  const r = size * 0.36;
  const n = categories.length;

  const point = (i, val) => {
    const angle = (i / n) * Math.PI * 2 - Math.PI / 2;
    const dist = (val / 10) * r;
    return [cx + Math.cos(angle) * dist, cy + Math.sin(angle) * dist];
  };

  const labelPoint = (i) => {
    const angle = (i / n) * Math.PI * 2 - Math.PI / 2;
    return [cx + Math.cos(angle) * (r + 24), cy + Math.sin(angle) * (r + 24)];
  };

  const polyA = categories.map((c, i) => point(i, c.a).join(',')).join(' ');
  const polyB = categories.map((c, i) => point(i, c.b).join(',')).join(' ');

  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`}>
      {/* Rings */}
      {[2, 4, 6, 8, 10].map(v => (
        <circle key={v} cx={cx} cy={cy} r={(v/10) * r} fill="none" stroke="var(--rule-soft)" strokeWidth="1" />
      ))}
      {/* Spokes */}
      {categories.map((c, i) => {
        const [x, y] = point(i, 10);
        return <line key={i} x1={cx} y1={cy} x2={x} y2={y} stroke="var(--rule-soft)" strokeWidth="1" />;
      })}
      {/* B polygon */}
      <polygon points={polyB} fill="var(--b)" fillOpacity="0.12" stroke="var(--b)" strokeWidth="1.5" />
      {/* A polygon */}
      <polygon points={polyA} fill="var(--a)" fillOpacity="0.12" stroke="var(--a)" strokeWidth="1.5" />
      {/* Dots */}
      {categories.map((c, i) => {
        const [ax, ay] = point(i, c.a);
        const [bx, by] = point(i, c.b);
        return (
          <g key={i}>
            <circle cx={ax} cy={ay} r="3" fill="var(--a)" />
            <circle cx={bx} cy={by} r="3" fill="var(--b)" />
          </g>
        );
      })}
      {/* Labels */}
      {categories.map((c, i) => {
        const [lx, ly] = labelPoint(i);
        const angle = (i / n) * Math.PI * 2 - Math.PI / 2;
        const anchor = Math.abs(Math.cos(angle)) < 0.3 ? 'middle' : Math.cos(angle) > 0 ? 'start' : 'end';
        return (
          <text key={i} x={lx} y={ly} textAnchor={anchor} dominantBaseline="middle"
            fontFamily="var(--mono)" fontSize="10" fill="var(--ink-2)" style={{ textTransform: 'uppercase', letterSpacing: '0.1em' }}>
            {c.label}
          </text>
        );
      })}
    </svg>
  );
};

const Results = ({ data, answers, onNew, onCompareAgain, onSave: onSaveProp, savedCount, issueNumber = 1, year = new Date().getFullYear(), layout = 'editorial' }) => {
  const issueLabel = String(issueNumber).padStart(3, '0');
  const [hoverCat, setHoverCat] = React.useState(null);
  const [savedTip, setSavedTip] = React.useState(false);

  const aWins = data.categories.filter(c => c.winner === 'a').length;
  const bWins = data.categories.filter(c => c.winner === 'b').length;

  const onSave = () => {
    if (onSaveProp) onSaveProp();
    setSavedTip(true);
    setTimeout(() => setSavedTip(false), 2000);
  };

  return (
    <div style={{ minHeight: '100vh' }}>
      <TopBar onHome={onNew} showNew={true} onNew={onNew} />

      {/* === MASTHEAD === */}
      <div className="container" style={{ padding: '40px 32px 24px' }}>
        <div className="fade-in masthead-row" style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16 }}>
          <div className="eyebrow">
            Vol. {year} · No. {issueLabel} · {data.context.purpose} · {data.context.priorities.slice(0, 3).join(' · ')}
          </div>
          <div style={{ display: 'flex', gap: 8, alignItems: 'center', position: 'relative' }}>
            <button className="chip" onClick={onSave}>★ Save{savedCount > 0 ? <span className="mono" style={{ marginLeft: 6, color: 'var(--accent)', fontSize: 11 }}>({savedCount})</span> : null}</button>
            <button className="chip" onClick={() => {
              if (navigator.share) {
                navigator.share({ title: `${data.a.name} vs ${data.b.name}`, text: data.verdict.headline, url: window.location.href }).catch(() => {});
              } else if (navigator.clipboard) {
                navigator.clipboard.writeText(`${data.a.name} vs ${data.b.name} — ${data.verdict.headline}`);
                setSavedTip('link');
                setTimeout(() => setSavedTip(false), 2000);
              }
            }}>↗ Share</button>
            <button className="chip" onClick={() => window.print()}>⤓ Export</button>
            {savedTip && (
              <div className="fade-in" style={{ position: 'absolute', top: 'calc(100% + 8px)', right: 0, background: 'var(--ink)', color: 'var(--paper)', padding: '6px 10px', borderRadius: 6, fontSize: 12, whiteSpace: 'nowrap', zIndex: 50 }}>
                {savedTip === 'link' ? 'Link copied' : 'Saved to your collection'}
              </div>
            )}
          </div>
        </div>
        <hr className="hr" />
      </div>

      {/* === HERO TITLE === */}
      <div className="container" style={{ padding: '32px' }}>
        <div className="fade-up" style={{ display: 'grid', gridTemplateColumns: '1fr', gap: 0, textAlign: 'center', position: 'relative' }}>
          <div className="g-title">
            <div style={{ textAlign: 'right' }}>
              <div className="serif" style={{ fontSize: 'clamp(56px, 9vw, 130px)', lineHeight: 0.95, letterSpacing: '-0.02em', color: 'var(--a)' }}>
                {data.a.name}
              </div>
              <div className="mono" style={{ fontSize: 12, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.15em', marginTop: 8 }}>
                {data.a.sub}
              </div>
            </div>
            <div className="serif italic" style={{ fontSize: 'clamp(28px, 5vw, 64px)', color: 'var(--ink-3)' }}>
              vs.
            </div>
            <div style={{ textAlign: 'left' }}>
              <div className="serif" style={{ fontSize: 'clamp(56px, 9vw, 130px)', lineHeight: 0.95, letterSpacing: '-0.02em', color: 'var(--b)' }}>
                {data.b.name}
              </div>
              <div className="mono" style={{ fontSize: 12, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.15em', marginTop: 8 }}>
                {data.b.sub}
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* === VERDICT === */}
      <div className="container" style={{ padding: '40px 32px' }}>
        <div className="fade-up delay-1 verdict-pad" style={{ background: 'var(--paper-2)', borderRadius: 'var(--r-xl)', padding: '48px', position: 'relative', overflow: 'hidden' }}>
          <div className="eyebrow" style={{ marginBottom: 24 }}>
            ◆ The Verdict · {data.context.audience}
          </div>
          <div className="g-verdict">
            <div>
              <h2 className="h1" style={{ margin: '0 0 24px' }}>
                <Typewriter text={data.verdict.headline} speed={12} startDelay={400} />
              </h2>
              <p className="lede" style={{ margin: 0, fontStyle: 'normal', fontSize: 19 }}>
                {data.verdict.body}
                {data.sources[0] && <SourceCite n={1} host={data.sources[0].host} title={data.sources[0].title} date={data.sources[0].date} />}
                {data.sources[2] && <SourceCite n={3} host={data.sources[2].host} title={data.sources[2].title} date={data.sources[2].date} />}
              </p>

              <div className="mono" style={{ marginTop: 16, fontSize: 12, color: 'var(--ink-3)', lineHeight: 1.5 }}>
                Synthesised by an LLM from the cited sources — verify before big decisions.
              </div>

              <div style={{ marginTop: 32, display: 'flex', gap: 16, alignItems: 'center', flexWrap: 'wrap' }}>
                <div>
                  <div className="mono" style={{ fontSize: 11, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.15em', marginBottom: 4 }}>Confidence</div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <div style={{ width: 100, height: 4, background: 'var(--rule)', borderRadius: 2, overflow: 'hidden' }}>
                      <div style={{ width: `${data.verdict.confidence * 100}%`, height: '100%', background: 'var(--accent)', animation: 'fadeIn 1s' }} />
                    </div>
                    <span className="mono" style={{ fontSize: 13, color: 'var(--ink-2)' }}>{Math.round(data.verdict.confidence * 100)}%</span>
                  </div>
                </div>
                <div className="stats-divider" style={{ height: 32, width: 1, background: 'var(--rule)' }} />
                <div>
                  <div className="mono" style={{ fontSize: 11, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.15em', marginBottom: 4 }}>Sources</div>
                  <div className="mono" style={{ fontSize: 14 }}>{data.sources.length} · cross-checked</div>
                </div>
                <div className="stats-divider" style={{ height: 32, width: 1, background: 'var(--rule)' }} />
                <div>
                  <div className="mono" style={{ fontSize: 11, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.15em', marginBottom: 4 }}>Categories</div>
                  <div className="mono" style={{ fontSize: 14 }}>
                    <span style={{ color: 'var(--a)' }}>{aWins}</span> · <span style={{ color: 'var(--b)' }}>{bWins}</span>
                  </div>
                </div>
              </div>
            </div>

            {/* Big score circles */}
            <div className="scores-row" style={{ display: 'flex', gap: 24, justifyContent: 'center' }}>
              {[
                { side: 'a', score: data.a.score, name: data.a.name, color: 'var(--a)' },
                { side: 'b', score: data.b.score, name: data.b.name, color: 'var(--b)' },
              ].map(s => (
                <div key={s.side} style={{ textAlign: 'center' }}>
                  <div style={{
                    width: 110, height: 110, borderRadius: '50%',
                    border: `2px solid ${s.color}`,
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    flexDirection: 'column',
                    background: `color-mix(in oklch, ${s.color} 8%, var(--paper))`,
                  }}>
                    <div className="serif" style={{ fontSize: 44, color: s.color, lineHeight: 1 }}>
                      <CountUp to={s.score} duration={1400} />
                    </div>
                    <div className="mono" style={{ fontSize: 10, color: 'var(--ink-3)', marginTop: 2 }}>/ 100</div>
                  </div>
                  <div className="serif" style={{ fontSize: 16, marginTop: 10, color: s.color }}>{s.name}</div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>

      {/* === CATEGORIES === */}
      <div className="container" style={{ padding: '32px' }}>
        <div className="fade-up delay-2 g-cats">
          <div>
            <div className="eyebrow" style={{ marginBottom: 16 }}>◆ By the numbers</div>
            <h2 className="h2" style={{ margin: '0 0 24px' }}>Where each one wins.</h2>
            <p style={{ color: 'var(--ink-2)', marginBottom: 24, fontSize: 15 }}>
              Hover any category to see the reasoning. Scores are out of 10, weighted against your priorities.
            </p>

            <div>
              {data.categories.map((c, i) => {
                const max = Math.max(c.a, c.b);
                const aPct = (c.a / 10) * 100;
                const bPct = (c.b / 10) * 100;
                const isHover = hoverCat === c.id;
                return (
                  <div key={c.id}
                    onMouseEnter={() => setHoverCat(c.id)}
                    onMouseLeave={() => setHoverCat(null)}
                    style={{
                      borderTop: '1px solid var(--rule-soft)',
                      borderBottom: i === data.categories.length - 1 ? '1px solid var(--rule-soft)' : 'none',
                      padding: '14px 0',
                      cursor: 'pointer',
                    }}>
                    <div className="g-catrow">
                      <div style={{ fontSize: 14, fontWeight: 500 }}>{c.label}</div>
                      {/* A bar — right-aligned */}
                      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'flex-end', gap: 10 }}>
                        <span className="mono" style={{ fontSize: 12, color: c.winner === 'a' ? 'var(--a)' : 'var(--ink-3)', fontWeight: c.winner === 'a' ? 600 : 400 }}>{c.a.toFixed(1)}</span>
                        <div style={{ flex: 1, height: 6, background: 'var(--rule-soft)', borderRadius: 3, overflow: 'hidden', display: 'flex', justifyContent: 'flex-end' }}>
                          <div style={{ width: `${aPct}%`, height: '100%', background: 'var(--a)', opacity: c.winner === 'a' ? 1 : 0.5, transition: 'all 0.3s' }} />
                        </div>
                      </div>
                      {/* B bar — left-aligned */}
                      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                        <div style={{ flex: 1, height: 6, background: 'var(--rule-soft)', borderRadius: 3, overflow: 'hidden' }}>
                          <div style={{ width: `${bPct}%`, height: '100%', background: 'var(--b)', opacity: c.winner === 'b' ? 1 : 0.5, transition: 'all 0.3s' }} />
                        </div>
                        <span className="mono" style={{ fontSize: 12, color: c.winner === 'b' ? 'var(--b)' : 'var(--ink-3)', fontWeight: c.winner === 'b' ? 600 : 400 }}>{c.b.toFixed(1)}</span>
                      </div>
                      <div className="serif italic" style={{ fontSize: 14, color: c.winner === 'a' ? 'var(--a)' : 'var(--b)', textAlign: 'center' }}>
                        {c.winner === 'a' ? '◀' : '▶'}
                      </div>
                    </div>
                    {isHover && (
                      <div className="fade-in" style={{ marginTop: 10, paddingLeft: 0, fontSize: 13, color: 'var(--ink-2)', fontStyle: 'italic', fontFamily: 'var(--serif)' }}>
                        {c.note}
                        <SourceCite n={(i % data.sources.length) + 1} host={data.sources[i % data.sources.length].host} title={data.sources[i % data.sources.length].title} date={data.sources[i % data.sources.length].date} />
                      </div>
                    )}
                  </div>
                );
              })}
            </div>
          </div>

          {/* Radar */}
          <div className="radar-sticky" style={{ position: 'sticky', top: 80, textAlign: 'center' }}>
            <div className="eyebrow" style={{ marginBottom: 16 }}>◆ Shape</div>
            <div style={{ background: 'var(--paper)', border: '1px solid var(--rule-soft)', borderRadius: 'var(--r-xl)', padding: 20 }}>
              <RadarChart categories={data.categories} size={300} />
              <div style={{ display: 'flex', justifyContent: 'center', gap: 24, marginTop: 12, fontSize: 13 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                  <span className="dot-a" /><span style={{ color: 'var(--a)' }}>{data.a.name}</span>
                </div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                  <span className="dot-b" /><span style={{ color: 'var(--b)' }}>{data.b.name}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* === PROS & CONS === */}
      <div className="container" style={{ padding: '60px 32px' }}>
        <div className="eyebrow" style={{ marginBottom: 16 }}>◆ Pros & cons</div>
        <h2 className="h2" style={{ margin: '0 0 32px' }}>The honest list.</h2>
        <div className="g-2col">
          {[
            { side: 'a', d: data.a, color: 'var(--a)', soft: 'var(--a-soft)' },
            { side: 'b', d: data.b, color: 'var(--b)', soft: 'var(--b-soft)' },
          ].map(side => (
            <div key={side.side} style={{ background: side.soft, borderRadius: 'var(--r-xl)', padding: 32 }}>
              <div className="serif" style={{ fontSize: 32, color: side.color, marginBottom: 24 }}>{side.d.name}</div>
              <div className="mono" style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: '0.15em', color: side.color, marginBottom: 12 }}>For</div>
              <ul style={{ margin: 0, padding: 0, listStyle: 'none' }}>
                {data.pros[side.side].map((p, i) => (
                  <li key={i} style={{ padding: '10px 0', borderBottom: '1px solid color-mix(in oklch, var(--ink) 8%, transparent)', display: 'flex', gap: 12 }}>
                    <span className="mono" style={{ fontSize: 11, color: side.color, paddingTop: 4, flexShrink: 0 }}>+</span>
                    <span style={{ fontSize: 14, lineHeight: 1.5 }}>{p}</span>
                  </li>
                ))}
              </ul>
              <div className="mono" style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: '0.15em', color: 'var(--ink-3)', marginTop: 24, marginBottom: 12 }}>Against</div>
              <ul style={{ margin: 0, padding: 0, listStyle: 'none' }}>
                {data.cons[side.side].map((p, i) => (
                  <li key={i} style={{ padding: '10px 0', borderBottom: i === data.cons[side.side].length - 1 ? 'none' : '1px solid color-mix(in oklch, var(--ink) 8%, transparent)', display: 'flex', gap: 12 }}>
                    <span className="mono" style={{ fontSize: 11, color: 'var(--ink-3)', paddingTop: 4, flexShrink: 0 }}>−</span>
                    <span style={{ fontSize: 14, lineHeight: 1.5, color: 'var(--ink-2)' }}>{p}</span>
                  </li>
                ))}
              </ul>
            </div>
          ))}
        </div>
      </div>

      {/* === SPECS TABLE === */}
      <div className="container" style={{ padding: '60px 32px' }}>
        <div className="eyebrow" style={{ marginBottom: 16 }}>◆ Specifications</div>
        <h2 className="h2" style={{ margin: '0 0 32px' }}>Side by side.</h2>
        <div style={{ borderTop: '2px solid var(--ink)' }}>
          {data.specs.map((spec, i) => (
            <div key={i} className="g-specs-row" style={{
              padding: '14px 0',
              borderBottom: '1px solid var(--rule-soft)',
            }}>
              <div className="mono" style={{ fontSize: 12, textTransform: 'uppercase', letterSpacing: '0.1em', color: 'var(--ink-3)' }}>{spec.label}</div>
              <div className="serif spec-side" data-name={data.a.name} style={{ fontSize: 18, color: 'var(--a)' }}>{spec.a}</div>
              <div className="serif spec-side" data-name={data.b.name} style={{ fontSize: 18, color: 'var(--b)' }}>{spec.b}</div>
            </div>
          ))}
        </div>
      </div>

      {/* === QUOTES === */}
      <div className="container" style={{ padding: '60px 32px' }}>
        <div className="eyebrow" style={{ marginBottom: 16 }}>◆ What people are saying</div>
        <h2 className="h2" style={{ margin: '0 0 32px' }}>From the field.</h2>
        <div className="g-quotes">
          {data.quotes.map((q, i) => {
            const color = q.side === 'a' ? 'var(--a)' : 'var(--b)';
            return (
              <div key={i} style={{ padding: 28, borderLeft: `2px solid ${color}`, background: 'var(--paper-2)' }}>
                <div className="serif italic" style={{ fontSize: 22, lineHeight: 1.35, marginBottom: 16 }}>
                  "{q.text}"
                </div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12, color: 'var(--ink-3)' }}>
                  <span className="mono" style={{ textTransform: 'uppercase', letterSpacing: '0.1em' }}>{q.source}</span>
                  <span>·</span>
                  <span>{q.date}</span>
                </div>
              </div>
            );
          })}
        </div>
      </div>

      {/* === RECOMMENDATION === */}
      <div className="container" style={{ padding: '60px 32px' }}>
        <div className="rec-pad" style={{ background: 'var(--ink)', color: 'var(--paper)', borderRadius: 'var(--r-xl)', padding: 56, position: 'relative', overflow: 'hidden' }}>
          <div className="eyebrow" style={{ marginBottom: 16, color: 'var(--accent-2)' }}>◆ Best for you</div>
          <div className="g-rec">
            <div>
              <div className="serif" style={{ fontSize: 18, color: 'var(--ink-4)', marginBottom: 8 }}>
                For a {data.recommendation.pickFor}, pick:
              </div>
              <div className="serif" style={{ fontSize: 'clamp(56px, 7vw, 92px)', lineHeight: 1, color: 'var(--accent-2)', letterSpacing: '-0.02em' }}>
                {data.recommendation.pick}.
              </div>
            </div>
            <div>
              <p className="serif" style={{ fontSize: 22, lineHeight: 1.4, fontStyle: 'italic', margin: '0 0 20px' }}>
                {data.recommendation.why}
              </p>
              <p style={{ fontSize: 14, color: 'var(--ink-4)', margin: 0 }}>
                {data.recommendation.altPick}
              </p>
              <div style={{ display: 'flex', gap: 12, marginTop: 28, flexWrap: 'wrap' }}>
                <button className="btn" onClick={onSave} style={{ background: 'var(--accent-2)', borderColor: 'var(--accent-2)', color: 'var(--ink)' }}>
                  ★ Save this verdict
                </button>
                <button className="btn ghost" onClick={onCompareAgain} style={{ borderColor: 'var(--ink-4)', color: 'var(--paper)' }}>
                  Compare again, differently
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* === SOURCES === */}
      <div className="container" style={{ padding: '40px 32px 80px' }}>
        <div className="eyebrow" style={{ marginBottom: 16 }}>◆ Sources · {data.sources.length}</div>
        <h2 className="h3" style={{ margin: '0 0 20px' }}>Where this came from.</h2>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: 0, borderTop: '1px solid var(--rule-soft)' }}>
          {data.sources.map((s, i) => (
            <div key={i} style={{ padding: '14px 16px 14px 0', borderBottom: '1px solid var(--rule-soft)', display: 'flex', gap: 12 }}>
              <div className="mono" style={{ fontSize: 11, color: 'var(--accent)', flexShrink: 0, paddingTop: 3 }}>{String(i + 1).padStart(2, '0')}</div>
              <div style={{ minWidth: 0 }}>
                <div className="serif italic" style={{ fontSize: 16, marginBottom: 2 }}>{s.title}</div>
                <div className="mono" style={{ fontSize: 11, color: 'var(--ink-3)' }}>
                  {s.host} · {s.date}
                </div>
              </div>
            </div>
          ))}
        </div>
        <div style={{ textAlign: 'center', marginTop: 60, paddingTop: 40, borderTop: '1px solid var(--rule)' }}>
          <Logo size={28} />
          <div className="mono" style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 14, letterSpacing: '0.1em', textTransform: 'uppercase' }}>
            Compare anything, thoughtfully.
          </div>
        </div>
      </div>

    </div>
  );
};

window.Results = Results;
window.RadarChart = RadarChart;
