/* ═══════════════════════════════════════════════════════════
   Orrery — the shared wheel (SVG). Driven by ORRERY data.
   Props: activeId, onPick(id), zodiacOpacity, showSpokes, ticks('all'|'active')
═══════════════════════════════════════════════════════════ */
const { useState: useStateO } = React;

if (!document.getElementById('orrw-styles')) {
  const s = document.createElement('style');
  s.id = 'orrw-styles';
  s.textContent = `
  .orrw-svg{ width:100%; height:auto; display:block; overflow:visible; }
  .orrw-ring{ fill:none; stroke:var(--rule); stroke-width:1; opacity:.5; transition:stroke .2s,stroke-width .2s,opacity .2s; }
  .orrw-ringgrp.on .orrw-ring{ stroke:var(--blue); stroke-width:1.8; opacity:1; }
  .orrw-ringgrp:not(.on):hover .orrw-ring{ stroke:var(--l-blue); opacity:.8; }
  .orrw-hit{ fill:none; stroke:transparent; stroke-width:18; cursor:pointer; }
  .orrw-tick{ stroke:var(--l-blue); stroke-width:.8; opacity:.45; pointer-events:none; transition:opacity .2s,stroke .2s; }
  .orrw-ringgrp.on .orrw-tick{ stroke:var(--blue); opacity:.9; }
  .orrw-rlabel{ font-family:var(--sc),system-ui,sans-serif; text-transform:uppercase; letter-spacing:.14em; font-size:9.5px; font-weight:500;
    fill:var(--muted); stroke:var(--paper); stroke-width:3px; paint-order:stroke; pointer-events:none; transition:fill .2s; }
  .orrw-ringgrp.on .orrw-rlabel{ fill:var(--blue); }
  .orrw-ringgrp:not(.on):hover .orrw-rlabel{ fill:var(--blue); }
  .orrw-spoke{ stroke:var(--vpale); stroke-width:.8; pointer-events:none; }
  .orrw-sign{ font-size:13px; fill:var(--icon); text-anchor:middle; dominant-baseline:central; pointer-events:none; }
  .orrw-halo{ fill:var(--paper); pointer-events:none; }
  .orrw-retro{ font-family:var(--body),Georgia,serif; font-style:italic; font-size:9px; fill:var(--blue); pointer-events:none; }
  .orrw-ghost{ fill:none; stroke:var(--rule); stroke-width:1; stroke-dasharray:2 5; opacity:.55; pointer-events:none; }
  .orrw-ghost-label{ font-family:var(--sc),system-ui,sans-serif; text-transform:uppercase; letter-spacing:.14em; font-size:8px; font-weight:500;
    fill:var(--icon); stroke:var(--paper); stroke-width:3px; paint-order:stroke; pointer-events:none; }
  .orrw-hub{ fill:var(--paper); stroke:var(--rule); stroke-width:1; }
  .orrw-hub-now{ font-family:var(--sc),system-ui,sans-serif; text-transform:uppercase; letter-spacing:.1em; font-size:7px; font-weight:500; fill:var(--muted); text-anchor:middle; }
  .orrw-planet{ cursor:pointer; }
  .orrw-phit{ fill:transparent; }
  .orrw-pname{ font-family:var(--sc),system-ui,sans-serif; text-transform:uppercase; letter-spacing:.08em; font-size:8px; font-weight:500;
    fill:var(--blue); stroke:var(--paper); stroke-width:3px; paint-order:stroke; text-anchor:middle; opacity:0; transition:opacity .15s; pointer-events:none; }
  .orrw-planet:hover .orrw-pname{ opacity:1; }
  .orrw-planet:hover .orrw-pdisc{ opacity:.18; }
  .orrw-pdisc{ fill:var(--blue); opacity:0; transition:opacity .15s; }
  `;
  document.head.appendChild(s);
}

const CX = 300, CY = 300;
function pol(r, lon) { const a = (lon - 90) * Math.PI / 180; return [CX + r * Math.cos(a), CY + r * Math.sin(a)]; }

function PlanetGlyph({ sym, pkey, r, lon, big, retro, color, onPlanet }) {
  const [x, y] = pol(r, lon);
  const sz = big ? 32 : 26, hp = big ? 19 : 16;
  const clickable = !!(onPlanet && pkey);
  const name = clickable ? (window.ORRERY.planets[pkey].name) : null;
  return (
    <g className={clickable ? 'orrw-planet' : undefined}
       onClick={clickable ? (e) => { e.stopPropagation(); onPlanet(pkey); } : undefined}>
      <circle className="orrw-halo" cx={x} cy={y} r={hp} />
      <circle className="orrw-pdisc" cx={x} cy={y} r={hp} />
      <use href={'#' + sym} x={x - sz / 2} y={y - sz / 2} width={sz} height={sz} style={{ color: color || 'var(--blue)' }} />
      {retro && <text className="orrw-retro" x={x + sz / 2 - 2} y={y - sz / 2 + 3}>{'\u211E'}</text>}
      {clickable && <circle className="orrw-phit" cx={x} cy={y} r={hp + 3} />}
      {name && <text className="orrw-pname" x={x} y={y + hp + 9}>{name}</text>}
    </g>
  );
}

