const CONSTELLATION_TINTS = [
  "#ffd66b",
  "#9ad7ff",
  "#ffb1d4",
  "#b9ffce",
  "#d9b6ff",
];
function useConstellations() {
  const [list, setList] = useState(() => {
    try {
      const raw = localStorage.getItem("planets_constellations");
      const arr = raw ? JSON.parse(raw) : [];
      return Array.isArray(arr) ? arr : [];
    } catch {
      return [];
    }
  });
  const writeStorage = (next) => {
    try {
      localStorage.setItem("planets_constellations", JSON.stringify(next));
    } catch {}
  };
  return {
    list,
    add: (c) =>
      setList((current) => {
        const next = [...current, c];
        writeStorage(next);
        return next;
      }),
    remove: (id) =>
      setList((current) => {
        const next = current.filter((c) => c.id !== id);
        writeStorage(next);
        return next;
      }),
    clear: () =>
      setList(() => {
        writeStorage([]);
        return [];
      }),
  };
}

function ConstellationOverlay({ constellations }) {
  if (!constellations.length) return null;
  return (
    <svg
      className="constellation-overlay"
      viewBox="0 0 100 100"
      preserveAspectRatio="none"
      style={{
        filter:
          "drop-shadow(0 0 1.5px rgba(255,255,255,0.55)) drop-shadow(0 0 3px rgba(255,214,107,0.28))",
      }}
    >
      {constellations.map((c, idx) => {
        const tint = CONSTELLATION_TINTS[idx % CONSTELLATION_TINTS.length];
        const pts = c.points;
        if (!pts || pts.length < 2) return null;
        const d = pts
          .map((p, i) => `${i === 0 ? "M" : "L"} ${p.x} ${p.y}`)
          .join(" ");
        const cx = pts.reduce((a, p) => a + p.x, 0) / pts.length;
        const cy = pts.reduce((a, p) => a + p.y, 0) / pts.length;
        return (
          <g key={c.id}>
            <path
              d={d}
              fill="none"
              stroke={tint}
              strokeOpacity="0.78"
              strokeWidth="1.2"
              strokeLinecap="round"
              strokeLinejoin="round"
            />
            {pts.map((p, i) => (
              <circle
                key={i}
                cx={p.x}
                cy={p.y}
                r="3"
                fill={tint}
                opacity="0.95"
              />
            ))}
            {c.name ? (
              <text
                x={cx}
                y={cy}
                fill={tint}
                fontSize="11"
                opacity="0.92"
                textAnchor="middle"
                dy="-8"
                style={{
                  fontFamily: "Inter, sans-serif",
                  fontWeight: 600,
                  paintOrder: "stroke fill",
                  stroke: "rgba(8,4,18,0.78)",
                  strokeWidth: "0.6px",
                  strokeLinejoin: "round",
                }}
              >
                {c.name}
              </text>
            ) : null}
          </g>
        );
      })}
    </svg>
  );
}

function ConstellationDrawLayer({ active, onFinish, onCancel }) {
  const [points, setPoints] = useState([]);
  const ref = useRef(null);
  if (!active) return null;
  const handleClick = (e) => {
    const rect = e.currentTarget.getBoundingClientRect();
    const x = ((e.clientX - rect.left) / rect.width) * 100;
    const y = ((e.clientY - rect.top) / rect.height) * 100;
    setPoints((pts) => [...pts, { x, y }]);
  };
  const finish = () => {
    if (points.length < 2) {
      onCancel();
      return;
    }
    onFinish({
      id: "c" + Date.now(),
      name: "",
      points,
    });
    setPoints([]);
  };
  const undo = () => setPoints((pts) => pts.slice(0, -1));
  const cancel = () => {
    setPoints([]);
    onCancel();
  };
  const d = points
    .map((p, i) => `${i === 0 ? "M" : "L"} ${p.x} ${p.y}`)
    .join(" ");
  return (
    <div
      ref={ref}
      className="constellation-draw"
      onClick={handleClick}
      onContextMenu={(e) => {
        e.preventDefault();
        finish();
      }}
    >
      <svg
        className="constellation-draw-svg"
        viewBox="0 0 100 100"
        preserveAspectRatio="none"
        style={{
          filter:
            "drop-shadow(0 0 2px rgba(255,214,107,0.55)) drop-shadow(0 0 5px rgba(255,214,107,0.32))",
        }}
      >
        {points.length > 1 ? (
          <path
            d={d}
            fill="none"
            stroke="#ffd66b"
            strokeOpacity="0.95"
            strokeWidth="1.4"
            strokeLinecap="round"
            strokeLinejoin="round"
          />
        ) : null}
        {points.map((p, i) => (
          <circle key={i} cx={p.x} cy={p.y} r="3.4" fill="#ffd66b" />
        ))}
      </svg>
      <div
        className="constellation-toolbar"
        onClick={(e) => e.stopPropagation()}
      >
        <span className="constellation-tip">
          Tap stars · {points.length} placed
        </span>
        <button className="btn-icon" onClick={undo} disabled={!points.length}>
          Back one
        </button>
        <button className="btn-icon" onClick={cancel}>
          Cancel
        </button>
        <button className="btn-tour on" onClick={finish}>
          Save stars
        </button>
      </div>
    </div>
  );
}
