/* cst-artifact.jsx — shared pieces for every tool's "session → artifact" payoff:
   the analyzing overlay, the strategist-run hook (graph + AI + dramatic beat),
   the radar chart, and the end-of-tool CTA (book a session; paywall kept for future).
   Exported to window. */

const { useState: _auS, useRef: _auR } = React;
const _AC = window.CST;
const { FONT: _aF, TEXT: _aT, HAZE: _aH, HAZE_DIM: _aHD, HAIR: _aHR, INK: _aI } = _AC;

// PAYWALL is plumbed but off — flip to true to surface the paid-report flow.
const PAYWALL = false;
const REPORT_PRICE = '[price]';

// drives: seed graph → bloom discovery nodes → cycle status lines → fetch
// artifact in parallel → reveal after a minimum dramatic beat.
function useStrategistRun() {
  const [analyzing, setAnalyzing] = _auS(false);
  const [statusIdx, setStatusIdx] = _auS(0);
  const [count, setCount] = _auS(0);
  const timers = _auR([]);

  const start = ({ sim, lines, nodes, build, onReady, minBeat = 3200 }) => {
    setAnalyzing(true); setStatusIdx(0); setCount(0);
    timers.current.forEach(clearTimeout); timers.current = [];
    if (sim) { sim.seedDomain('YOU'); }

    (nodes || []).slice(0, 6).forEach((label, i) => {
      timers.current.push(setTimeout(() => {
        if (sim) sim.addAgent(label, (i + 1) % 3);
        setCount((c) => c + 1);
      }, 500 + i * 280));
    });
    (lines || []).forEach((_, i) => {
      timers.current.push(setTimeout(() => setStatusIdx(i), 450 + i * 520));
    });
    timers.current.push(setTimeout(() => sim && sim.run(() => {}, () => {}), 1500));

    const started = Date.now();
    const reveal = (artifact) => {
      const wait = Math.max(0, minBeat - (Date.now() - started));
      timers.current.push(setTimeout(() => {
        setAnalyzing(false);
        if (sim) sim.setMode('celebrate');
        onReady(artifact);
      }, wait));
    };
    Promise.resolve().then(build).then(reveal).catch(() => reveal(null));
  };

  const cancel = () => { timers.current.forEach(clearTimeout); timers.current = []; setAnalyzing(false); };
  return { analyzing, statusIdx, count, start, cancel };
}

const _PRO_TIPS = [
  'Pro tip: the score is a starting point, not a verdict.',
  'Pro tip: share your result card to get a second opinion.',
  'Pro tip: try the same idea with a different focus angle.',
  'Pro tip: run SWOT after Validate to stress-test your edge.',
  'Pro tip: the 20% raise scenario is usually closer than you think.',
  'Pro tip: your weakest dimension is your biggest lever.',
  'Pro tip: revisit in a week \u2014 your read changes as you learn.',
  'Pro tip: the best founders re-run this after every pivot.',
  'Fun fact: the average decision takes 2.4 seconds to pressure-test.',
  'Fun fact: "price it" users raise prices 23% more often.',
  'Remember: a bad decision made fast beats a good one made never.',
  'Remember: you already know the answer. This just confirms it.',
];

