// widgets.jsx — visual atoms for the 標靶招募分析 dashboard
// Multi-ring, dial, mini bar chart, sparkline, glyphs, etc.

const { useState, useEffect, useRef } = React;

// ─────────────────────────────────────────────────────────────
// Concentric multi-ring with orbital glyphs (the "命盤環")
// ─────────────────────────────────────────────────────────────
function MultiRing({ a = 0.78, b = 0.62, c = 0.50, size = 158 }) {
  const cx = size / 2, cy = size / 2;
  const R = [size * 0.43, size * 0.33, size * 0.23];
  const W = size * 0.07;

  const ring = (r, prog, color, glow) => {
    const C = 2 * Math.PI * r;
    return (
      <g>
        <circle cx={cx} cy={cy} r={r} fill="none"
                stroke="rgba(255,255,255,0.05)" strokeWidth={W} />
        <circle cx={cx} cy={cy} r={r} fill="none"
                stroke={color} strokeWidth={W} strokeLinecap="round"
                strokeDasharray={`${C * prog} ${C}`}
                transform={`rotate(-90 ${cx} ${cy})`}
                style={{ filter: `drop-shadow(0 0 ${glow}px ${color})` }} />
      </g>
    );
  };

  // orbital glyphs — small floating tags inside rings
  const glyphs = [
    { angle: 70,  r: R[0] - W*0.2, color: 'var(--pink-soft)', symbol: '♕' }, // 命主
    { angle: 160, r: R[0] - W*0.2, color: 'var(--purple)',    symbol: '☉' }, // 天命
    { angle: 230, r: R[1] - W*0.2, color: 'var(--neon-green)',symbol: '✦' }, // 共振
    { angle: 310, r: R[1] - W*0.2, color: 'var(--amber)',     symbol: '⚖' }, // 阿卡西
    { angle: 40,  r: R[2] - W*0.2, color: 'var(--magenta)',   symbol: '✶' }, // 標靶
  ];

  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`}>
      {ring(R[0], a, 'var(--purple)', 6)}
      {ring(R[1], b, 'var(--neon-green)', 6)}
      {ring(R[2], c, 'var(--magenta)', 6)}
      {/* center punch */}
      <circle cx={cx} cy={cy} r={size * 0.11} fill="#080A14"/>
      {/* orbital glyphs */}
      {glyphs.map((g, i) => {
        const rad = (g.angle - 90) * Math.PI / 180;
        const x = cx + Math.cos(rad) * g.r;
        const y = cy + Math.sin(rad) * g.r;
        return (
          <g key={i}>
            <circle cx={x} cy={y} r={size*0.05} fill="rgba(8,10,20,0.92)" stroke={g.color} strokeWidth="0.8"/>
            <text x={x} y={y+size*0.018} textAnchor="middle" fontSize={size*0.055}
                  fill={g.color} fontFamily="serif" style={{ filter: `drop-shadow(0 0 3px ${g.color})` }}>
              {g.symbol}
            </text>
          </g>
        );
      })}
    </svg>
  );
}

// ─────────────────────────────────────────────────────────────
// Mini-ring used in the phase strip (one per day)
// ─────────────────────────────────────────────────────────────
function PhaseRing({ active = false, label, day, scores = [0.7, 0.5, 0.4], dim = false }) {
  const size = 42, cx = size/2, cy = size/2;
  const R = [size*0.42, size*0.30, size*0.18];
  const W = size*0.10;
  const colors = active
    ? ['var(--purple)', 'var(--neon-green)', 'var(--magenta)']
    : ['rgba(176,124,255,0.55)', 'rgba(43,212,168,0.55)', 'rgba(255,93,162,0.55)'];

  if (dim) {
    return (
      <div style={{ textAlign: 'center', opacity: 0.32 }}>
        <div style={{ fontSize: 11, color: 'var(--fg-3)' }}>{label}</div>
        <div style={{ width: size, height: size, borderRadius: '50%',
                      border: '2px solid rgba(255,255,255,0.08)',
                      display:'flex', alignItems:'center', justifyContent:'center',
                      margin: '4px auto 0' }}>
          <span className="num" style={{ fontSize: 13, color: 'var(--fg-3)' }}>{day}</span>
        </div>
      </div>
    );
  }

  const ring = (r, p, color) => {
    const C = 2*Math.PI*r;
    return (
      <circle cx={cx} cy={cy} r={r} fill="none" stroke={color} strokeWidth={W}
              strokeLinecap="round"
              strokeDasharray={`${C*p} ${C}`}
              transform={`rotate(-90 ${cx} ${cy})`}
              style={{ filter: active ? `drop-shadow(0 0 4px ${color})` : 'none' }}/>
    );
  };

  return (
    <div style={{ textAlign: 'center' }}>
      <div style={{ fontSize: 11, color: active ? 'var(--fg)' : 'var(--fg-2)', fontWeight: active ? 600 : 400 }}>{label}</div>
      <div style={{ position: 'relative', width: size, height: size, margin: '4px auto 0' }}>
        <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`}>
          {ring(R[0], scores[0], colors[0])}
          {ring(R[1], scores[1], colors[1])}
          {ring(R[2], scores[2], colors[2])}
          {active && <circle cx={cx} cy={cy} r={size*0.42 + W/2 + 2} fill="none" stroke="rgba(176,124,255,0.55)" strokeWidth="1"/>}
        </svg>
        <span className="num" style={{
          position: 'absolute', inset: 0, display: 'flex',
          alignItems: 'center', justifyContent: 'center',
          fontSize: 12, color: 'var(--fg)', fontWeight: 500
        }}>{day}</span>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Hourly tick bar (the strip under the main card)
