// Helpers: PhoneFrame, ClosedLoop, Sparkline, QRPlaceholder, FounderPortrait, Helper sparkline.

function PhoneFrame({ src }) {
  const h = 540;
  const w = Math.round(h * 9 / 19.5); // 249
  return (
    <div style={{
      width: w, height: h,
      background: '#000', padding: 6, border: `1px solid ${D.borderLight}`,
      position: 'relative', overflow: 'hidden', boxSizing: 'border-box',
    }}>
      <img src={src} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover', objectPosition: 'top', display: 'block', background: '#E4E4E4' }} />
    </div>
  );
}

// Sparkline — plots a real `data` series (climbing up-and-to-the-right), or a
// lively rising default. Values are normalized to fill the vertical range, so
// the peak reaches near the top instead of clamping flat partway up.
function Sparkline({ width = 200, height = 32, color = '#000', points = 28, data = null }) {
  let series = data;
  if (!series || series.length < 2) {
    series = [];
    for (let i = 0; i < points; i++) {
      const trend = (i / (points - 1)) * 0.62;          // steady climb across the full width
      const wobble = (Math.sin(i * 0.7) + Math.cos(i * 1.3)) * 0.05;
      series.push(0.18 + trend + wobble);
    }
  }
  const n = series.length;
  const min = Math.min(...series);
  const max = Math.max(...series);
  const span = max - min || 1;
  // map [min,max] → [0.08, 0.95] of height (top = peak), leaving headroom top/bottom
  const norm = series.map((d) => 0.08 + ((d - min) / span) * 0.87);
  const stepX = width / (n - 1);
  const path = norm.map((d, i) => `${i === 0 ? 'M' : 'L'} ${(i * stepX).toFixed(1)} ${(height - d * height).toFixed(1)}`).join(' ');
  const last = norm.length - 1;
  return (
    <svg width={width} height={height} style={{ display: 'block' }}>
      <path d={path} fill="none" stroke={color} strokeWidth="1.2" />
      <circle cx={(last * stepX).toFixed(1)} cy={(height - norm[last] * height).toFixed(1)} r="2.5" fill={color} />
    </svg>
  );
}

// Real, scannable QR code. Uses qrcode-generator (loaded in index.html).
// `value` is the URL/string encoded. Falls back to a flat block if the lib is missing.
function QRPlaceholder({ size = 120, dark = true, label = true, value = 'https://ccomplete.app', ecc = 'M', quiet = 2 }) {
  const fg = dark ? D.text : D.textLight;
  const bg = dark ? D.bg : D.bgLight;
  let modules = null;
  let count = 0;
  if (typeof window !== 'undefined' && typeof window.qrcode === 'function') {
    const q = window.qrcode(0, ecc);
    q.addData(value);
    q.make();
    count = q.getModuleCount();
    modules = [];
    for (let r = 0; r < count; r++) {
      for (let c = 0; c < count; c++) {
        if (q.isDark(r, c)) modules.push([c, r]);
      }
    }
  }
  const total = count + quiet * 2 || 1;
  const cellSize = size / total;
  return (
    <div style={{ background: bg, padding: 0, border: `1px solid ${fg}`, display: 'flex', flexDirection: 'column' }}>
      <svg width={size} height={size} viewBox={`0 0 ${total} ${total}`} shapeRendering="crispEdges" style={{ display: 'block' }}>
        <rect x="0" y="0" width={total} height={total} fill={bg} />
        {modules && modules.map(([x, y], i) => (
          <rect key={i} x={x + quiet} y={y + quiet} width="1" height="1" fill={fg} />
        ))}
        {!modules && (
          <text x={total / 2} y={total / 2} fontSize="2" textAnchor="middle" dominantBaseline="middle" fill={fg}>QR</text>
        )}
      </svg>
    </div>
  );
}

function FounderPortrait({ size = 80, src = 'assets/founder-paul.png' }) {
  return (
    <div style={{
      width: size, height: size, border: `1px solid ${D.borderLight}`,
      background: '#C8C8C8', overflow: 'hidden', position: 'relative',
    }}>
      {src ? (
        <img
          src={src} alt="Paul Schmidt"
          style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }}
        />
      ) : (
        <div style={{
          width: '100%', height: '100%',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontFamily: D.fontMono, fontSize: size * 0.32, fontWeight: 700, color: D.textLight,
          letterSpacing: -0.5,
        }}>PS</div>
      )}
    </div>
  );
}

// Closed loop diagram for slide 03
function ClosedLoop() {
  const nodes = [
    'Recovery', 'Context', 'Multi-modal data',
    'Prescription', 'Execution', 'Adaptation', 'Community',
  ];
  const W = 1600, H = 380, cx = W / 2, cy = H / 2;
  const rx = 660, ry = 130;
  const positions = nodes.map((_, i) => {
    const angle = (i / nodes.length) * Math.PI * 2 - Math.PI / 2;
    return { x: cx + Math.cos(angle) * rx, y: cy + Math.sin(angle) * ry };
  });
  return (
    <svg viewBox={`0 0 ${W} ${H}`} width="100%" style={{ maxWidth: 1700, overflow: 'visible' }}>
      <ellipse cx={cx} cy={cy} rx={rx} ry={ry} fill="none" stroke={D.borderLight} strokeWidth="1" strokeDasharray="4 6" />
      {/* Arrow indicators on the ellipse */}
      {[0, 1, 2, 3, 4, 5, 6].map(i => {
        const a = (i / 7) * Math.PI * 2 - Math.PI / 2 + 0.22;
        const x = cx + Math.cos(a) * rx;
        const y = cy + Math.sin(a) * ry;
        const ta = a + Math.PI / 2;
        return <text key={`a${i}`} x={x} y={y} fontFamily={D.fontMono} fontSize="16" fill={D.textLight} textAnchor="middle" transform={`rotate(${(ta * 180 / Math.PI - 90).toFixed(1)} ${x} ${y})`}>›</text>;
      })}
      {positions.map((p, i) => (
        <g key={i}>
          <rect x={p.x - 110} y={p.y - 26} width="220" height="52" fill={D.bgLight} stroke={D.borderLight} strokeWidth="1" />
          <text x={p.x} y={p.y + 6} fontFamily={D.fontSans} fontSize="20" fontWeight="700" fill={D.textLight} textAnchor="middle" letterSpacing="-0.3">{nodes[i]}</text>
        </g>
      ))}
      <g>
        <text x={cx} y={cy - 8} fontFamily={D.fontMono} fontSize="13" fontWeight="700" fill={D.textSecLight} textAnchor="middle" letterSpacing="1.5">CLOSED LOOP</text>
        <text x={cx} y={cy + 16} fontFamily={D.fontMono} fontSize="13" fontWeight="700" fill={D.textLight} textAnchor="middle" letterSpacing="1.5">SEVEN STAGES</text>
      </g>
    </svg>
  );
}

Object.assign(window, { PhoneFrame, Sparkline, QRPlaceholder, FounderPortrait, ClosedLoop });
