const { useEffect, useState } = React;

// ── Docking Ring (the centerpiece) ─────────────────────────
function DockingRing({ pilder, body, hover, setHover }) {
  // P0-DOCKRING-NULL-BODY · 教練 2026-05-15 字面 spec:
  //   if (!pilder || !body) → return null (不 render · 不 crash)
  //   console.warn 留追跡 · 之後 Sprint 6 補 body 創建 endpoint 再 render
  // 紅線 (教練字面):
  //   ❌ 不在這裡自動補 body
  //   ❌ 不 fake data
  //   ❌ 不改後端 schema
  // React Rules of Hooks: hooks 必須在 early-return 之前 (順序固定)
  const insc = window.HG2.INSCRIPTIONS;
  const [t, setT] = useState(0);

  useEffect(() => {
    if (!pilder || !body) return;  // hook 內 guard · 不啟 raf
    let raf;
    const tick = () => { setT(performance.now() * 0.001); raf = requestAnimationFrame(tick); };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [pilder, body]);

  // 教練 spec 字面 early-return (hooks 之後 · 對齊 React Rules of Hooks)
  if (!pilder || !body) {
    if (pilder && !body) {
      console.warn("[HG2] pilder has no body", pilder.id);
    }
    return null;
  }

  const W = 1000, H = 720;
  const cx = W/2, cy = H/2;
  const ringR = 230;     // main ring
  const ringR2 = 280;    // outer
  const ringR3 = 180;    // inner

  const tagPos = (a, r) => ({
    x: cx + Math.cos((a) * Math.PI/180) * r,
    y: cy + Math.sin((a) * Math.PI/180) * r,
  });

  return (
    <div className="dock-frame">
      <span className="dock-corner tl" />
      <span className="dock-corner tr" />
      <span className="dock-corner bl" />
      <span className="dock-corner br" />

      <div className="dock-status">
        <span className="pulse" />
        {/* P0-DOCKRING-NULL-BODY · 教練 2026-05-15
            到此處時 body 必非 null (上方 early return 已守) · 直接讀 body.code 安全 */}
        DOCK · {pilder.code} → {body.code}
      </div>

      <svg className="dock-svg" viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="xMidYMid meet">
        <defs>
          <radialGradient id="ring-glow"><stop offset="0%" stopColor="var(--energy)" stopOpacity="0.18" /><stop offset="100%" stopColor="var(--energy)" stopOpacity="0" /></radialGradient>
          <linearGradient id="dock-line" x1="0" x2="1">
            <stop offset="0" stopColor="var(--energy)" />
            <stop offset="1" stopColor="var(--gold)" />
          </linearGradient>
        </defs>

        {/* outer ambience */}
        <circle cx={cx} cy={cy} r={ringR2 + 60} fill="url(#ring-glow)" />

        {/* concentric rings */}
        <circle cx={cx} cy={cy} r={ringR3} fill="none" stroke="var(--hair-strong)" strokeDasharray="2 6" />
        <circle cx={cx} cy={cy} r={ringR}  fill="none" stroke="var(--energy-dim)" strokeWidth="1" />
        <circle cx={cx} cy={cy} r={ringR2} fill="none" stroke="var(--hair-strong)" strokeDasharray="1 5" />

        {/* rotating ticks */}
        <g transform={`rotate(${(t*8) % 360} ${cx} ${cy})`}>
          {Array.from({length: 60}).map((_, i) => {
            const a = (i / 60) * Math.PI * 2;
            const r1 = ringR2 - 6, r2 = ringR2 + 4;
            const x1 = cx + Math.cos(a)*r1, y1 = cy + Math.sin(a)*r1;
            const x2 = cx + Math.cos(a)*r2, y2 = cy + Math.sin(a)*r2;
            return <line key={i} x1={x1} y1={y1} x2={x2} y2={y2} stroke={i%5===0 ? "var(--energy)" : "var(--hair-strong)"} strokeWidth={i%5===0?1.2:0.6} />;
          })}
        </g>

        {/* counter-rotating inner */}
        <g transform={`rotate(${-(t*16) % 360} ${cx} ${cy})`}>
          <circle cx={cx} cy={cy} r={ringR3 - 16} fill="none" stroke="var(--energy)" strokeOpacity="0.4" strokeDasharray="20 14" />
        </g>

        {/* spokes from each inscription point to core */}
        {insc.map((ins, i) => {
          const p = tagPos(ins.angle, ringR);
          const isHover = hover === ins.id;
          const phase = (t * 0.4 + i * 0.14) % 1;
          return (
            <g key={ins.id}>
              <line x1={cx} y1={cy} x2={p.x} y2={p.y}
                stroke={ins.locked ? "var(--gold-dim)" : (isHover ? "var(--energy)" : "var(--hair-strong)")}
                strokeWidth={isHover ? 1.4 : 0.8}
                strokeDasharray={ins.locked ? "3 4" : "0"} />
              {/* particle */}
              <circle
                cx={cx + (p.x - cx) * phase}
                cy={cy + (p.y - cy) * phase}
                r="1.8"
                fill={ins.locked ? "var(--gold)" : "var(--energy)"} />
              {/* anchor pin */}
              <circle cx={p.x} cy={p.y} r={isHover ? 5 : 3.5}
                fill={ins.locked ? "var(--gold)" : "var(--energy)"}
                stroke="var(--bg)" strokeWidth="1" />
            </g>
          );
        })}

        {/* Pilder side line (left) */}
        <line x1={28} y1={cy} x2={cx - ringR3} y2={cy} stroke="url(#dock-line)" strokeWidth="1" strokeOpacity="0.6" />
        {/* Body side line (right) */}
        <line x1={cx + ringR3} y1={cy} x2={W - 28} y2={cy} stroke="url(#dock-line)" strokeWidth="1" strokeOpacity="0.6" />

        {/* central core: diamond inside hex */}
        <g transform={`translate(${cx},${cy})`}>
          <polygon
            points={(() => {
              const pts = [];
              for (let i=0; i<6; i++) {
                const a = (i/6) * Math.PI*2 - Math.PI/2;
                pts.push(`${Math.cos(a)*60},${Math.sin(a)*60}`);
              }
              return pts.join(" ");
            })()}
            fill="rgba(0,0,0,0.85)" stroke="var(--energy)" />
          <polygon points="0,-30 30,0 0,30 -30,0"
            fill="none" stroke="var(--gold)" strokeWidth="1" />
          <circle r="8" fill="var(--gold)" />
          <text textAnchor="middle" y="78" fontFamily="var(--font-mono)" fontSize="11"
            fill="var(--energy)" letterSpacing="0.16em">SOUL · BODY DOCK</text>
        </g>
      </svg>

      {/* API tags positioned around ring */}
      {insc.map((ins) => {
        const p = tagPos(ins.angle, ringR + 32);
        const align = Math.cos(ins.angle * Math.PI/180);
        const xPct = (p.x / W) * 100;
        const yPct = (p.y / H) * 100;
        return (
          <button
            key={ins.id}
            className={`api-tag ${hover === ins.id ? "hover" : ""} ${ins.locked ? "locked" : ""}`}
            style={{
              left: `${xPct}%`,
              top: `${yPct}%`,
              transform: `translate(${align < -0.3 ? "-100%" : align > 0.3 ? "0%" : "-50%"}, -50%)`,
            }}
            onMouseEnter={() => setHover(ins.id)}
            onMouseLeave={() => setHover(null)}
            onClick={() => {
              const el = document.getElementById(`panel-${ins.id}`);
              if (el) el.scrollIntoView({ block: "nearest", behavior: "smooth" });
            }}
          >
            <div className="api-num">{ins.num}</div>
            <div>{ins.en}</div>
            <div className="api-zh">{ins.zh}</div>
          </button>
        );
      })}

      {/* Pilder card (left) */}
      <div className="dock-overlay-l">
        <div className="entity-card pilder">
          <div className="ec-label">PILDER · 指揮艇</div>
          <div className="ec-name">{pilder.name}</div>
          <div className="ec-sub">{pilder.code} · {pilder.tag}</div>
          <div className="ec-meter"><i style={{ width: `${pilder.resonance}%` }} /></div>
          <div className="ec-sub" style={{display:"flex", justifyContent:"space-between"}}>
            <span>RESONANCE</span><span>{pilder.resonance.toFixed(1)}%</span>
          </div>
        </div>
        <div className="entity-card pilder" style={{ minWidth: 200 }}>
          <div className="ec-label">FIRMWARE</div>
          <div className="ec-sub">soul-{pilder.id}.fw.json</div>
          <div className="ec-sub">v3.14.{pilder.id.length}-stable</div>
        </div>
      </div>

      {/* Body card (right) · 到此處時 body 必非 null (上方 early-return guard) */}
      <div className="dock-overlay-r">
        <div className="entity-card body">
          <div className="ec-label">ROBOT BODY · 機械身體</div>
          <div className="ec-name">{body.name}</div>
          <div className="ec-sub">{body.code} · {body.subsidiary}</div>
          <div className="ec-meter"><i style={{ width: `${body.load}%` }} /></div>
          <div className="ec-sub" style={{display:"flex", justifyContent:"space-between"}}>
            <span>LOAD</span><span>{body.load}%</span>
          </div>
        </div>
        <div className="entity-card body" style={{ minWidth: 200 }}>
          <div className="ec-label">CHANNELS</div>
          <div className="ec-sub" style={{textTransform:"uppercase",letterSpacing:"0.14em"}}>
            {body.channels.join(" · ")}
          </div>
          <div className="ec-sub">REGION · {body.region}</div>
        </div>
      </div>
    </div>
  );
}

window.HG2Hub = { DockingRing };