// ─────────────────────────────────────────────────────────────
function TickStrip({ ticks = 27, peakIdx = [3,4,8,9,10,14,15,19,20] }) {
  return (
    <div style={{ display: 'flex', gap: 3, alignItems: 'flex-end', height: 18 }}>
      {Array.from({ length: ticks }).map((_, i) => {
        const peak = peakIdx.includes(i);
        return (
          <div key={i} style={{
            flex: 1, height: peak ? 14 : 9,
            borderRadius: 99,
            background: peak ? 'var(--neon-green)' : 'rgba(43,212,168,0.32)',
            boxShadow: peak ? '0 0 5px rgba(43,212,168,0.6)' : 'none',
          }}/>
        );
      })}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Gauge / dial — half-circle with gradient + needle dot
// ─────────────────────────────────────────────────────────────
function Dial({ value = 18, max = 36, w = 130 }) {
  const cx = w/2, cy = w*0.55, r = w*0.38;
  const startAng = Math.PI, endAng = 0;
  const valAng = startAng + (value/max) * (endAng - startAng);
  const dx = cx + Math.cos(valAng) * r;
  const dy = cy + Math.sin(valAng) * r;

  const arcPath = (a1, a2) => {
    const x1 = cx + Math.cos(a1)*r, y1 = cy + Math.sin(a1)*r;
    const x2 = cx + Math.cos(a2)*r, y2 = cy + Math.sin(a2)*r;
    const large = Math.abs(a2-a1) > Math.PI ? 1 : 0;
    const sweep = a2 > a1 ? 0 : 1; // for clockwise on top semicircle (sweep depends on orientation)
    return `M ${x1} ${y1} A ${r} ${r} 0 ${large} ${sweep} ${x2} ${y2}`;
  };

  return (
    <svg width={w} height={w*0.65} viewBox={`0 0 ${w} ${w*0.65}`} style={{ overflow: 'visible' }}>
      <defs>
        <linearGradient id="dialgrad" x1="0%" y1="0%" x2="100%" y2="0%">
          <stop offset="0%"  stopColor="#2BD4A8"/>
          <stop offset="35%" stopColor="#5BA9FF"/>
          <stop offset="65%" stopColor="#B07CFF"/>
          <stop offset="100%" stopColor="#FF3B5C"/>
        </linearGradient>
      </defs>
      <path d={arcPath(startAng, endAng)} stroke="rgba(255,255,255,0.08)" strokeWidth={w*0.09} fill="none" strokeLinecap="round"/>
      <path d={arcPath(startAng, endAng)} stroke="url(#dialgrad)" strokeWidth={w*0.09} fill="none" strokeLinecap="round"/>
      <circle cx={dx} cy={dy} r={w*0.045} fill="#fff" stroke="rgba(0,0,0,0.3)" strokeWidth="1"
              style={{ filter: 'drop-shadow(0 0 3px rgba(255,255,255,0.7))' }}/>
    </svg>
  );
}

// ─────────────────────────────────────────────────────────────
// Talent stack — 3 horizontal bars with a node on the lead bar
// ─────────────────────────────────────────────────────────────
function TalentStack({ values = [0.92, 0.58, 0.32] }) {
  const w = 110, h = 22, gap = 6;
  const colors = ['#5DD89A', '#A8A14A', '#A14A4A'];
  return (
    <svg width={w} height={(h+gap)*3 - gap} viewBox={`0 0 ${w} ${(h+gap)*3 - gap}`}>
      {values.map((v, i) => {
        const y = i*(h+gap);
        return (
          <g key={i}>
            <rect x="0" y={y} width={w} height={h} rx="3"
                  fill={colors[i]} opacity={0.85}/>
            {i === 0 && (
              <circle cx={w*v - 4} cy={y + h/2} r={6}
                      fill="#fff" stroke="rgba(0,0,0,0.2)" strokeWidth="0.5"
                      style={{ filter: 'drop-shadow(0 0 3px rgba(255,255,255,0.6))' }}/>
            )}
          </g>
        );
      })}
    </svg>
  );
}

// ─────────────────────────────────────────────────────────────
// Stars row (4/5 filled)
// ─────────────────────────────────────────────────────────────
function Stars({ filled = 4, total = 5 }) {
  return (
    <div style={{ display: 'flex', gap: 4 }}>
      {Array.from({ length: total }).map((_, i) => (
        <svg key={i} width="14" height="14" viewBox="0 0 24 24">
          <path d="M12 2l3 7h7l-5.5 4.5L18 21l-6-4-6 4 1.5-7.5L2 9h7z"
                fill={i < filled ? 'var(--amber)' : 'rgba(255,215,107,0.18)'}
                stroke={i < filled ? 'var(--gold)' : 'rgba(255,215,107,0.3)'}
                strokeWidth="0.8"
                style={i < filled ? { filter: 'drop-shadow(0 0 2px rgba(255,215,107,0.5))' } : {}}/>
        </svg>
      ))}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Potential chart — three curves over time, peaks + valleys
// ─────────────────────────────────────────────────────────────
function PotentialChart({ data, h = 170, w = 360 }) {
  const pad = { l: 22, r: 12, t: 8, b: 22 };
  const innerW = w - pad.l - pad.r;
  const innerH = h - pad.t - pad.b;

  const yMax = 50, yMin = 0;
  const xMax = data.gold.length - 1;
  const xPos = i => pad.l + (i / xMax) * innerW;
  const yPos = v => pad.t + (1 - (v - yMin) / (yMax - yMin)) * innerH;

  const toPath = (arr) => arr.map((v, i) => `${i === 0 ? 'M' : 'L'} ${xPos(i)} ${yPos(v)}`).join(' ');
  const toArea = (arr) => `${toPath(arr)} L ${xPos(xMax)} ${pad.t + innerH} L ${pad.l} ${pad.t + innerH} Z`;

  const yTicks = [10, 20, 30, 40, 50];

  return (
    <svg width={w} height={h} viewBox={`0 0 ${w} ${h}`}>
      <defs>
        <linearGradient id="goldArea" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="#F5B450" stopOpacity="0.35"/>
          <stop offset="100%" stopColor="#F5B450" stopOpacity="0"/>
        </linearGradient>
        <linearGradient id="magArea" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="#FF5DA2" stopOpacity="0.25"/>
          <stop offset="100%" stopColor="#FF5DA2" stopOpacity="0"/>
        </linearGradient>
      </defs>

      {/* horizontal gridlines */}
      {yTicks.map((t, i) => (
        <g key={i}>
          <line x1={pad.l} x2={w - pad.r} y1={yPos(t)} y2={yPos(t)}
                stroke="rgba(255,255,255,0.06)" strokeDasharray="2 4"/>
          <text x={pad.l - 6} y={yPos(t) + 3} fontSize="9"
                textAnchor="end" fill="var(--fg-3)" className="num">{t}</text>
        </g>
      ))}

      {/* warning labels right side */}
      <text x={w - pad.r + 2} y={yPos(43)} fontSize="9" fill="var(--red)" textAnchor="end">焦慮</text>
      <text x={w - pad.r + 2} y={yPos(33)} fontSize="9" fill="var(--orange)" textAnchor="end">高</text>
      <text x={w - pad.r + 2} y={yPos(22)} fontSize="9" fill="var(--neon-green)" textAnchor="end">一般</text>

      {/* magenta (events) underlay */}
      <path d={toArea(data.magenta)} fill="url(#magArea)"/>
      <path d={toPath(data.magenta)} fill="none" stroke="var(--magenta)" strokeWidth="1.6"
            style={{ filter: 'drop-shadow(0 0 3px rgba(255,93,162,0.4))' }}/>

      {/* gold (motivation) */}
      <path d={toArea(data.gold)} fill="url(#goldArea)"/>
      <path d={toPath(data.gold)} fill="none" stroke="var(--gold)" strokeWidth="1.8"
            style={{ filter: 'drop-shadow(0 0 3px rgba(245,180,80,0.5))' }}/>

      {/* x labels */}
      {[0, 4, 8, 12, 16, 20].map(i => (
        <text key={i} x={xPos(i)} y={h - 6} fontSize="9"
              textAnchor="middle" fill="var(--fg-3)" className="num">{i*4}</text>
      ))}
    </svg>
  );
}

// ─────────────────────────────────────────────────────────────
// Tiny logo cluster (the integration row under the AI banner)
// ─────────────────────────────────────────────────────────────
function LogoCluster() {
  const items = [
    { bg: '#FF6B35', letter: '通', color: '#fff' },
    { bg: 'transparent', letter: '✦', color: '#FFD76B' },
    { bg: 'transparent', letter: '◐', color: '#5BA9FF' },
    { bg: 'transparent', letter: '⌘', color: '#B07CFF' },
    { bg: 'transparent', letter: '∞', color: '#7AE0C4' },
    { bg: 'transparent', letter: 'Z', color: '#FF5DA2' },
    { bg: 'transparent', letter: '✧', color: '#FFD76B' },
    { bg: 'transparent', letter: '✺', color: '#B07CFF' },
    { bg: 'transparent', letter: '◈', color: '#FF8A4C' },
  ];
  return (
    <div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
      {items.map((it, i) => (
        <div key={i} style={{
          width: 18, height: 18, borderRadius: 4,
          background: it.bg,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          color: it.color, fontSize: 13, lineHeight: 1, fontWeight: 600,
        }}>{it.letter}</div>
      ))}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Blob avatar (the soft purple/pink orb on AI banner)
// ─────────────────────────────────────────────────────────────
function Blob({ size = 64 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 64 64" style={{ overflow: 'visible' }}>
      <defs>
        <radialGradient id="blob" cx="35%" cy="30%" r="80%">
          <stop offset="0%" stopColor="#FFFFFF"/>
          <stop offset="35%" stopColor="#E8C8FF"/>
          <stop offset="75%" stopColor="#B07CFF"/>
          <stop offset="100%" stopColor="#7A4FCC"/>
        </radialGradient>
        <filter id="blobGlow">
          <feGaussianBlur stdDeviation="3"/>
        </filter>
      </defs>
      <ellipse cx="32" cy="36" rx="22" ry="14" fill="#B07CFF" opacity="0.4" filter="url(#blobGlow)"/>
      <path d="M22 18 C 12 22, 10 38, 22 46 C 36 52, 50 42, 48 28 C 46 16, 32 14, 22 18 Z"
            fill="url(#blob)" style={{ filter: 'drop-shadow(0 4px 12px rgba(176,124,255,0.5))' }}/>
    </svg>
  );
}

// ─────────────────────────────────────────────────────────────
// Heart pulse icon (top-left of 天時 card)
// ─────────────────────────────────────────────────────────────
function HeartIcon() {
  return (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="var(--red)"
         style={{ filter: 'drop-shadow(0 0 4px rgba(255,59,92,0.6))' }}>
      <path d="M12 21s-7-4.5-9.5-9C.5 8 3 4 6.5 4c2 0 3.5 1 5.5 3 2-2 3.5-3 5.5-3C21 4 23.5 8 21.5 12 19 16.5 12 21 12 21z"/>
    </svg>
  );
}

// ─────────────────────────────────────────────────────────────
// Mask icon (top-left of 阿卡西 card — drama mask)
// ─────────────────────────────────────────────────────────────
function MaskIcon({ color = 'var(--blue)' }) {
  return (
    <svg width="22" height="20" viewBox="0 0 24 22" fill={color}
         style={{ filter: `drop-shadow(0 0 4px ${color})` }}>
      <path d="M6 2 C 3 4, 2 9, 4 14 C 6 18, 9 19, 11 17 C 12 16, 12 14, 11 12 C 10 10, 9 8, 9 6 C 9 4, 8 2.5, 6 2 Z"/>
      <path d="M18 2 C 21 4, 22 9, 20 14 C 18 18, 15 19, 13 17 C 14 16, 14 14, 13 12 C 14 10, 15 8, 15 6 C 15 4, 16 2.5, 18 2 Z" opacity="0.7"/>
      <circle cx="7" cy="9" r="1.1" fill="#08111C"/>
      <circle cx="17" cy="9" r="1.1" fill="#08111C"/>
    </svg>
  );
}

// ─────────────────────────────────────────────────────────────
// Arrows-LR icon
// ─────────────────────────────────────────────────────────────
function ArrowsIcon({ color = 'var(--orange)' }) {
  return (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2"
         strokeLinecap="round" strokeLinejoin="round"
         style={{ filter: `drop-shadow(0 0 4px ${color})` }}>
      <path d="M7 7h13M7 7l3-3M7 7l3 3"/>
      <path d="M17 17H4m13 0l-3-3m3 3l-3 3"/>
    </svg>
  );
}

// ─────────────────────────────────────────────────────────────
// Lucide-style line icons for the tab bar
// ─────────────────────────────────────────────────────────────
const TabIcons = {
  overview: (color) => (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none">
      <circle cx="7" cy="7" r="2.4" fill={color}/>
      <circle cx="17" cy="7" r="2.4" fill={color}/>
      <circle cx="7" cy="17" r="2.4" fill={color}/>
      <circle cx="17" cy="17" r="2.4" fill={color}/>
      <circle cx="12" cy="12" r="2.4" fill={color}/>
    </svg>
  ),
  doc: (color) => (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
      <rect x="5" y="3" width="14" height="18" rx="2"/>
      <path d="M9 8h6M9 12h6M9 16h4"/>
    </svg>
  ),
  ai: (color) => (
    <svg width="26" height="26" viewBox="0 0 24 24" fill="none">
      <text x="12" y="17" textAnchor="middle" fontSize="14" fontWeight="700"
            fill={color} fontFamily="Geist, system-ui">Ai</text>
    </svg>
  ),
  target: (color) => (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="1.6">
      <circle cx="12" cy="12" r="9"/>
      <circle cx="12" cy="12" r="5.5"/>
      <circle cx="12" cy="12" r="2" fill={color}/>
    </svg>
  ),
  user: (color) => (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
      <circle cx="12" cy="8" r="3.8"/>
      <path d="M4 21c1.5-4 5-6 8-6s6.5 2 8 6"/>
    </svg>
  ),
};

// expose
Object.assign(window, {
  MultiRing, PhaseRing, TickStrip, Dial, TalentStack, Stars,
  PotentialChart, LogoCluster, Blob, HeartIcon, MaskIcon, ArrowsIcon, TabIcons,
});
