// ============================================================
// Persist — save typed values to localStorage and restore them
// when DOM re-mounts (FO↔PO toggle) or the page reloads.
//
// Key scheme:
//   scope :: placeholder :: ordinal
//   - scope = current .party-block's role label + active variant (FO/PO/SZCO),
//             or the article id if the field lives outside a party-block.
//   - ordinal = index among siblings in the same scope that share the same placeholder.
//
// This means FO and PO inside the same party have different scopes,
// so switching FO→PO→FO restores the FO data without collisions.
// ============================================================

(function () {
  const KEY = 'zmluvaonajme.ed.v1';

  let store = {};
  try { store = JSON.parse(localStorage.getItem(KEY) || '{}'); } catch (e) {}

  let saveTimer = 0;
  function commitSave() {
    clearTimeout(saveTimer);
    saveTimer = setTimeout(() => {
      try { localStorage.setItem(KEY, JSON.stringify(store)); } catch (e) {}
    }, 200);
  }

  // Figure out a stable scope string for the Ed element.
  function scopeFor(el) {
    const party = el.closest('.party-block');
    if (party) {
      const label = party.querySelector('.party-role-label');
      const role = label ? label.textContent.trim() : 'party';

      // The active type button: Fyzická osoba | Podnikateľ
      let active = '';
      const typeBtn = party.querySelector('.party-type-switch > button.active, .party-type-switch [role="tab"].active');
      if (typeBtn) active = typeBtn.textContent.trim();

      // If Podnikateľ, the sub-switch picks PO vs SZCO
      let sub = '';
      const subBtn = party.querySelector('.party-type-switch-sub button.active, .party-type-switch-sub [role="tab"].active');
      if (subBtn) sub = subBtn.textContent.trim();

      return `${role}::${active}${sub ? '/' + sub : ''}`;
    }
    const art = el.closest('.article');
    return 'art::' + (art && art.id ? art.id : 'doc');
  }

  // Compute ordinal among elements sharing this scope + placeholder.
  function keyFor(el) {
    const scope = scopeFor(el);
    const ph = el.dataset.placeholder || '';
    const scopeEl = el.closest('.party-block') || el.closest('.article') || document.body;

    // Query only in the same scope root. CSS.escape guards against odd chars.
    let siblings;
    try {
      siblings = Array.from(scopeEl.querySelectorAll(
        '.ed[data-placeholder="' + CSS.escape(ph) + '"]'
      ));
    } catch (e) {
      siblings = Array.from(scopeEl.querySelectorAll('.ed[data-placeholder]')).filter(
        n => n.dataset.placeholder === ph
      );
    }

    // For party-block fields, keep only same-scope (same variant tree) elements.
    // Since .party-type-switch content is always present in DOM but only one variant
    // renders <Ed>, this is usually fine; filtering is belt-and-braces.
    const idx = siblings.indexOf(el);
    return scope + '::' + ph + '::' + idx;
  }

  // Restore value into element from store (idempotent — only runs once per element).
  function restore(el) {
    if (!el || !el.dataset || el.dataset.persisted === '1') return;
    if (!el.classList || !el.classList.contains('ed')) return;
    if (!el.dataset.placeholder) return;
    el.dataset.persisted = '1';
    const k = keyFor(el);
    const v = store[k];
    if (typeof v === 'string' && v.length) {
      el.textContent = v;
      // Dispatch input so React's onInput handler clears the empty flag
      el.dispatchEvent(new Event('input', { bubbles: true }));
    }
  }

  function saveEl(el) {
    if (!el || !el.classList || !el.classList.contains('ed')) return;
    if (!el.dataset.placeholder) return;
    const k = keyFor(el);
    const v = (el.textContent || '').trim();
    if (v) store[k] = v; else delete store[k];
    commitSave();
  }

  // Scan a subtree for .ed elements and restore them.
  function scan(root) {
    if (!root) return;
    if (root.nodeType === 1 && root.classList && root.classList.contains('ed')) {
      restore(root);
      return;
    }
    if (root.querySelectorAll) {
      root.querySelectorAll('.ed[data-placeholder]').forEach(restore);
    }
  }

  // Any input event on a .ed field triggers save.
  document.addEventListener('input', (e) => {
    const t = e.target;
    if (t && t.classList && t.classList.contains('ed')) saveEl(t);
  }, true);

  // When party type changes, the old .ed nodes are replaced by new ones.
  // A MutationObserver picks them up and restores their values.
  const mo = new MutationObserver((muts) => {
    for (const m of muts) {
      m.addedNodes && m.addedNodes.forEach(n => { if (n.nodeType === 1) scan(n); });
    }
  });

  function init() {
    scan(document.body);
    mo.observe(document.body, { childList: true, subtree: true });
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
  } else {
    setTimeout(init, 150);
  }
})();
