"use client";

import { useEffect, useRef } from "react";

/**
 * Renders a page's ported markup + CSS exactly as extracted from the
 * original HTML, and re-executes its original inline <script> content.
 *
 * The script is injected as a real <script> DOM node (so it actually runs,
 * unlike innerHTML) and synthetic `DOMContentLoaded` (on document) and
 * `load` (on window) events are dispatched right after — the source pages
 * use both `document.addEventListener('DOMContentLoaded', ...)` and
 * `window.addEventListener('load', ...)` (e.g. the preloader), and by the
 * time this effect runs both real events have long since fired.
 *
 * React Strict Mode (dev) remounts effects without remounting the HTML:
 * cleanup only removes the <script> tag, so a second run would attach every
 * addEventListener again (e.g. OTP send fires twice). We skip re-binding
 * when the same scriptJs is already active on this mount.
 */
export default function LegacyBody({
  styleCss,
  bodyHtml,
  scriptJs,
}: {
  styleCss: string;
  bodyHtml: string;
  scriptJs: string;
}) {
  const scriptHolder = useRef<HTMLScriptElement | null>(null);
  const boundScriptJs = useRef<string | null>(null);

  useEffect(() => {
    if (!scriptJs) return;
    if (boundScriptJs.current === scriptJs) return;
    boundScriptJs.current = scriptJs;

    const script = document.createElement("script");
    script.textContent = scriptJs;
    document.body.appendChild(script);
    scriptHolder.current = script;
    document.dispatchEvent(
      new Event("DOMContentLoaded", { bubbles: true, cancelable: true })
    );
    window.dispatchEvent(new Event("load"));
    // Ensure legacy preloaders don't stick if their hide timer missed.
    window.setTimeout(() => {
      document.querySelectorAll(".preloader").forEach((el) => {
        el.classList.add("hidden");
      });
    }, 1600);
    return () => {
      if (scriptHolder.current?.parentNode) {
        scriptHolder.current.parentNode.removeChild(scriptHolder.current);
      }
      scriptHolder.current = null;
      // Do not clear boundScriptJs here — Strict Mode cleanup runs before the
      // second effect on the same DOM, and clearing would re-bind listeners.
    };
  }, [scriptJs]);

  return (
    <>
      {styleCss ? <style dangerouslySetInnerHTML={{ __html: styleCss }} /> : null}
      <div dangerouslySetInnerHTML={{ __html: bodyHtml }} />
    </>
  );
}
