/* Embedded static pages (Home navy, Médicos, Programa Lealtad)
 * Renders the original hand-built HTML with its CSS scoped under a wrapper
 * class so it can't collide with styles.css. Internal links carry data-nav
 * and are routed through the SPA navigate().
 */

function EmbeddedPage({ data, scope, navigate, onMount }) {
  const ref = React.useRef(null);

  React.useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const onClick = (e) => {
      const a = e.target.closest("[data-nav]");
      if (a && el.contains(a)) {
        e.preventDefault();
        navigate(a.getAttribute("data-nav"));
        window.scrollTo({ top: 0, behavior: "instant" });
      }
    };
    el.addEventListener("click", onClick);
    const cleanup = onMount ? onMount(el) : null;
    return () => { el.removeEventListener("click", onClick); if (cleanup) cleanup(); };
  }, [data, navigate, onMount]);

  if (!data) return null;
  return (
    <React.Fragment>
      <style>{data.css}</style>
      <div className={scope} ref={ref} dangerouslySetInnerHTML={{ __html: data.html }} />
    </React.Fragment>
  );
}

/* Home "audiencias" tabs behavior */
function initHomeTabs(el) {
  const tabs = el.querySelector("#tabs");
  if (!tabs) return null;
  const handler = (e) => {
    const btn = e.target.closest(".tab");
    if (!btn) return;
    const key = btn.getAttribute("data-tab");
    el.querySelectorAll("#tabs .tab").forEach(t => t.classList.toggle("active", t === btn));
    el.querySelectorAll(".panel").forEach(p => p.classList.toggle("active", p.id === "panel-" + key));
  };
  tabs.addEventListener("click", handler);
  return () => tabs.removeEventListener("click", handler);
}

function HomeNavy({ navigate }) {
  return <EmbeddedPage data={window.EMBED_HOME} scope="embed-home" navigate={navigate} onMount={initHomeTabs} />;
}
function MedicosNavy({ navigate }) {
  return <EmbeddedPage data={window.EMBED_MEDICOS} scope="embed-medicos" navigate={navigate} />;
}
function LealtadPage({ navigate }) {
  return <EmbeddedPage data={window.EMBED_LEALTAD} scope="embed-lealtad" navigate={navigate} />;
}

Object.assign(window, { EmbeddedPage, HomeNavy, MedicosNavy, LealtadPage });
