// Edit-mode bridge for the visual builder. Loaded before HomePage.jsx.
// Completely inert unless the page URL carries ?edit=1 — the public site is unaffected.
//
// Responsibilities in edit mode:
//   • expose window.EDIT_MODE, window.EditSection, window.Editable for HomePage/shared to use
//   • capture clicks on the live page → resolve which section / item was hit → postMessage the
//     selection to the parent builder frame (and paint a selection outline)
//   • block link navigation so clicking a CTA selects it instead of navigating away
//   • listen for host messages: refresh (re-fetch CMS data), scrollTo, setLang
//   • report inline text edits (contentEditable) back to the host on blur

(function () {
  const EDIT_MODE = new URLSearchParams(window.location.search).has('edit');
  window.EDIT_MODE = EDIT_MODE;

  function postToHost(msg) {
    if (window.parent && window.parent !== window) {
      window.parent.postMessage({ __builder: true, ...msg }, '*');
    }
  }
  window.postToHost = postToHost;

  // ---- Non-edit mode: EditSection / Editable are transparent passthroughs -------------------
  if (!EDIT_MODE) {
    window.EditSection = ({ children }) => children;
    window.EditItem = ({ children }) => children;
    window.Editable = ({ tag = 'span', value, children, style, className }) =>
      React.createElement(tag, { style, className }, children != null ? children : value);
    return;
  }

  // ---- Edit mode --------------------------------------------------------------------------
  document.documentElement.setAttribute('data-edit-mode', '1');

  // Injected chrome: hover + selection outlines and a floating type badge.
  const style = document.createElement('style');
  style.textContent = `
    [data-edit-id], [data-edit-item] { cursor: pointer; }
    [data-edit-id]:hover { outline: 1.5px dashed var(--accent-gold, #C9A24B); outline-offset: -1px; }
    [data-edit-item]:hover { outline: 1.5px dashed var(--accent-gold, #C9A24B); outline-offset: -2px; }
    .eb-selected { outline: 2px solid var(--accent-gold, #C9A24B) !important; outline-offset: -1px; position: relative; }
    .eb-selected::after {
      content: attr(data-eb-label); position: absolute; top: 0; left: 0;
      transform: translateY(-100%); background: var(--accent-gold, #C9A24B); color: #fff;
      font: 600 11px/1.6 system-ui, sans-serif; letter-spacing: .04em; text-transform: uppercase;
      padding: 1px 8px; border-radius: 3px 3px 0 0; white-space: nowrap; z-index: 60; pointer-events: none;
    }
    [contenteditable="true"]:focus { outline: 2px solid var(--accent-gold, #C9A24B); outline-offset: 2px; border-radius: 2px; }
    [contenteditable="true"]:hover { background: color-mix(in srgb, var(--accent-gold, #C9A24B) 10%, transparent); }
  `;
  document.head.appendChild(style);

  let selectedEl = null;
  function clearSelection() {
    if (selectedEl) { selectedEl.classList.remove('eb-selected'); selectedEl.removeAttribute('data-eb-label'); }
    selectedEl = null;
  }
  function paintSelection(el, label) {
    clearSelection();
    if (!el) return;
    el.classList.add('eb-selected');
    if (label) el.setAttribute('data-eb-label', label);
    selectedEl = el;
  }
  window.__ebSelect = paintSelection; // used by scrollTo handler

  // Single delegated click handler — resolves the hit section/item from data-* attributes.
  document.addEventListener('click', (e) => {
    // Let inline text editors handle their own clicks.
    if (e.target.closest('[contenteditable="true"]')) return;

    const link = e.target.closest('a');
    if (link) e.preventDefault(); // never navigate away inside the editor

    const itemEl = e.target.closest('[data-edit-item]');
    const secEl = e.target.closest('[data-edit-id]');
    if (!secEl && !itemEl) return;

    // Always ring the section (a visible block); item wrappers use display:contents (no box).
    const paintEl = secEl || itemEl;
    const label = secEl ? (secEl.getAttribute('data-edit-type') || 'section') : (itemEl.getAttribute('data-edit-table') || 'item');
    paintSelection(paintEl, label);

    postToHost({
      type: 'select',
      sectionId: secEl ? secEl.getAttribute('data-edit-id') : null,
      sectionType: secEl ? secEl.getAttribute('data-edit-type') : null,
      item: itemEl
        ? { table: itemEl.getAttribute('data-edit-table'), id: itemEl.getAttribute('data-edit-item') }
        : null,
    });
  }, true);

  // Host → iframe messages.
  window.addEventListener('message', (e) => {
    const d = e.data;
    if (!d || !d.__builderHost) return;
    if (d.type === 'refresh') {
      window.dispatchEvent(new CustomEvent('cms-refresh'));
    } else if (d.type === 'setLang') {
      window.dispatchEvent(new CustomEvent('set-lang', { detail: d.lang }));
    } else if (d.type === 'navigate') {
      // Host page switcher (home ↔ gallery). Hash routing — no reload.
      window.location.hash = d.hash || '#/';
      clearSelection();
    } else if (d.type === 'scrollTo') {
      const el = document.querySelector(`[data-edit-id="${d.sectionId}"]`);
      if (el) {
        el.scrollIntoView({ behavior: 'smooth', block: 'start' });
        paintSelection(el, el.getAttribute('data-edit-type'));
      }
    } else if (d.type === 'clearSelection') {
      clearSelection();
    }
  });

  postToHost({ type: 'ready' });

  // ---- Editable wrappers used by HomePage / shared ----------------------------------------

  // Wraps a whole section so the delegated handler can resolve it. Plain block wrapper —
  // sections use padding/auto-margins internally, so an extra block div is layout-safe.
  window.EditSection = function EditSection({ type, id, children }) {
    return React.createElement('div', { 'data-edit-id': id, 'data-edit-type': type }, children);
  };

  // Tags a repeatable card. display:contents keeps layout identical; clicks still resolve via
  // closest('[data-edit-item]'), and the section ring provides the visible selection feedback.
  window.EditItem = function EditItem({ table, id, children }) {
    return React.createElement('div', { 'data-edit-item': id, 'data-edit-table': table, style: { display: 'contents' } }, children);
  };

  // In-place text editor for copy we own (headings, subtitle, legal). Posts on blur.
  window.Editable = function Editable({ tag = 'span', table = 'sections', id, field, value, style, className }) {
    const ref = React.useRef(null);
    // Keep DOM text in sync when value changes from outside (e.g. language switch) but not while focused.
    React.useEffect(() => {
      if (ref.current && document.activeElement !== ref.current) {
        ref.current.textContent = value != null ? value : '';
      }
    }, [value]);
    return React.createElement(tag, {
      ref,
      className,
      style,
      contentEditable: true,
      suppressContentEditableWarning: true,
      spellCheck: false,
      'data-edit-field': field,
      onClick: (e) => e.stopPropagation(),
      onBlur: (e) => {
        const next = e.currentTarget.textContent;
        if (next !== value) postToHost({ type: 'edit', table, id, field, value: next });
      },
      onKeyDown: (e) => {
        if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); e.currentTarget.blur(); }
      },
    }, value);
  };
})();
