/* ═══════════════════════════════════════════════════════════════════
   IframeTab.jsx — reusable iframe wrapper for embedded tool pages
   ═══════════════════════════════════════════════════════════════════
   Embeds /scanner.html, /estimator.html, /embed-support.html,
   /embed-roadmap.html inside Claude Design tab panels.

   Since the iframe is same-origin (app.wpsitebeam.io/*), it naturally
   shares localStorage with the parent — so Supabase session, WPSBD
   settings, and any other browser state is visible to the iframe.
   No token passing or postMessage needed for auth.

   Query param `embedded=1` tells the child page it's being rendered
   inside the Claude Design shell, so it can hide its own header/nav
   chrome if needed.
   ═══════════════════════════════════════════════════════════════════ */

(function(){
  const { useState, useRef, useEffect } = React;

  function IframeTab({ src, title, allowFeatures, sandbox, fallbackHint }) {
    const [loaded, setLoaded] = useState(false);
    const [errored, setErrored] = useState(false);
    const [timedOut, setTimedOut] = useState(false);
    const iframeRef = useRef(null);

    /* Show a timeout warning if the iframe hasn't fired load event in 10s */
    useEffect(() => {
      if (loaded || errored) return;
      const t = setTimeout(() => {
        if (!loaded && !errored) setTimedOut(true);
      }, 10000);
      return () => clearTimeout(t);
    }, [loaded, errored]);

    const reload = () => {
      setLoaded(false); setErrored(false); setTimedOut(false);
      if (iframeRef.current) iframeRef.current.src = iframeRef.current.src;
    };

    /* Once loaded, set embedded-mode class on iframe body so the child
       page hides its own topbar/sidebar. Same-origin = we can touch
       contentDocument directly. */
    // Sync theme from parent to iframe
    const syncTheme = () => {
      try {
        const doc = iframeRef.current?.contentDocument;
        if (!doc) return;
        const theme = document.documentElement.getAttribute('data-theme') || 'dark';
        doc.documentElement.setAttribute('data-theme', theme);
      } catch(e) {}
    };

    const handleLoad = () => {
      setLoaded(true);
      try {
        const doc = iframeRef.current?.contentDocument;
        if (doc?.body) {
          doc.body.classList.add('embedded-mode');
          doc.documentElement.classList.add('embedded-mode');

          // Inject tokens.css so the iframe respects the design system
          if (!doc.querySelector('link[data-wpsb-tokens]')) {
            const link = doc.createElement('link');
            link.rel = 'stylesheet';
            link.href = '/design/tokens.css';
            link.setAttribute('data-wpsb-tokens', '1');
            doc.head.appendChild(link);
          }

          // Sync current theme
          syncTheme();
        }
      } catch(e) {
        console.warn('[IframeTab] Could not set embedded class:', e);
      }
    };

    /* Re-sync theme whenever parent data-theme changes */
    useEffect(() => {
      if (!loaded) return;
      syncTheme();
      // Watch for parent theme attribute changes
      const observer = new MutationObserver(syncTheme);
      observer.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] });
      return () => observer.disconnect();
    }, [loaded]);

    /* Build full URL with embedded flag */
    const url = (() => {
      try {
        const u = new URL(src, window.location.origin);
        u.searchParams.set('embedded', '1');
        return u.toString();
      } catch { return src; }
    })();

    return (
      <div className="iframe-tab" style={{
        display: 'flex', flexDirection: 'column',
        height: '100%',
        minHeight: '600px',
        width: '100%',
        background: 'var(--bg)',
        position: 'relative',
        /* Cancel parent padding for full-bleed */
        margin: 'calc(-1 * var(--sp-6))',
        padding: 0,
      }}>
        {/* Loading overlay */}
        {!loaded && !errored && (
          <div className="iframe-tab-overlay" aria-busy="true" style={{
            position: 'absolute', inset: 0,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            flexDirection: 'column', gap: 14,
            background: 'var(--bg)',
            zIndex: 2,
          }}>
            <div className="spinner" style={{
              width: 26, height: 26,
              border: '2px solid var(--border)',
              borderTopColor: 'var(--beam)',
              borderRadius: '50%',
              animation: 'spin .7s linear infinite',
            }}/>
            <div style={{ fontSize: '.86rem', color: 'var(--muted)' }}>
              {timedOut
                ? `Still loading ${title}… (slower than usual)`
                : `Loading ${title}…`}
            </div>
            {timedOut && (
              <button className="btn btn-ghost btn-sm"
                      onClick={reload}
                      style={{ marginTop: 6 }}>
                Reload
              </button>
            )}
          </div>
        )}

        {/* Error state */}
        {errored && (
          <div className="iframe-tab-error" role="alert" style={{
            flex: 1,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            flexDirection: 'column', gap: 12, padding: 40,
          }}>
            <div style={{
              width: 40, height: 40, borderRadius: '50%',
              background: 'var(--red-dim)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              color: 'var(--red)', fontSize: '1.2rem', fontWeight: 700,
            }}>!</div>
            <div style={{ fontWeight: 600, fontSize: '1rem' }}>
              Couldn't load {title}
            </div>
            <div style={{ fontSize: '.85rem', color: 'var(--muted)', maxWidth: 420, textAlign: 'center' }}>
              {fallbackHint || `The ${title} page failed to load. This is usually a temporary network issue.`}
            </div>
            <div style={{ display: 'flex', gap: 8, marginTop: 6 }}>
              <button className="btn btn-sm" onClick={reload}>
                Retry
              </button>
              <a className="btn btn-ghost btn-sm" href={src} target="_blank" rel="noopener">
                Open in new tab
              </a>
            </div>
          </div>
        )}

        {/* The iframe itself */}
        <iframe
          ref={iframeRef}
          src={url}
          title={title}
          onLoad={handleLoad}
          onError={() => setErrored(true)}
          allow={allowFeatures || 'clipboard-read; clipboard-write; fullscreen'}
          sandbox={sandbox /* undefined = no sandbox, full permissions */}
          style={{
            flex: 1,
            width: '100%',
            border: 'none',
            background: 'var(--bg)',
            display: errored ? 'none' : 'block',
          }}
        />
      </div>
    );
  }

  /* ── TAB-SPECIFIC WRAPPERS ───────────────────────────────────── */

  function ScannerIframe() {
    return <IframeTab
      src="/scanner.html"
      title="Site Scanner"
      fallbackHint="The Scanner tool is a separate embedded page. If it keeps failing, try hard-refreshing or opening in a new tab."
    />;
  }

  function EstimatorIframe() {
    return <IframeTab
      src="/estimator.html"
      title="WP Scope Estimator"
      fallbackHint="The Estimator tool is a separate embedded page."
    />;
  }

  function SupportIframe() {
    return <IframeTab
      src="/embed-support.html"
      title="Support"
      fallbackHint="Support resources couldn't load. You can also reach us at support@wpsitebeam.io."
    />;
  }

  function RoadmapIframe() {
    return <IframeTab
      src="/embed-roadmap.html"
      title="Roadmap"
      fallbackHint="The Roadmap page couldn't load. This is where feature requests and announcements live."
    />;
  }

  /* ── EXPORT ──────────────────────────────────────────────────── */
  window.IframeTab       = IframeTab;
  window.ScannerIframe   = ScannerIframe;
  window.EstimatorIframe = EstimatorIframe;
  window.SupportIframe   = SupportIframe;
  window.RoadmapIframe   = RoadmapIframe;

  console.log('[WPSB] IframeTab components loaded');
})();
