// standalone.jsx — dedicated /event/<id> and /event/pack/<phaseId> pages.
//
// Each of these pages exists so Google can index one template (or starter
// pack) as its own document instead of a near-duplicate of the gallery at
// /events?template=... . They render nothing but the modal — no Header,
// Footer, or grid — on a plain page (see body.tb-standalone in styles.css).
//
// The gallery embeds these pages in an <iframe> when a card is clicked, so
// the same markup also has to behave as an embedded fragment: closing and
// "Use This Template" hand off to the parent window via postMessage instead
// of navigating in place, and it reports its own height so the parent can
// size the iframe to hug the card exactly.

const FLOWS_IMPORT_URL = "https://app.reelflow.com/dashboard/flows";
const EMBEDDED = window.self !== window.top;

// Tracks `track` (if given) and navigates to the flows importer for `slugs`.
// When embedded, both steps are handed off to the parent page instead of
// done here: the parent's GTM has been loaded since the gallery first
// opened, while this iframe's only started loading when the modal did, so
// firing+navigating here risks a fast click leaving before the hit sends.
// When visited directly there's no parent to hand off to, so a short delay
// stands in for that same margin.
function useTemplates(slugs, track) {
  const ids = (Array.isArray(slugs) ? slugs : [slugs]).filter(Boolean);
  if (!ids.length) return;
  if (EMBEDDED) {
    window.parent.postMessage({ type: "reelflow:useTemplate", ids: ids, track: track }, "*");
    return;
  }
  if (track && window.trackEvent) window.trackEvent(track.name, track.params);
  const url = FLOWS_IMPORT_URL + "?template_ids=" + ids.join(",");
  window.setTimeout(() => { window.location.href = url; }, 250);
}

function buildPackForPhase(phaseId) {
  const p = window.PHASES.find((x) => x.id === phaseId);
  if (!p) return null;
  const items = window.TEMPLATES.filter((t) => t.phase === phaseId);
  return {
    name: p.label + " Pack",
    phaseId: p.id,
    description: p.packDescription || p.job,
    window: p.window,
    templates: items,
    variants: items.slice(0, 3).map((t) => Math.max(0, Math.min(5, ((t.videos || []).length || 1) - 1)))
  };
}

function StandaloneModalPage({ page }) {
  const template = page.type === "template" ? window.TEMPLATES.find((t) => t.id === page.id) : null;
  const pack = page.type === "pack" ? buildPackForPhase(page.id) : null;
  const related = template ?
  window.TEMPLATES.filter((u) => u.id !== template.id && u.phase === template.phase).slice(0, 3) :
  [];

  const close = () => {
    if (EMBEDDED) window.parent.postMessage({ type: "reelflow:closeModal" }, "*");else
    window.location.href = page.backHref;
  };

  // Switching to a related template inside the modal: if we're embedded,
  // ask the parent to swap the iframe (keeps the overlay open); otherwise
  // just navigate — the related page is a sibling file in the same folder.
  const openRelated = (rt) => {
    if (EMBEDDED) window.parent.postMessage({ type: "reelflow:openTemplate", id: rt.id }, "*");else
    window.location.href = rt.id;
  };

  // Report content height to the parent so the iframe can hug the card
  // instead of showing a fixed-size window onto it.
  React.useEffect(() => {
    if (!EMBEDDED) return;
    const el = document.querySelector(".tb-modal");
    if (!el) return;
    const report = () => window.parent.postMessage({ type: "reelflow:modalHeight", height: el.offsetHeight }, "*");
    report();
    const ro = new ResizeObserver(report);
    ro.observe(el);
    return () => ro.disconnect();
  }, [page.type, page.id]);

  React.useEffect(() => {
    document.body.classList.add("tb-standalone");
    if (EMBEDDED) document.body.classList.add("tb-embedded");
  }, []);

  if (template) {
    return (
      <TemplateDetailModal
        template={{ ...template, variant: 0 }}
        onClose={close}
        related={related}
        onUse={() => useTemplates(template.slug, {
          name: "use_template_click",
          params: {
            template_id: template.id,
            template_title: template.title,
            source: EMBEDDED ? "template_modal" : "template_page"
          }
        })}
        onOpenRelated={openRelated} />);


  }
  if (pack) {
    return (
      <StarterPackModal
        pack={pack}
        onClose={close}
        onLoadAll={() => useTemplates((pack.templates || []).map((t) => t.slug), {
          name: "load_all_templates_click",
          params: {
            pack_id: pack.phaseId,
            pack_name: pack.name,
            template_count: (pack.templates || []).length,
            source: EMBEDDED ? "pack_modal" : "pack_page"
          }
        })} />);


  }
  return null;
}

ReactDOM.createRoot(document.getElementById("root")).render(<StandaloneModalPage page={window.__PAGE__} />);
