// @wuys/map · ui/overlays.js
//
// Premium UI overlays. All are opt-in and rendered as plain DOM (not SVG), so
// they don't interfere with the renderer's hot path.
//
// Includes:
//   • Theme picker (vector / antique / toon / pixel)
//   • View toggle (flat ↔ globe)
//   • Flag toggle
//   • Country search (with fly-to)
//   • FPS / draw-call readout (only with `perf: true`)
//   • ? help overlay listing shortcuts
//   • Renderer (CPU/GPU) selector
//
// Usage:
//   import { attachOverlays } from "@wuys/map/ui/overlays.js";
//   attachOverlays({ map, target, ui: { search: true, perf: false, help: true } });

import { ensureStyles } from "./styles.js";

export function attachOverlays({ map, target, ui = {} }) {
  ensureStyles();
  const overlay = document.createElement("div");
  overlay.className = "wuys-map-overlay";
  overlay.setAttribute("data-no-drag", "1");
  target.style.position = target.style.position || "relative";
  target.appendChild(overlay);

  // ---- Top-left: view + theme + flag controls --------------------------------
  const topL = el("div", "wuys-map-overlay-tl");
  overlay.appendChild(topL);

  if (ui.view !== false) {
    const btn = makeButton("🌍", "Toggle flat/globe view (G)", () => map.view.toggle());
    btn.dataset.role = "view-toggle";
    map.on("view:change", (mode) => { btn.textContent = mode === "globe" ? "🗺" : "🌍"; });
    topL.appendChild(btn);
  }
  if (ui.flags !== false) {
    const btn = makeButton("⚑", "Toggle flag fills (F)", () => map.theme.toggleFlags());
    topL.appendChild(btn);
  }
  if (ui.themes !== false) {
    const themeNames = Object.keys(map._internal ? (map._internal.themes || {}) : {});
    const sel = document.createElement("select");
    sel.className = "wuys-map-btn wuys-map-select";
    sel.title = "Theme";
    for (const k of (themeNames.length ? themeNames : ["vector","antique","toon","pixel"])) {
      const o = document.createElement("option");
      o.value = k; o.textContent = capitalize(k);
      sel.appendChild(o);
    }
    sel.value = map.theme.id;
    sel.addEventListener("change", () => map.theme.set(sel.value));
    map.on("theme:change", (id) => { sel.value = id; });
    topL.appendChild(sel);
  }

  // ---- Top-right: search + help ----------------------------------------------
  const topR = el("div", "wuys-map-overlay-tr");
  overlay.appendChild(topR);

  if (ui.search !== false) {
    const wrap = el("div", "wuys-map-search-wrap");
    const input = document.createElement("input");
    input.type = "search";
    input.placeholder = "Search country…";
    input.className = "wuys-map-search";
    wrap.appendChild(input);
    const results = el("div", "wuys-map-search-results");
    wrap.appendChild(results);
    topR.appendChild(wrap);

    let countries = [];
    function ensureIndex() {
      if (countries.length || !map.state.data.countries) return;
      for (const [iso, cm] of map.state.data.countries) {
        countries.push({ iso, name: cm.name || iso, lon: cm.lon, lat: cm.lat });
      }
      // Spotlights too
      for (const s of (map.state.data.spotlights || [])) {
        countries.push({ iso: s.iso, name: s.name, lon: s.lon, lat: s.lat });
      }
    }
    function render(matches) {
      results.innerHTML = "";
      for (const c of matches.slice(0, 8)) {
        const item = document.createElement("button");
        item.className = "wuys-map-search-item";
        item.textContent = c.name;
        item.addEventListener("click", () => {
          map.nav.flyTo({ lon: c.lon, lat: c.lat, zoom: 3.5 });
          results.innerHTML = "";
          input.value = "";
        });
        results.appendChild(item);
      }
    }
    input.addEventListener("input", () => {
      ensureIndex();
      const q = input.value.trim().toLowerCase();
      if (!q) { results.innerHTML = ""; return; }
      const matches = countries.filter(c => c.name.toLowerCase().includes(q) || c.iso.toLowerCase().includes(q));
      render(matches);
    });
    input.addEventListener("blur", () => { setTimeout(() => results.innerHTML = "", 250); });
  }

  if (ui.help !== false) {
    const btn = makeButton("?", "Keyboard shortcuts (?)", () => helpModal.classList.toggle("open"));
    topR.appendChild(btn);
    const helpModal = el("div", "wuys-map-help");
    helpModal.innerHTML = `
      <div class="wuys-map-help-card">
        <h3>Map shortcuts</h3>
        <ul>
          <li><kbd>↑ ↓ ← →</kbd> Pan (hold Shift = 3×, Ctrl = 6×)</li>
          <li><kbd>+</kbd> / <kbd>-</kbd> Zoom in / out</li>
          <li><kbd>Space</kbd> Reset view</li>
          <li><kbd>G</kbd> Toggle flat / globe</li>
          <li><kbd>F</kbd> Toggle flag fills</li>
          <li><kbd>?</kbd> This help</li>
        </ul>
        <button class="wuys-map-btn">Close</button>
      </div>`;
    overlay.appendChild(helpModal);
    helpModal.querySelector("button").addEventListener("click", () => helpModal.classList.remove("open"));
    map.on("help:toggle", () => helpModal.classList.toggle("open"));
  }

  // ---- Bottom-right: perf readout --------------------------------------------
  if (ui.perf) {
    const perf = el("div", "wuys-map-perf");
    overlay.appendChild(perf);
    let frames = 0, last = performance.now(), fps = 0;
    map.on("nav:change", () => {
      frames++;
      const now = performance.now();
      if (now - last > 500) {
        fps = Math.round(frames * 1000 / (now - last));
        frames = 0; last = now;
        perf.textContent = "fps " + fps + " · zoom " + map.nav.getCenter().zoom.toFixed(2);
      }
    });
  }

  // ---- Bottom-left: renderer (CPU/GPU) picker -------------------------------
  if (ui.rendererBadge !== false) {
    const wrap = el("div", "wuys-map-renderer-badge");
    const label = document.createElement("span");
    const sel = document.createElement("select");
    sel.className = "wuys-map-renderer-select";
    const renderers = (map.listRenderers && map.listRenderers()) || ["svg"];
    for (const id of renderers) {
      const o = document.createElement("option");
      o.value = id;
      const isGpu = id === "webgl";
      o.textContent = id + " (" + (isGpu ? "gpu" : "cpu") + ")";
      sel.appendChild(o);
    }
    sel.value = map.getRendererId ? map.getRendererId() : "svg";
    sel.title = "Switch renderer (CPU/GPU)";
    sel.addEventListener("change", async () => {
      const prev = sel.value;
      try {
        if (map.setRenderer) await map.setRenderer(sel.value);
      } catch (err) {
        console.warn("[wuys/map] renderer swap failed:", err);
      }
    });
    label.textContent = "renderer: ";
    wrap.appendChild(label);
    wrap.appendChild(sel);
    overlay.appendChild(wrap);
    map.on("renderer:change", (id) => { sel.value = id; });
    map.on("renderer:error", ({ id, err }) => {
      console.warn("[wuys/map] renderer error:", id, err);
      sel.value = map.getRendererId();
    });
  }

  return {
    destroy() { if (overlay.parentNode) overlay.parentNode.removeChild(overlay); },
    overlay,
  };
}

// ---- helpers ---------------------------------------------------------------

function el(tag, cls) { const e = document.createElement(tag); if (cls) e.className = cls; return e; }
function capitalize(s) { return s ? s.charAt(0).toUpperCase() + s.slice(1) : s; }
function makeButton(label, title, onClick) {
  const b = document.createElement("button");
  b.className = "wuys-map-btn";
  b.title = title;
  b.textContent = label;
  b.addEventListener("click", onClick);
  return b;
}
