// MoonWidget.jsx — current moon phase visualization with what to look for.

function MoonWidget({ seenIds, onPickMoonObject }) {
  const [now, setNow] = React.useState(() => new Date());

  React.useEffect(() => {
    const t = setInterval(() => setNow(new Date()), 60000);
    return () => clearInterval(t);
  }, []);

  const { age, illumination, waxing, name } = window.moonPhase(now);

  // Moon features in the catalog — surface them here.
  const moonObjects = window.CATALOG.filter(o => o.cat === 'Moon');

  // What to look for tonight based on phase:
  let tip;
  if (age < 1.5) tip = "The Moon is nearly invisible tonight — a perfect night for deep-sky hunting!";
  else if (age < 7) tip = "The terminator is on the eastern limb. Craters along it cast long shadows — great for detail.";
  else if (age < 10) tip = "First quarter — the straight terminator reveals craters and mountain ranges in sharp relief.";
  else if (age < 14) tip = "Waxing gibbous — lots of lit surface but still good shadow detail near the western edge.";
  else if (age < 16) tip = "Near-full Moon is bright and flat. Tycho's rays look spectacular tonight.";
  else if (age < 22) tip = "Waning — terminator is on the western limb. Features there are dramatic in the morning.";
  else tip = "Thin waning crescent — rises just before dawn. Earthshine may light the dark side.";

  const size = 120; // px
  const cx = size / 2, cy = size / 2, r = 50;

  // SVG path for the lit portion. Based on illumination and waxing side.
  // Two half-ellipses: outer full disc edge + terminator ellipse.
  function litPath() {
    const k = 1 - 2 * illumination; // -1 (full) .. 1 (new)
    // Terminator ellipse: rx = r * |k|, ry = r.
    const rx = r * Math.abs(k);
    // Start at top, sweep outer edge to bottom, then terminator back to top.
    // Waxing: lit side is right. Waning: lit side is left.
    const outerSweep = waxing ? 1 : 0;
    const innerSweep = k > 0 ? outerSweep : 1 - outerSweep;
    return `
      M ${cx} ${cy - r}
      A ${r} ${r} 0 0 ${outerSweep} ${cx} ${cy + r}
      A ${rx} ${r} 0 0 ${innerSweep} ${cx} ${cy - r}
      Z`;
  }

  return (
    <div className="moonwidget">
      <div className="moonwidget__visual">
        <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`}>
          <defs>
            <radialGradient id="moonSurface" cx="40%" cy="40%">
              <stop offset="0%" stopColor="#e8e3d3" />
              <stop offset="60%" stopColor="#c4bca5" />
              <stop offset="100%" stopColor="#8e876f" />
            </radialGradient>
            <radialGradient id="moonShadow" cx="50%" cy="50%">
              <stop offset="85%" stopColor="var(--bg)" stopOpacity="1" />
              <stop offset="100%" stopColor="var(--bg)" stopOpacity="0.3" />
            </radialGradient>
          </defs>
          {/* Dark disc */}
          <circle cx={cx} cy={cy} r={r} fill="var(--ink-800)" stroke="var(--line-strong)" strokeWidth="0.5" />
          {/* Lit region */}
          <path d={litPath()} fill="url(#moonSurface)" />
          {/* Outer ring */}
          <circle cx={cx} cy={cy} r={r} fill="none" stroke="var(--ink-600)" strokeWidth="0.8" />
          {/* Subtle craters (decorative) — fixed positions so they move with phase darkness */}
          <g opacity="0.35">
            <circle cx={cx - 14} cy={cy - 8} r="3" fill="#6b6754" />
            <circle cx={cx + 8} cy={cy + 12} r="4" fill="#6b6754" />
            <circle cx={cx - 5} cy={cy + 18} r="2" fill="#6b6754" />
            <circle cx={cx + 16} cy={cy - 14} r="2.5" fill="#6b6754" />
            <circle cx={cx + 2} cy={cy - 18} r="1.8" fill="#6b6754" />
          </g>
          {/* Clip craters to lit portion only */}
          <clipPath id="clipLit"><path d={litPath()} /></clipPath>
        </svg>
      </div>

      <div className="moonwidget__info">
        <div className="moonwidget__kicker mono">THE MOON TONIGHT</div>
        <div className="moonwidget__name">{name}</div>
        <div className="moonwidget__stats mono">
          <span>{Math.round(illumination * 100)}% LIT</span>
          <span className="moonwidget__dot">·</span>
          <span>DAY {Math.round(age)} OF 29</span>
          <span className="moonwidget__dot">·</span>
          <span>{waxing ? 'WAXING' : 'WANING'}</span>
        </div>
        <p className="moonwidget__tip">{tip}</p>

        <div className="moonwidget__features">
          <div className="moonwidget__features-label mono">MOON FEATURES TO LOG</div>
          <div className="moonwidget__feature-list">
            {moonObjects.map(o => {
              const isSeen = seenIds.has(o.id);
              return (
                <button
                  key={o.id}
                  className="moonwidget__feature"
                  data-seen={isSeen}
                  onClick={() => onPickMoonObject(o)}
                >
                  <span className="moonwidget__feature-dot" />
                  <span>{o.name}</span>
                  {isSeen && <span className="mono moonwidget__feature-tag">SEEN</span>}
                </button>
              );
            })}
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { MoonWidget });