function AnalyzeOverlay({ lines, idx, accent, count, countNoun = 'signals read' }) {
  const [tipIdx] = React.useState(() => Math.floor(Math.random() * _PRO_TIPS.length));
  const showTip = count > 2;
  return (
    <div style={{ position: 'absolute', inset: 0, zIndex: 8, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', pointerEvents: 'none', padding: 24 }}>
      <div style={{ fontFamily: _aF, fontSize: 11, letterSpacing: 3, color: accent, marginBottom: 14 }}>● WORKING ON IT</div>
      <div style={{ fontFamily: _aF, fontWeight: 700, fontSize: 19, color: _aT, textAlign: 'center', minHeight: 26, textShadow: `0 0 22px ${accent}55` }}>
        {lines[idx]}
      </div>
      <div style={{ fontFamily: _aF, fontSize: 11, color: _aH, marginTop: 10 }}>{count} {countNoun}</div>
      {showTip && <div style={{ fontFamily: _aF, fontSize: 11, color: _aH, marginTop: 22, opacity: 0.7, textAlign: 'center', maxWidth: 280, lineHeight: 1.5, animation: 'cstFadeIn .6s ease' }}>{_PRO_TIPS[tipIdx]}</div>}
    </div>);
}

// radar chart — how the subject scores across factors
function RadarChart({ factors, breakdown, accent, onPick }) {
  const data = factors.map((f) => ({ key: f.key, label: f.label, value: (breakdown && breakdown[f.key] != null) ? breakdown[f.key] : 50 }));
  const N = data.length, R = 70, cx = 130, cy = 92;
  const ang = (i) => (-Math.PI / 2) + i * (2 * Math.PI / N);
  const pt = (i, r) => [cx + Math.cos(ang(i)) * r, cy + Math.sin(ang(i)) * r];
  const ring = (f) => data.map((_, i) => pt(i, R * f).join(',')).join(' ');
  const valPts = data.map((d, i) => pt(i, R * Math.max(0.08, d.value / 100)).join(',')).join(' ');
  const clickable = typeof onPick === 'function';
  return (
    <svg width="260" height="184" viewBox="0 0 260 184">
      {[0.34, 0.67, 1].map((f, k) => <polygon key={k} points={ring(f)} fill="none" stroke="rgba(236,237,241,0.10)" strokeWidth="1" />)}
      {data.map((_, i) => { const [x, y] = pt(i, R); return <line key={i} x1={cx} y1={cy} x2={x} y2={y} stroke="rgba(236,237,241,0.08)" strokeWidth="1" />; })}
      <polygon points={valPts} fill={accent + '2e'} stroke={accent} strokeWidth="2" strokeLinejoin="round" style={{ filter: `drop-shadow(0 0 6px ${accent})` }} />
      {data.map((d, i) => {
        const [x, y] = pt(i, R * Math.max(0.08, d.value / 100));
        return (
          <g key={i}>
            {clickable && <circle cx={x} cy={y} r="6.5" fill="none" stroke={accent} strokeWidth="1.2" opacity="0.5" />}
            <circle cx={x} cy={y} r="3" fill={accent} />
          </g>);
      })}
      {data.map((d, i) => {
        const [x, y] = pt(i, R + 16);
        const anchor = Math.abs(x - cx) < 6 ? 'middle' : (x > cx ? 'start' : 'end');
        return (
          <text key={'t' + i} x={x} y={y + 3} textAnchor={anchor} fontFamily="'Bricolage Grotesque', ui-sans-serif, system-ui, sans-serif" fontSize="9.5" letterSpacing="0.5" fill="rgba(236,237,241,0.72)">{d.label}
            <tspan x={x} dy="11" fontSize="8.5" fill={accent}>{d.value}</tspan>
          </text>);
      })}
      {/* generous tap targets over each point + label */}
      {clickable && data.map((d, i) => {
        const [vx, vy] = pt(i, R * Math.max(0.08, d.value / 100));
        const [lx, ly] = pt(i, R + 14);
        return (
          <g key={'h' + i} style={{ cursor: 'pointer' }} onClick={() => onPick(d)}>
            <circle cx={vx} cy={vy} r="15" fill="transparent" />
            <circle cx={lx} cy={ly} r="20" fill="transparent" />
          </g>);
      })}
    </svg>);
}

// the standard end-of-tool CTA. Share is the prominent (viral) action; Book is
// the business CTA; paywall is plumbed for future use.
function ArtifactCTA({ accent, onShare, onBook, onRestart, restartLabel = 'Run another', booked,
                       paywall = PAYWALL, unlocked, onUnlock, onDownload, tool, shareLabel = 'Share result' }) {
  if (paywall && !unlocked) {
    return (
      <div style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>
        <CardWatermark tool={tool} />
        <div style={{ fontFamily: _aF, fontSize: 11, letterSpacing: 0.3, color: _aH, textAlign: 'center' }}>
          Full written report to keep & share — <span style={{ color: accent, fontWeight: 600 }}>{REPORT_PRICE}</span>
        </div>
        <PrimaryBtn accent={accent} onClick={onUnlock}>Unlock full report · {REPORT_PRICE}</PrimaryBtn>
        <div style={{ display: 'flex', gap: 9 }}>
          {onShare && <ShareButton onShare={onShare} accent={accent} label={shareLabel} />}
          <button onClick={onBook} style={ghostInline()}>Talk to CS Tech</button>
        </div>
      </div>);
  }
  if (booked) {
    return (
      <div style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>
        <div style={{ fontFamily: _aF, fontSize: 12.5, color: accent, fontWeight: 700, letterSpacing: 0.3, textAlign: 'center' }}>✓ We’ll be in touch</div>
        <p style={{ margin: 0, fontFamily: _aF, fontSize: 12, color: _aH, lineHeight: 1.45, textAlign: 'center' }}>
          A CS Tech strategist will reach out to turn this into a plan you can act on.
        </p>
        <div style={{ display: 'flex', gap: 9 }}>
          {onShare && <ShareButton onShare={onShare} accent={accent} label={shareLabel} />}
          <button onClick={onRestart} style={ghostInline()}>{restartLabel}</button>
        </div>
      </div>);
  }
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>
      <CardWatermark tool={tool} />
      {onShare && <PrimaryBtn accent={accent} onClick={onShare}>{shareLabel} ↗</PrimaryBtn>}
      <div style={{ display: 'flex', gap: 9 }}>
        <button onClick={onBook} style={ghostInline()}>Book a session</button>
        {(paywall && unlocked) && (
          <button onClick={onDownload} style={ghostInline()}>Download ↓</button>
        )}
        <button onClick={onRestart} style={ghostInline()}>{restartLabel}</button>
      </div>
    </div>);
}
function ghostInline() {
  return { flex: 1, cursor: 'pointer', padding: '12px', borderRadius: 11, fontFamily: _aF, fontWeight: 600, fontSize: 12.5, color: _aH, background: 'transparent', border: `1px solid ${_aHR}` };
}

Object.assign(window, { useStrategistRun, AnalyzeOverlay, RadarChart, ArtifactCTA, CST_PAYWALL: PAYWALL });
