"use client";

import { useEffect, useRef, useState } from "react";

/**
 * SVGNest panel – same-origin iframe wrapper (clean, frameless).
 * Also hides the legacy page’s heading/tagline for a minimal look.
 */
export default function SVGNestPanel() {
    const iframeRef = useRef<HTMLIFrameElement | null>(null);
    const [ready, setReady] = useState(false);
    const [err, setErr] = useState<string | null>(null);

    useEffect(() => {
        const el = iframeRef.current;
        if (!el) return;

        const onLoad = () => {
            setReady(true);

            // Hide the legacy heading/tagline inside svgnest without touching the vendor files.
            try {
                const doc = el.contentDocument;
                if (!doc) return;

                // 1) Hide the first H1 (their title)
                const h1 = doc.querySelector("h1");
                if (h1) (h1 as HTMLElement).style.display = "none";

                // 2) Hide any node that literally contains that tagline text
                const all = Array.from(doc.querySelectorAll<HTMLElement>("body *"));
                for (const n of all) {
                    const t = (n.textContent || "").trim().toLowerCase();
                    if (t.includes("automatically nests parts") && t.includes("exports svg")) {
                        n.style.display = "none";
                    }
                }

                // 3) Optional: tighten top padding/margins so content sits snugly
                (doc.body as HTMLElement).style.marginTop = "4px";
            } catch {
                // ignore; same-origin so this should succeed
            }
        };

        const onError = () => setErr("Failed to load /svgnest/index.html");

        el.addEventListener("load", onLoad);
        el.addEventListener("error", onError);
        return () => {
            el.removeEventListener("load", onLoad);
            el.removeEventListener("error", onError);
        };
    }, []);

    return (
        <div className="w-full">
        {!ready && !err && (
            <div className="mb-2 text-sm text-zinc-400">Loading SVGnest…</div>
        )}
        {err && (
            <div className="mb-2 rounded border border-rose-600/40 bg-rose-600/10 p-3 text-sm">
            Couldn’t load SVGnest: {err}
            </div>
        )}

        {/* Frameless iframe (no border, no wrapper frame) */}
        <iframe
        ref={iframeRef}
        src="/svgnest/index.html"
        title="SVGNest"
        className="w-full"
        style={{ height: "72vh", background: "transparent", border: "none" }}
        />
        </div>
    );
}
