// Security Posture Radar — interactive radar chart for Security page.
// User toggles "AI deployed" on/off; zones fill/darken based on whether Tech Cycle secured the AI pipeline.
const { useState: useStateSR } = React;

const RADAR_DIMS = [
  { key: 'dataPrivacy', label: 'Data privacy' },
  { key: 'modelVetting', label: 'AI model vetting' },
  { key: 'humanLoop', label: 'Human oversight' },
  { key: 'compliance', label: 'Compliance' },
  { key: 'auditTrail', label: 'Audit trails' },
  { key: 'accessControl', label: 'Access control' },
  { key: 'dataResidency', label: 'Data residency' },
  { key: 'kill', label: 'Kill switches' },
];

const SCORES = {
  // 0–1
  'ai-unsecured': { dataPrivacy: 0.3, modelVetting: 0.15, humanLoop: 0.2, compliance: 0.25, auditTrail: 0.2, accessControl: 0.4, dataResidency: 0.25, kill: 0.1 },
  'no-ai': { dataPrivacy: 0.55, modelVetting: 0.0, humanLoop: 0.6, compliance: 0.55, auditTrail: 0.45, accessControl: 0.6, dataResidency: 0.5, kill: 0.3 },
  'tc-ai': { dataPrivacy: 0.95, modelVetting: 0.92, humanLoop: 0.94, compliance: 0.95, auditTrail: 0.97, accessControl: 0.92, dataResidency: 0.9, kill: 0.93 },
};

