/* FINAZ · Catálogo estético — PASARELA.
   Shell a pantalla completa: una dirección por pantalla, navegación por
   flechas/teclado, riel de índice, ficha curatorial y lectura al hover.
   El gráfico (línea FNX 50) es el mismo en todas; cambia el renderizador. */
(function () {
  "use strict";
  const e = React.createElement;
  const { useState, useEffect, useRef, useCallback } = React;
  const C = window.FZCORE;
  const { VBW, VBH, PAD } = C;

  function App() {
    const data = window.FINAZ_DATA;
    const DIRS = window.FINAZ_DIRECTIONS;
    const RENDER = window.FZRENDERERS;
    const G = C.useGeom(data.points);

    const [idx, setIdx] = useState(() => {
      const s = +localStorage.getItem("finaz-cat-idx");
      return Number.isFinite(s) && s >= 0 && s < DIRS.length ? s : 0;
    });
    const [focus, setFocus] = useState(null);
    const dir = DIRS[idx];
    const T = dir.tokens;
    const intro = C.useIntro(dir.id + ":" + idx, 1600);

    useEffect(() => { localStorage.setItem("finaz-cat-idx", idx); setFocus(null); }, [idx]);

    // gancho de navegación determinista (export PPTX / control externo)
    useEffect(() => { window.__finazGoTo = (n) => setIdx(((n % DIRS.length) + DIRS.length) % DIRS.length); return () => { delete window.__finazGoTo; }; }, [DIRS.length]);

    const go = useCallback((d) => setIdx((i) => (i + d + DIRS.length) % DIRS.length), [DIRS.length]);
    useEffect(() => {
      const onKey = (ev) => {
        if (ev.key === "ArrowRight") go(1);
        else if (ev.key === "ArrowLeft") go(-1);
      };
      window.addEventListener("keydown", onKey);
      return () => window.removeEventListener("keydown", onKey);
    }, [go]);

    // ---- hover sobre el gráfico ----
    const svgRef = useRef(null);
    const onMove = useCallback((ev) => {
      const r = svgRef.current.getBoundingClientRect();
      const sx = (ev.clientX - r.left) * (VBW / r.width);
      const k = (sx - PAD.l) / (VBW - PAD.l - PAD.r);
      const i = Math.max(0, Math.min(G.n - 1, Math.round(k * (G.n - 1))));
      setFocus(i);
    }, [G.n]);
    const onLeave = useCallback(() => setFocus(null), []);

    const Renderer = RENDER[dir.render];
    const focusPt = focus == null ? null : G.pts[focus];
    const m = data.meta, up = m.changeAbs >= 0;
    const liveVal = focus == null ? m.last : data.points[focus].v;

    const cssVars = {
      "--ink": T.ink, "--sub": T.sub, "--faint": T.faint, "--accent": T.accent,
      "--accent2": T.accent2, "--accent3": T.accent3, "--edge": T.edge,
      "--pos": T.pos, "--neg": T.neg, "--glow": T.glow,
      "--fdisplay": dir.fonts.display, "--fbody": dir.fonts.body, "--fmono": dir.fonts.mono,
      background: T.bgGrad && T.bgGrad !== "none" ? T.bgGrad : T.bg,
      backgroundColor: T.bg, color: T.ink, fontFamily: dir.fonts.body,
    };

    // etiquetas de tiempo (eje)
    const ticks = [0, 0.25, 0.5, 0.75, 1].map((f) => {
      const i = Math.round(f * (G.n - 1));
      return { x: PAD.l + f * (VBW - PAD.l - PAD.r), t: data.points[i].t };
    });

    return e("div", { className: "cat-root", style: cssVars, "data-screen-label": dir.n },
      e("div", { className: "cat-grain" }),

      // ---------- CABECERA ----------
      e("header", { className: "cat-top" },
        e("div", { className: "cat-brand" },
          e("span", { className: "cat-logo" }, "FINAZ"),
          e("span", { className: "cat-lab" }, "Catálogo estético · Línea FNX 50")),
        e("div", { className: "cat-counter" },
          e("span", { className: "cat-cnow" }, dir.n),
          e("span", { className: "cat-ctot" }, "/ " + String(DIRS.length).padStart(2, "0")))),

      // ---------- ESCENARIO ----------
      e("main", { className: "cat-stage" },
        // --- gráfico ---
        e("section", { className: "cat-chartwrap", key: "c" + idx },
          e("div", { className: "cat-symrow" },
            e("div", { className: "cat-sym" },
              e("strong", null, m.symbol),
              e("span", null, m.name)),
            e("div", { className: "cat-price" },
              e("span", { className: "cat-pv" }, liveVal.toLocaleString("es-ES")),
              e("span", { className: "cat-unit" }, m.currency),
              e("span", { className: "cat-chg " + (up ? "pos" : "neg") },
                (up ? "▲ +" : "▼ ") + m.changeAbs + " (" + (up ? "+" : "") + m.changePct + "%)"))),
          e("div", { className: "cat-canvasbox" },
            // capa de partículas (cinética)
            e(C.ParticleCanvas, { key: "p" + idx, mode: dir.particle, palette: [T.accent, T.accent2, T.accent3], geom: G, active: idx }),
            // SVG del gráfico
            e("svg", { ref: svgRef, className: "cat-svg", viewBox: "0 0 " + VBW + " " + VBH,
              onPointerMove: onMove, onPointerLeave: onLeave },
              // eje temporal tenue
              e("g", { opacity: 0.55 },
                ticks.map((tk, i) => e("text", { key: i, x: tk.x, y: VBH - PAD.b + 30, textAnchor: "middle", fontFamily: dir.fonts.mono, fontSize: 13, fill: T.faint, letterSpacing: ".06em" }, tk.t)),
                e("line", { x1: PAD.l, x2: VBW - PAD.r, y1: VBH - PAD.b + 4, y2: VBH - PAD.b + 4, stroke: T.faint, strokeWidth: 0.6, opacity: 0.4 })),
              // renderizador de la dirección
              Renderer ? e(Renderer, { G, T, fonts: dir.fonts, chart: dir.chart, intro, id: dir.id }) : null,
              // lectura al hover
              intro > 0.9 && e(C.HoverReadout, { pt: focusPt, T, fonts: dir.fonts, open: m.open })))),

        // --- ficha curatorial ---
        e("aside", { className: "cat-caption", key: "cap" + idx },
          e("div", { className: "cat-cap-k" }, "Dirección " + dir.n + " · de 10"),
          e("div", { className: "cat-artist" }, dir.artist),
          e("div", { className: "cat-work" }, dir.work),
          e("h1", { className: "cat-title" }, dir.title),
          e("p", { className: "cat-tagline" }, dir.tagline),
          e("p", { className: "cat-apply" }, dir.apply),
          e("div", { className: "cat-palette" },
            [["bg", T.bg], ["acento", T.accent], ["", T.accent2], ["", T.accent3]].map(([lab, col], i) =>
              e("span", { key: i, className: "cat-sw", style: { background: col }, title: col })),
            e("span", { className: "cat-palette-lab" }, "paleta")))),

      // ---------- RIEL DE ÍNDICE ----------
      e("footer", { className: "cat-rail" },
        e("button", { className: "cat-arrow", onClick: () => go(-1), "aria-label": "Anterior" }, "←"),
        e("div", { className: "cat-dots" },
          DIRS.map((d, i) =>
            e("button", { key: d.id, className: "cat-dot" + (i === idx ? " on" : ""), onClick: () => setIdx(i), title: d.artist },
              e("span", { className: "cat-dot-n" }, d.n),
              e("span", { className: "cat-dot-name" }, d.artist.split(" ")[0])))),
        e("button", { className: "cat-arrow", onClick: () => go(1), "aria-label": "Siguiente" }, "→")),

      // flechas laterales grandes
      e("button", { className: "cat-side cat-side-l", onClick: () => go(-1), "aria-label": "Anterior" }, "‹"),
      e("button", { className: "cat-side cat-side-r", onClick: () => go(1), "aria-label": "Siguiente" }, "›"));
  }

  window.FinazCatalog = App;
})();
