/* ============================================
   Compass — Living Compass OS hero
   Big central rotating compass with 16 stars
   ============================================ */

const TYPES_16 = [
  // [code, label_jp, group, blurb]
  ["INFP", "静かな詩人",     "diplomat", "感じたことを、自分の言葉でゆっくり整える人"],
  ["ENFP", "灯をともす人",   "diplomat", "可能性を見つけ、まわりに火を渡す人"],
  ["INFJ", "月夜の道標",     "diplomat", "見えない流れを読み、静かに導く人"],
  ["ENFJ", "人を結ぶ人",     "diplomat", "場の気持ちを束ねて、前へ進める人"],
  ["INTJ", "静かな設計者",   "analyst",  "遠くを見て、戦略を描く人"],
  ["ENTJ", "道を切り拓く人", "analyst",  "意志をもって、現実を動かす人"],
  ["INTP", "思考の探検家",   "analyst",  "問いを愛し、構造を解き明かす人"],
  ["ENTP", "風を読む人",     "analyst",  "面白さで状況を変えていく人"],
  ["ISFJ", "温かな守り手",   "sentinel", "細やかに気づき、誰かを支える人"],
  ["ESFJ", "場を整える人",   "sentinel", "人と人のあいだに、調和をつくる人"],
  ["ISTJ", "揺るぎない実務家","sentinel","約束を、静かに果たし続ける人"],
  ["ESTJ", "まとめる人",     "sentinel", "段取りを組み、物事を前に進める人"],
  ["ISFP", "美を編む人",     "explorer", "感じたままを、形にしていく人"],
  ["ESFP", "喜びを運ぶ人",   "explorer", "いまこの瞬間に、灯をともす人"],
  ["ISTP", "静かな技巧家",   "explorer", "観察し、手を動かして確かめる人"],
  ["ESTP", "即興の旅人",     "explorer", "風向きを読み、即座に動く人"],
];

// 16 stars laid out across 4 concentric rings — looks like a sky map, not a grid
const STAR_POSITIONS = [
  // angle (deg), radius (0..1)
  { a:  -78, r: 0.78 }, // INFP
  { a:  -22, r: 0.88 }, // ENFP
  { a:   30, r: 0.72 }, // INFJ
  { a:   72, r: 0.86 }, // ENFJ
  { a:  118, r: 0.80 }, // INTJ
  { a:  158, r: 0.92 }, // ENTJ
  { a: -158, r: 0.74 }, // INTP
  { a: -120, r: 0.90 }, // ENTP

  { a:  -56, r: 0.54 }, // ISFJ
  { a:    8, r: 0.60 }, // ESFJ
  { a:   55, r: 0.50 }, // ISTJ
  { a:  100, r: 0.58 }, // ESTJ
  { a:  142, r: 0.52 }, // ISFP
  { a: -176, r: 0.62 }, // ESFP
  { a: -132, r: 0.48 }, // ISTP
  { a:  -98, r: 0.58 }, // ESTP
];

function polarToXY(angleDeg, radius, cx, cy, scale) {
  const rad = (angleDeg - 90) * Math.PI / 180;
  return {
    x: cx + Math.cos(rad) * radius * scale,
    y: cy + Math.sin(rad) * radius * scale,
  };
}

