"use client";

import { Component, useCallback, useEffect, useLayoutEffect, useRef, useState, type ReactNode } from "react";
import { PAGE_RENDERERS } from "@/app/(site)/_components/pages/renderers";
import type { SectionContext, SectionRenderers } from "@/app/(site)/_components/pages/render";
import { isPreviewMessage, type FromPreview, type ToPreview } from "@/app/(site)/_lib/previewProtocol";

type State = Extract<ToPreview, { type: "cms-preview:state" }>;
type Box = { top: number; left: number; width: number; height: number };

const post = (m: FromPreview) => window.parent.postMessage(m, location.origin);

/**
 * Sections render inside wrappers with display: contents (no box, so the page's
 * layout and CSS selectors are unchanged). A section's area is the union of its
 * children's boxes.
 */
function boxOf(el: Element): Box | null {
  let top = Infinity, left = Infinity, right = -Infinity, bottom = -Infinity;
  for (const c of Array.from(el.children)) {
    const r = c.getBoundingClientRect();
    if (!r.width && !r.height) continue;
    top = Math.min(top, r.top);
    left = Math.min(left, r.left);
    right = Math.max(right, r.right);
    bottom = Math.max(bottom, r.bottom);
  }
  if (top === Infinity) return null;
  return { top: top + scrollY, left: left + scrollX, width: right - left, height: bottom - top };
}

/** Calls the renderer while rendering, so errors in it reach the boundary around it. */
function Render({ render, content, ctx }: { render: SectionRenderers[string]; content: unknown; ctx: SectionContext }) {
  return <>{render(content, ctx)}</>;
}

/** Content being edited can be incomplete (a list without items, an image without a URL…). */
class SectionBoundary extends Component<{ resetKey: unknown; children: ReactNode }, { failed: boolean }> {
  state = { failed: false };
  static getDerivedStateFromError() {
    return { failed: true };
  }
  componentDidUpdate(prev: { resetKey: unknown }) {
    if (prev.resetKey !== this.props.resetKey && this.state.failed) this.setState({ failed: false });
  }
  render() {
    if (!this.state.failed) return this.props.children;
    return (
      <section style={{ padding: "48px 24px", textAlign: "center", background: "#fff7ed", color: "#9a3412", font: "500 15px/1.6 system-ui, sans-serif", borderTop: "1px dashed #fdba74", borderBottom: "1px dashed #fdba74" }}>
        This section can&apos;t be shown yet: fill in its required fields.
      </section>
    );
  }
}

/** The live preview of one inner page, driven by the admin page editor (see previewProtocol). */
export function PreviewFrame({ pageKey }: { pageKey: string }) {
  const page = PAGE_RENDERERS[pageKey];
  const [state, setState] = useState<State | null>(null);
  const rootRef = useRef<HTMLDivElement>(null);
  const [boxes, setBoxes] = useState<Record<string, Box>>({});

  const sectionEl = (key: string) => rootRef.current?.querySelector(`[data-s="${CSS.escape(key)}"]`) ?? null;

  useEffect(() => {
    const onMessage = (e: MessageEvent) => {
      if (e.origin !== location.origin || e.source !== window.parent || !isPreviewMessage(e.data)) return;
      const m = e.data as ToPreview;
      if (m.type === "cms-preview:state") setState(m);
      else if (m.type === "cms-preview:reveal") {
        const el = sectionEl(m.key);
        const b = el && boxOf(el);
        if (b) post({ type: "cms-preview:top", key: m.key, top: b.top });
      }
    };
    addEventListener("message", onMessage);
    post({ type: "cms-preview:ready" });
    return () => removeEventListener("message", onMessage);
  }, []);

  // A click selects the section in the editor. Links, buttons and forms do nothing here.
  useEffect(() => {
    const onClick = (e: MouseEvent) => {
      e.preventDefault();
      const key = (e.target as Element | null)?.closest?.("[data-s]")?.getAttribute("data-s");
      if (key) post({ type: "cms-preview:select", key });
    };
    const stop = (e: Event) => e.preventDefault();
    document.addEventListener("click", onClick, true);
    document.addEventListener("submit", stop, true);
    return () => {
      document.removeEventListener("click", onClick, true);
      document.removeEventListener("submit", stop, true);
    };
  }, []);

  // Section areas (selection outline, "unsaved" badges) and the page height for the editor.
  const measure = useCallback(() => {
    const root = rootRef.current;
    if (!root) return;
    const next: Record<string, Box> = {};
    root.querySelectorAll("[data-s]").forEach((el) => {
      const b = boxOf(el);
      if (b) next[el.getAttribute("data-s")!] = b;
    });
    setBoxes(next);
    post({ type: "cms-preview:height", height: Math.ceil(root.getBoundingClientRect().height) });
  }, []);
  useLayoutEffect(measure, [state, measure]);
  useEffect(() => {
    const root = rootRef.current;
    if (!root) return;
    const ro = new ResizeObserver(measure);
    ro.observe(root);
    return () => ro.disconnect();
  }, [measure]);

  const selected = state?.selected ? boxes[state.selected] : undefined;

  return (
    <>
      {/* Scroll animations would leave sections below the fold invisible: show everything as revealed. */}
      <style>{`html,body{overflow:hidden}[data-reveal]{opacity:1!important;transform:none!important;transition:none!important}[data-s]{cursor:pointer}[data-s]:hover>*{outline:3px solid rgba(11,87,208,.35);outline-offset:-3px}`}</style>
      <div ref={rootRef} lang={state?.lang} dir={state?.dir} style={{ display: "flow-root" }}>
        <div className={page?.className} style={{ display: "contents" }}>
          <main id="main">
            {page &&
              state?.sections.map((s, index) => {
                const render = page.sections[s.key];
                if (!render) return null;
                return (
                  <div key={s.key} data-s={s.key} style={{ display: "contents" }}>
                    <SectionBoundary resetKey={s.content}>
                      <Render render={render} content={s.content} ctx={{ sections: state.sections, index, preview: true }} />
                    </SectionBoundary>
                  </div>
                );
              })}
          </main>
        </div>
      </div>
      {selected && (
        <div
          aria-hidden="true"
          style={{ position: "absolute", ...px(selected), outline: "3px solid #0b57d0", outlineOffset: -3, pointerEvents: "none", zIndex: 2147483646 }}
        />
      )}
      {state?.sections
        .filter((s) => s.dirty && boxes[s.key])
        .map((s) => (
          <span
            key={s.key}
            aria-hidden="true"
            style={{ position: "absolute", top: boxes[s.key].top + 10, left: boxes[s.key].left + boxes[s.key].width - 130, width: 120, textAlign: "center", padding: "4px 0", borderRadius: 6, background: "#f59e0b", color: "#fff", font: "600 12px/1.4 system-ui, sans-serif", pointerEvents: "none", zIndex: 2147483647 }}
          >
            Unsaved edits
          </span>
        ))}
    </>
  );
}

const px = (b: Box) => ({ top: b.top, left: b.left, width: b.width, height: b.height });
