import { useCallback, useEffect, useRef, useState } from 'react';
import { ExternalLink, Eye } from 'lucide-react';

export const SECTION_PREVIEW_ANCHORS = {
  hero: 'home',
  about: 'aboutus',
  certifications: 'certifications',
  services: 'services',
  whyUs: 'whyus',
  gallery: 'featured-gallery',
  products: 'products',
  insights: 'insights',
  footer: 'contactus',
};

export function buildPreviewContent(baseContent, section, sectionData) {
  if (!baseContent || !sectionData) return baseContent;

  const merged = { ...baseContent };

  if (section === 'hero') {
    merged.hero = sectionData.hero ?? merged.hero;
    merged.metrics = sectionData.metrics ?? merged.metrics;
  } else if (section === 'about') {
    merged.about = sectionData.about ?? merged.about;
    merged.partners = sectionData.partners ?? merged.partners;
  } else {
    merged[section] = sectionData;
  }

  return merged;
}

const PREVIEW_SRC = '/preview.html';
const PREVIEW_WIDTH = 1440;
const PREVIEW_HEIGHT = 900;

export function SectionPreview({ section, label, content, sectionData }) {
  const viewportRef = useRef(null);
  const iframeRef = useRef(null);
  const payloadRef = useRef({});
  const debounceRef = useRef(null);
  const anchor = SECTION_PREVIEW_ANCHORS[section] || 'home';
  const [scale, setScale] = useState(0.45);
  const [iframeReady, setIframeReady] = useState(false);
  const [previewReady, setPreviewReady] = useState(false);
  const [showIframe, setShowIframe] = useState(false);

  payloadRef.current = { content, sectionData, section, anchor };

  // Defer iframe mount so the editor form paints first
  useEffect(() => {
    const timer = window.setTimeout(() => setShowIframe(true), 50);
    return () => window.clearTimeout(timer);
  }, []);

  useEffect(() => {
    const onMessage = (event) => {
      if (event.origin !== window.location.origin) return;
      if (event.data?.type === 'PREVIEW_READY') setPreviewReady(true);
    };
    window.addEventListener('message', onMessage);
    return () => window.removeEventListener('message', onMessage);
  }, []);

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

    const updateScale = () => {
      const width = el.clientWidth;
      setScale(width > 0 ? width / PREVIEW_WIDTH : 0.45);
    };

    updateScale();
    const observer = new ResizeObserver(updateScale);
    observer.observe(el);
    return () => observer.disconnect();
  }, []);

  const postPreview = useCallback((immediate = false) => {
    const send = () => {
      const iframe = iframeRef.current;
      const { content: base, sectionData: data, section: sec, anchor: id } = payloadRef.current;
      if (!iframe?.contentWindow || !base || !data) return;

      iframe.contentWindow.postMessage(
        {
          type: 'ADMIN_PREVIEW',
          section: sec,
          anchor: id,
          fullContent: buildPreviewContent(base, sec, data),
        },
        window.location.origin,
      );
    };

    if (immediate) {
      window.clearTimeout(debounceRef.current);
      send();
      return;
    }

    window.clearTimeout(debounceRef.current);
    debounceRef.current = window.setTimeout(send, 200);
  }, []);

  useEffect(() => {
    if (!iframeReady) return;
    postPreview(true);
  }, [iframeReady, section, anchor, iframeReady, postPreview]);

  useEffect(() => {
    if (!iframeReady) return;
    postPreview(false);
    return () => window.clearTimeout(debounceRef.current);
  }, [content, sectionData, iframeReady, postPreview]);

  const handleIframeLoad = () => {
    setIframeReady(true);
    postPreview(true);
  };

  const isLoading = !showIframe || !iframeReady || !previewReady;

  return (
    <aside className="admin-preview-panel">
      <div className="admin-preview-panel-header">
        <div>
          <span className="admin-preview-eyebrow">
            <Eye size={14} />
            Live preview
          </span>
          <h3>{label}</h3>
        </div>
        <a
          href={`/#${anchor}`}
          target="_blank"
          rel="noopener noreferrer"
          className="admin-preview-open"
        >
          <ExternalLink size={13} />
          Open
        </a>
      </div>

      <div className="admin-preview-shell">
        <div className="admin-preview-chrome">
          <span className="admin-preview-dot" />
          <span className="admin-preview-dot" />
          <span className="admin-preview-dot" />
          <span className="admin-preview-url">/{anchor}</span>
        </div>
        <div
          className="admin-preview-viewport"
          ref={viewportRef}
          style={{ height: PREVIEW_HEIGHT * scale }}
        >
          {isLoading && (
            <div className="admin-preview-loading">
              <div className="admin-spinner" />
              <span>Loading preview…</span>
            </div>
          )}
          {showIframe && (
            <div
              className="admin-preview-stage"
              style={{ width: PREVIEW_WIDTH * scale, height: PREVIEW_HEIGHT * scale, opacity: isLoading ? 0 : 1 }}
            >
              <iframe
                ref={iframeRef}
                src={PREVIEW_SRC}
                title={`${label} preview`}
                className="admin-preview-iframe"
                onLoad={handleIframeLoad}
                style={{
                  width: PREVIEW_WIDTH,
                  height: PREVIEW_HEIGHT,
                  transform: `scale(${scale})`,
                }}
              />
            </div>
          )}
        </div>
      </div>
      <p className="admin-preview-note">Updates as you edit. Save to publish to the live site.</p>
    </aside>
  );
}