function CompassRose({ activeIdx, hoverIdx }) {
  // Determine target angle for the needle
  const target = hoverIdx ?? activeIdx;
  const needleAngle = target != null ? STAR_POSITIONS[target].a : 0;

  return (
    <svg viewBox="0 0 600 600" className="compass-svg" aria-hidden="true">
      <defs>
        <radialGradient id="comp-glow" cx="50%" cy="50%" r="50%">
          <stop offset="0%"  stopColor="rgba(201,165,101,.35)" />
          <stop offset="60%" stopColor="rgba(201,165,101,.06)" />
          <stop offset="100%" stopColor="rgba(201,165,101,0)" />
        </radialGradient>
        <linearGradient id="needle-grad" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%"  stopColor="#E0C893" />
          <stop offset="50%" stopColor="#C9A565" />
          <stop offset="100%" stopColor="#7A6234" />
        </linearGradient>
        <linearGradient id="needle-back" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%"  stopColor="#5C6B8A" />
          <stop offset="100%" stopColor="#2A3656" />
        </linearGradient>
      </defs>

      {/* Outer glow */}
      <circle cx="300" cy="300" r="290" fill="url(#comp-glow)" />

      {/* Concentric rings */}
      <g className="rings" stroke="rgba(246,241,230,.10)" fill="none">
        <circle cx="300" cy="300" r="272" />
        <circle cx="300" cy="300" r="232" strokeDasharray="2 6" />
        <circle cx="300" cy="300" r="182" />
        <circle cx="300" cy="300" r="142" strokeDasharray="1 4" />
        <circle cx="300" cy="300" r="96" />
      </g>

      {/* Slow rotating outer degree ring */}
      <g className="spin-slow" style={{ transformOrigin: "300px 300px" }}>
        {Array.from({ length: 72 }).map((_, i) => {
          const a = (i * 5 - 90) * Math.PI / 180;
          const isMajor = i % 9 === 0;
          const r1 = isMajor ? 252 : 260;
          const r2 = 272;
          return (
            <line key={i}
              x1={300 + Math.cos(a) * r1} y1={300 + Math.sin(a) * r1}
              x2={300 + Math.cos(a) * r2} y2={300 + Math.sin(a) * r2}
              stroke={isMajor ? "rgba(201,165,101,.6)" : "rgba(246,241,230,.18)"}
              strokeWidth={isMajor ? 1.4 : 1}
            />
          );
        })}
        {/* Cardinal letters */}
        {[
          ["N", 0, 240], ["E", 90, 240], ["S", 180, 240], ["W", 270, 240]
        ].map(([l, deg, r]) => {
          const a = (deg - 90) * Math.PI / 180;
          return (
            <text key={l}
              x={300 + Math.cos(a) * r} y={300 + Math.sin(a) * r + 4}
              textAnchor="middle"
              fontFamily="JetBrains Mono, monospace"
              fontSize="11"
              letterSpacing="2"
              fill="rgba(201,165,101,.7)"
            >{l}</text>
          );
        })}
      </g>

      {/* Cardinal cross */}
      <g stroke="rgba(246,241,230,.16)" strokeWidth="1">
        <line x1="300" y1="50"  x2="300" y2="550" />
        <line x1="50"  y1="300" x2="550" y2="300" />
        <line x1="125" y1="125" x2="475" y2="475" strokeDasharray="2 5" opacity=".5"/>
        <line x1="125" y1="475" x2="475" y2="125" strokeDasharray="2 5" opacity=".5"/>
      </g>

      {/* Needle */}
      <g style={{
        transformOrigin: "300px 300px",
        transform: `rotate(${needleAngle}deg)`,
        transition: "transform 1200ms cubic-bezier(.22,.61,.36,1)",
      }}>
        <polygon points="300,90 308,300 292,300" fill="url(#needle-grad)" />
        <polygon points="300,510 308,300 292,300" fill="url(#needle-back)" />
        <circle cx="300" cy="300" r="14" fill="#0B1426" stroke="#C9A565" strokeWidth="2" />
        <circle cx="300" cy="300" r="4" fill="#C9A565" />
      </g>

      {/* Inner monogram */}
      <g opacity=".9">
        <circle cx="300" cy="300" r="58" fill="none" stroke="rgba(201,165,101,.4)" />
        <text x="300" y="288" textAnchor="middle"
          fontFamily="JetBrains Mono, monospace" fontSize="9" letterSpacing="3"
          fill="rgba(201,165,101,.7)">COMPASS</text>
        <text x="300" y="318" textAnchor="middle"
          fontFamily="Shippori Mincho B1, serif" fontSize="18" letterSpacing="6"
          fill="rgba(246,241,230,.85)">羅</text>
        <text x="300" y="338" textAnchor="middle"
          fontFamily="JetBrains Mono, monospace" fontSize="8" letterSpacing="3"
          fill="rgba(201,165,101,.55)">v.01 — 自己理解</text>
      </g>

      {/* Theme markers — N/E/S/W labels */}
      {[
        ["自己理解", -90, 102],
        ["仕事",       0, 102],
        ["人間関係",  90, 102],
        ["恋愛",     180, 102],
      ].map(([label, deg, r]) => {
        const a = (deg) * Math.PI / 180;
        const x = 300 + Math.cos(a) * r;
        const y = 300 + Math.sin(a) * r;
        return (
          <g key={label}>
            <circle cx={x} cy={y} r="3" fill="#C9A565" />
            <text x={x} y={y - 10} textAnchor="middle"
              fontFamily="Shippori Mincho B1, serif" fontSize="11"
              fill="rgba(246,241,230,.85)" letterSpacing="2">{label}</text>
          </g>
        );
      })}
    </svg>
  );
}