window.PostureRadar = function PostureRadar() {
  const [mode, setMode] = useStateSR('no-ai');
  const [hint, setHint] = useStateSR(false);
  // Animated copy of the score object. The SVG renders off THIS state so
  // we can smoothly interpolate polygon vertex positions between modes
  // instead of snapping (polygon `points` doesn't CSS-transition in SVG).
  const [scores, setScores] = useStateSR(SCORES['no-ai']);
  const rootRef = React.useRef(null);
  const autoplayed = React.useRef(false);
  const animRef = React.useRef(null);

  // On mode change, tween each dimension's value toward the new target
  // over ~1400ms with ease-out. Cancels any in-flight tween.
  React.useEffect(() => {
    const target = SCORES[mode];
    const start = { ...scores };
    const duration = 1400;
    const t0 = performance.now();
    if (animRef.current) cancelAnimationFrame(animRef.current);
    const tick = (t) => {
      const raw = Math.min(1, (t - t0) / duration);
      const eased = 1 - Math.pow(1 - raw, 3); // easeOutCubic
      const next = {};
      Object.keys(target).forEach(k => {
        next[k] = start[k] + (target[k] - start[k]) * eased;
      });
      setScores(next);
      if (raw < 1) animRef.current = requestAnimationFrame(tick);
    };
    animRef.current = requestAnimationFrame(tick);
    return () => { if (animRef.current) cancelAnimationFrame(animRef.current); };
  }, [mode]);

  React.useEffect(() => {
    if (!rootRef.current) return;
    const io = new IntersectionObserver(entries => {
      entries.forEach(e => {
        if (e.isIntersecting && !autoplayed.current) {
          autoplayed.current = true;
          io.disconnect();
          // Auto-sequence cycles through the three modes after scroll-in.
          // Interval 3000ms: 1.4s tween + ~1.5s to actually perceive
          // the resulting shape before the next change kicks in.
          const seq = ['ai-unsecured', 'tc-ai'];
          seq.forEach((m, i) => setTimeout(() => setMode(m), 3000 * (i + 1)));
          setTimeout(() => setHint(true), 3000 * (seq.length + 1));
          setTimeout(() => setHint(false), 3000 * (seq.length + 1) + 5500);
        }
      });
    }, { threshold: 0.3 });
    io.observe(rootRef.current);
    return () => io.disconnect();
  }, []);

  const cx = 260, cy = 260, R = 200;
  const pts = RADAR_DIMS.map((d, i) => {
    const angle = (i / RADAR_DIMS.length) * Math.PI * 2 - Math.PI / 2;
    const v = scores[d.key];
    return {
      x: cx + Math.cos(angle) * R * v,
      y: cy + Math.sin(angle) * R * v,
      lx: cx + Math.cos(angle) * (R + 30),
      ly: cy + Math.sin(angle) * (R + 30),
      ax: Math.cos(angle), ay: Math.sin(angle),
      label: d.label,
      key: d.key,
      v,
    };
  });
  const polygon = pts.map(p => `${p.x},${p.y}`).join(' ');
  const avg = Math.round((Object.values(scores).reduce((a, b) => a + b, 0) / Object.values(scores).length) * 100);

  const modeInfo = {
    'no-ai': { title: 'No AI deployed', sub: 'Baseline security posture — decent but blind to AI-specific risk.', tone: 'neutral' },
    'ai-unsecured': { title: 'AI deployed without architecture', sub: 'New attack surface, data exposure, untracked model calls. The risk you hear about.', tone: 'danger' },
    'tc-ai': { title: 'AI deployed the Technology Cycle way', sub: 'Security-first. Every dimension addressed from day one.', tone: 'good' },
  }[mode];

  return (
    <div className="radar-widget" ref={rootRef}>
      <div className="radar-toggle">
        <button className={mode === 'no-ai' ? 'active' : ''} onClick={() => setMode('no-ai')}>No AI</button>
        <button className={mode === 'ai-unsecured' ? 'active' : ''} onClick={() => setMode('ai-unsecured')}>AI without architecture</button>
        <button className={mode === 'tc-ai' ? 'active' : ''} onClick={() => setMode('tc-ai')}>AI with Technology Cycle</button>
        {/* hint removed — toggles are self-evident */}
      </div>

      <div className="radar-layout">
        <div className="radar-svg-wrap">
          {/* Wider viewBox with padding so long axis labels like
              "Human oversight" and "Data residency" render entirely
              inside the SVG bounds (they were clipping against the
              right and left edges previously). */}
          <svg viewBox="-110 -10 740 540" className="radar-svg">
            <defs>
              <radialGradient id="radar-fill-good">
                <stop offset="0%" stopColor="#10B981" stopOpacity="0.4" />
                <stop offset="100%" stopColor="#10B981" stopOpacity="0.08" />
              </radialGradient>
              <radialGradient id="radar-fill-neutral">
                <stop offset="0%" stopColor="#6B8BC5" stopOpacity="0.35" />
                <stop offset="100%" stopColor="#6B8BC5" stopOpacity="0.08" />
              </radialGradient>
              <radialGradient id="radar-fill-danger">
                <stop offset="0%" stopColor="#ef4444" stopOpacity="0.35" />
                <stop offset="100%" stopColor="#ef4444" stopOpacity="0.06" />
              </radialGradient>
            </defs>

            {/* grid rings */}
            {[0.25, 0.5, 0.75, 1].map(r => (
              <circle key={r} cx={cx} cy={cy} r={R * r} fill="none" stroke="var(--border)" strokeWidth="1" strokeDasharray={r < 1 ? '2 4' : ''} />
            ))}
            {/* spokes */}
            {RADAR_DIMS.map((d, i) => {
              const angle = (i / RADAR_DIMS.length) * Math.PI * 2 - Math.PI / 2;
              const x = cx + Math.cos(angle) * R;
              const y = cy + Math.sin(angle) * R;
              return <line key={d.key} x1={cx} y1={cy} x2={x} y2={y} stroke="var(--border)" strokeWidth="1" />;
            })}

            {/* filled polygon */}
            <polygon
              points={polygon}
              fill={`url(#radar-fill-${modeInfo.tone})`}
              stroke={modeInfo.tone === 'good' ? '#10B981' : modeInfo.tone === 'danger' ? '#ef4444' : '#6B8BC5'}
              strokeWidth="2"
              style={{ transition: 'all 1.4s var(--ease-out)' }}
            />

            {/* vertices */}
            {pts.map(p => (
              <circle key={p.key} cx={p.x} cy={p.y} r="4"
                fill={modeInfo.tone === 'good' ? '#10B981' : modeInfo.tone === 'danger' ? '#ef4444' : '#6B8BC5'}
                style={{ transition: 'all 1.4s var(--ease-out)' }}
              />
            ))}

            {/* labels */}
            {pts.map(p => (
              <text
                key={p.key + 'l'}
                x={p.lx} y={p.ly}
                textAnchor={p.ax > 0.2 ? 'start' : p.ax < -0.2 ? 'end' : 'middle'}
                fontSize="12"
                fontFamily="var(--font-mono)"
                fill="var(--text-muted)"
                dy="4"
              >{p.label}</text>
            ))}
          </svg>
        </div>

        <div className="radar-sidebar">
          <div className={`radar-status radar-status-${modeInfo.tone}`}>
            <span className="label-mono">Posture</span>
            <h4>{modeInfo.title}</h4>
            <p>{modeInfo.sub}</p>
            <div className="radar-score">
              <div className="radar-score-num">{avg}<span style={{ fontSize: 18, color: 'var(--text-muted)' }}>/100</span></div>
              <div className="label-mono">Overall</div>
            </div>
          </div>

          <div className="radar-dim-list">
            {RADAR_DIMS.map(d => {
              const v = Math.round(scores[d.key] * 100);
              return (
                <div className="radar-dim-row" key={d.key}>
                  <span>{d.label}</span>
                  <div className="radar-dim-bar"><div style={{ width: `${v}%`, background: modeInfo.tone === 'good' ? '#10B981' : modeInfo.tone === 'danger' ? '#ef4444' : '#6B8BC5' }} /></div>
                  <span className="mono">{v}</span>
                </div>
              );
            })}
          </div>
        </div>
      </div>
    </div>
  );
};
