// ============================================================
// PDF preview — iframe-embedded multi-page A4 plan, scaled to fit
// the right column, synced to the active chapter AND fed the live
// plan so it reflects the editor's content as the doctor types.
// Zoom is adjustable (defaults to 60% on tablet, 80% on desktop)
// and persisted so it survives refreshes.
// ============================================================

const PDF_SRC = 'Plano%20de%20A%C3%A7%C3%A3o%20-%20PDF.html';
const ZOOM_KEY = 'blife.preview.zoom';
const ZOOM_STEPS = [0.5, 0.6, 0.75, 1.0];

function defaultZoom() {
  // Tablet landscape (≤1366px) reads best around 60%; desktop at 80%.
  if (typeof window !== 'undefined' && window.matchMedia && window.matchMedia('(max-width: 1366px)').matches) return 0.6;
  return 0.8;
}

function PreviewPanel({ active, plan }) {
  const iframeRef = React.useRef(null);
  const [ready, setReady] = React.useState(false);
  const [zoom, setZoom] = React.useState(() => {
    try { const v = parseFloat(localStorage.getItem(ZOOM_KEY)); if (v) return v; } catch (e) {}
    return defaultZoom();
  });

  const changeZoom = (z) => {
    setZoom(z);
    try { localStorage.setItem(ZOOM_KEY, String(z)); } catch (e) {}
  };

  // Wait for the iframe's bootstrap to announce it's ready.
  React.useEffect(() => {
    const onMsg = (e) => {
      const d = e.data || {};
      if (d.type === 'pdf-preview-ready') setReady(true);
    };
    window.addEventListener('message', onMsg);
    return () => window.removeEventListener('message', onMsg);
  }, []);

  // Push the plan to the iframe whenever it changes (or it becomes ready).
  // Also re-pin the preview to the chapter currently being edited once the
  // layout settles — so a chapter that only just gained a PDF page (e.g. after
  // importing an exam, or typing the final notes) scrolls into view.
  const activeRef = React.useRef(active);
  React.useEffect(() => { activeRef.current = active; }, [active]);

  React.useEffect(() => {
    if (!ready) return;
    const ifr = iframeRef.current;
    if (!ifr || !ifr.contentWindow) return;
    ifr.contentWindow.postMessage({ type: 'plan-update', plan }, '*');
    const t = setTimeout(() => {
      try { ifr.contentWindow.postMessage({ type: 'pdf-scroll-to-chapter', chapter: activeRef.current }, '*'); } catch (e) {}
    }, 350);
    return () => clearTimeout(t);
  }, [plan, ready]);

  // Scroll to the active chapter once the iframe is ready / the user switches.
  // Retry once after a short delay in case the page is still laying out.
  React.useEffect(() => {
    if (!ready) return;
    const ifr = iframeRef.current;
    if (!ifr || !ifr.contentWindow) return;
    const post = () => { try { ifr.contentWindow.postMessage({ type: 'pdf-scroll-to-chapter', chapter: active }, '*'); } catch (e) {} };
    post();
    const t = setTimeout(post, 220);
    return () => clearTimeout(t);
  }, [active, ready]);

  return (
    <div className="preview pdf-preview">
      <div className="pdf-toolbar">
        <span className="preview-head"><span className="dot" /> Preview do PDF</span>
        <div className="pdf-zoom">
          {ZOOM_STEPS.map(z => (
            <button
              key={z}
              className={'pdf-zoom-btn' + (Math.abs(zoom - z) < 0.001 ? ' active' : '')}
              onClick={() => changeZoom(z)}
            >{Math.round(z * 100)}%</button>
          ))}
        </div>
      </div>

      <div className="pdf-stage">
        <div
          className="pdf-stage-scale"
          style={{
            transform: `scale(${zoom})`,
            width: `${100 / zoom}%`,
            height: `${100 / zoom}%`,
          }}
        >
          <iframe
            ref={iframeRef}
            className="pdf-frame"
            src={PDF_SRC}
            title="Preview do PDF do plano de ação"
          />
        </div>
      </div>
    </div>
  );
}

window.PreviewPanel = PreviewPanel;