function TypeStar({ idx, type, active, hovered, onHover, onLeave, onSelect, cx, cy, scale }) {
  const pos = polarToXY(STAR_POSITIONS[idx].a, STAR_POSITIONS[idx].r, cx, cy, scale);
  const grp = type[2];
  const state = active ? "active" : hovered ? "hover" : "rest";
  return (
    <button
      className={`type-star type-star--${grp} type-star--${state}`}
      style={{ left: `${(pos.x/600)*100}%`, top: `${(pos.y/600)*100}%`, animationDelay: `${idx * 0.18}s` }}
      onMouseEnter={() => onHover(idx)}
      onMouseLeave={onLeave}
      onFocus={() => onHover(idx)}
      onBlur={onLeave}
      onClick={() => onSelect(idx)}
      aria-label={`${type[0]} ${type[1]}`}
    >
      <span className="ts-dot" aria-hidden="true">
        <span className="ts-dot-inner" />
      </span>
      <span className="ts-label">
        <span className="ts-code">{type[0]}</span>
        <span className="ts-jp">{type[1]}</span>
      </span>
    </button>
  );
}

function LivingCompass({ activeIdx, setActiveIdx }) {
  const [hover, setHover] = React.useState(null);
  // SVG is 600x600. We use the same coordinate system for stars overlay.
  const cx = 300, cy = 300, scale = 270;

  return (
    <div className="compass-stage">
      <div className="compass-orbit drift">
        <CompassRose activeIdx={activeIdx} hoverIdx={hover} />
        {/* Star overlay (HTML positioned over SVG) */}
        <div className="compass-stars">
          {TYPES_16.map((t, i) => (
            <TypeStar
              key={t[0]}
              idx={i} type={t}
              active={activeIdx === i}
              hovered={hover === i}
              onHover={setHover}
              onLeave={() => setHover(null)}
              onSelect={setActiveIdx}
              cx={cx} cy={cy} scale={scale}
            />
          ))}
        </div>
      </div>

      {/* Floating readout card */}
      <ActiveTypeReadout idx={hover ?? activeIdx} />
    </div>
  );
}

function ActiveTypeReadout({ idx }) {
  const t = TYPES_16[idx];
  return (
    <div className="compass-readout">
      <div className="cr-row">
        <span className="label-mono" style={{ color: "var(--gold)" }}>NOW POINTING</span>
        <span className="cr-dot" />
      </div>
      <div className="cr-code">{t[0]}</div>
      <div className="cr-name">{t[1]}</div>
      <div className="cr-blurb">{t[3]}</div>
      <div className="cr-themes">
        <span>恋愛</span><span>仕事</span><span>人間関係</span><span>自己理解</span>
      </div>
    </div>
  );
}

window.TYPES_16 = TYPES_16;
window.STAR_POSITIONS = STAR_POSITIONS;
window.LivingCompass = LivingCompass;
window.CompassRose = CompassRose;
