/* ═══════════════════════════════════════════════════════════════════
   ExampleState.jsx — shared "instructive example" pattern (v1.0.0)
   ═══════════════════════════════════════════════════════════════════

   Reusable across the SaaS + plugin (plugin renders these same panels via
   iframes, so behavior is inherited for free). Formalizes the manual
   "Populated demo" toggle / "PREVIEW" rows into one consistent rule:

     showExamples  ===  (realCount === 0)  &&  (!busy)  &&  (!dismissed)

   - Real data arrives  -> examples hide.
   - A live action runs (busy) -> examples hide for its duration, then restore.
   - Data cleared back to zero -> examples return ("for next time").
   - User can dismiss (escape hatch); the choice persists per storageKey and
     is overridable via reset()/toggle().

   Locked guarantees this enforces by construction:
   - NEVER mix example + real (examples only render when realCount === 0).
   - Examples are always clearly labeled + non-interactive (use ExampleBadge +
     the .wpsb-example class on the container so they read as samples, not data).

   Exposes: window.WPSB.useExampleState, window.WPSB.ExampleBadge.
   ═══════════════════════════════════════════════════════════════════ */

(function () {
  'use strict';

  const { useState, useCallback, useEffect } = React;

  const VERSION = '1.0.0';
  const LS_PREFIX = 'wpsb-ex-dismiss:';

  function readDismissed(storageKey) {
    if (!storageKey) return false;
    try { return localStorage.getItem(LS_PREFIX + storageKey) === '1'; } catch (_) { return false; }
  }
  function writeDismissed(storageKey, val) {
    if (!storageKey) return;
    try {
      if (val) localStorage.setItem(LS_PREFIX + storageKey, '1');
      else localStorage.removeItem(LS_PREFIX + storageKey);
    } catch (_) { /* quota / unavailable */ }
  }

  /* useExampleState({ realCount, busy, storageKey })
     -> { showExamples, dismissed, dismiss, reset, toggle } */
  function useExampleState(opts) {
    opts = opts || {};
    const storageKey = opts.storageKey || null;
    const realCount = Number(opts.realCount || 0);
    const busy = !!opts.busy;

    const [dismissed, setDismissed] = useState(() => readDismissed(storageKey));

    // Keep state in sync if the storageKey changes (e.g. switching sites).
    useEffect(() => { setDismissed(readDismissed(storageKey)); }, [storageKey]);

    const dismiss = useCallback(() => { setDismissed(true); writeDismissed(storageKey, true); }, [storageKey]);
    const reset = useCallback(() => { setDismissed(false); writeDismissed(storageKey, false); }, [storageKey]);
    const toggle = useCallback(() => {
      setDismissed(prev => { const next = !prev; writeDismissed(storageKey, next); return next; });
    }, [storageKey]);

    const showExamples = realCount === 0 && !busy && !dismissed;
    return { showExamples, dismissed, dismiss, reset, toggle };
  }

  /* Small, consistent "EXAMPLE" badge. Pass label to override (e.g. "PREVIEW · v2"). */
  function ExampleBadge({ label }) {
    return (
      <span className="tag warn" style={{ fontSize: '.52rem', padding: '1px 6px', letterSpacing: '.5px', fontStyle: 'normal', verticalAlign: 'middle' }}>
        {label || 'EXAMPLE'}
      </span>
    );
  }

  /* Inject the shared .wpsb-example styling once (faded + non-interactive look). */
  function injectStyleOnce() {
    if (typeof document === 'undefined') return;
    if (document.getElementById('wpsb-example-style')) return;
    const el = document.createElement('style');
    el.id = 'wpsb-example-style';
    el.textContent = [
      '.wpsb-example{opacity:.62;font-style:italic;position:relative;}',
      '.wpsb-example .wpsb-example-actions{pointer-events:none;}',
      '.wpsb-example input,.wpsb-example button:not(.wpsb-example-allow){pointer-events:none;}',
      '.wpsb-example-note{display:flex;align-items:flex-start;gap:6px;font-size:.72rem;color:var(--dim);line-height:1.5;margin-bottom:8px;}',
    ].join('\n');
    document.head.appendChild(el);
  }
  injectStyleOnce();

  /* ── EXPORTS ─────────────────────────────────────────────────── */
  window.WPSB = window.WPSB || {};
  window.WPSB.useExampleState = useExampleState;
  window.WPSB.ExampleBadge = ExampleBadge;

  console.log('[WPSB ExampleState] loaded v' + VERSION);
})();