function OrreryWheel({ activeId, onPick, onPlanet, zodiacOpacity = 0.6, showSpokes = true, ticks = 'all', showLabels = 'all', focusRing = null }) {
  const O = window.ORRERY;
  const focus = focusRing ? O.byId[focusRing] : null;
  // zoom so the selected ring fills the frame; clamp so inner rings don't over-magnify
  const s = focus ? Math.min(3, Math.max(1, 236 / focus.r)) : 1;
  const zoomStyle = { transform: `translate(${CX}px,${CY}px) scale(${s}) translate(${-CX}px,${-CY}px)`, transformOrigin: '0 0', transition: 'transform .45s cubic-bezier(.4,0,.2,1)' };
  return (
    <svg className="orrw-svg" viewBox="0 0 600 600" role="img" aria-label="Orrery of time">
     <g className="orrw-zoom" style={zoomStyle}>
      {/* zodiac reference */}
      <g style={{ opacity: zodiacOpacity }}>
        {showSpokes && O.signs.map((s) => {
          const [x1, y1] = pol(244, s.start), [x2, y2] = pol(292, s.start);
          return <line key={'sp' + s.start} className="orrw-spoke" x1={x1} y1={y1} x2={x2} y2={y2} />;
        })}
        {O.signs.map((s) => { const [x, y] = pol(282, s.start + 15); return <text key={s.name} className="orrw-sign" x={x} y={y}>{s.glyph + '\uFE0E'}</text>; })}
      </g>

      {/* ghost cycles ring (wireframe for a later round) */}
      <circle className="orrw-ghost" cx={CX} cy={CY} r={O.cyclesGhost.r} />
      {O.cyclesGhost.planets.map((pl) => { const p = O.planets[pl]; return <PlanetGlyph key={'g' + pl} sym={p.sym} pkey={pl} r={O.cyclesGhost.r} lon={p.lon} color="var(--icon)" onPlanet={onPlanet} />; })}
      {showLabels === 'all' && <text className="orrw-ghost-label" x={CX} y={CY - O.cyclesGhost.r - 5} textAnchor="middle">{O.cyclesGhost.label}</text>}

      {/* rings — draw outermost first so inner ones layer on top */}
      {O.rings.slice().reverse().map((ring) => {
        const on = ring.id === activeId;
        const tArr = [];
        if (ticks === 'all' || on) {
          for (let k = 0; k < ring.ticks; k++) {
            const lon = (k / ring.ticks) * 360;
            const [x1, y1] = pol(ring.r - 2.6, lon), [x2, y2] = pol(ring.r + 2.6, lon);
            tArr.push(<line key={k} className="orrw-tick" x1={x1} y1={y1} x2={x2} y2={y2} />);
          }
        }
        const sigs = ring.signature ? (Array.isArray(ring.signature) ? ring.signature : [ring.signature]) : [];
        return (
          <g key={ring.id} className={'orrw-ringgrp' + (on ? ' on' : '')} onClick={() => onPick(ring.id)}>
            <circle className="orrw-hit" cx={CX} cy={CY} r={ring.r} />
            <circle className="orrw-ring" cx={CX} cy={CY} r={ring.r} />
            {tArr}
            {sigs.map((key) => { const p = O.planets[key]; return <PlanetGlyph key={key} sym={p.sym} pkey={key} r={ring.r} lon={p.lon} big={on} retro={p.retro} onPlanet={onPlanet} />; })}
            {(showLabels === 'all' || (showLabels === 'active' && on)) && <text className="orrw-rlabel" x={CX} y={CY - ring.r - 4} textAnchor="middle">{ring.short}</text>}
          </g>
        );
      })}

      {/* living centre */}
      <circle className="orrw-hub" cx={CX} cy={CY} r="27" />
      <use href={'#' + O.center.sym} x={CX - 7} y={CY - 11} width="14" height="14" style={{ color: 'var(--blue)' }} />
      <text className="orrw-hub-now" x={CX} y={CY + 12}>{O.center.label}</text>
     </g>
    </svg>
  );
}

window.OrreryWheel = OrreryWheel;
