/* global React, MegaFooter */
//
// /emails — internal reference page showing every applicant-facing email
// the site sends, rendered with sample data. Wears the standard site
// chrome (Nav rendered by app.jsx, MegaFooter rendered here) so it feels
// part of the system rather than a standalone surface.
//
// The actual template-rendering logic lives in lib/email-template-previews.js
// — a pure ES module loaded at mount time via dynamic import(). That keeps
// this JSX file readable and avoids putting Babel-Standalone through the
// 300-line interpolation of email HTML.

const { useState: useStateEmails, useEffect: useEffectEmails, useRef: useRefEmails } = React;

function EmailTemplatesPage({ onGoto }) {
  const [emails, setEmails] = useStateEmails([]);
  const [loadError, setLoadError] = useStateEmails(null);
  const [activeId, setActiveId] = useStateEmails(null);
  const emailsRef = useRefEmails(null);

  // Pull in the email rendering module. We deliberately wrap the dynamic
  // import in `new Function(...)` so Babel-Standalone (which compiles this
  // file in the browser with the env preset) doesn't try to transform
  // `import()` into a CommonJS `require()` — which would fail at runtime
  // because the browser has no `require`. The Function-wrapped version is
  // opaque to Babel and runs the native browser dynamic import as intended.
  useEffectEmails(() => {
    let cancelled = false;
    const nativeImport = new Function('url', 'return import(url)');
    nativeImport('/lib/email-template-previews.js')
      .then((mod) => {
        if (cancelled) return;
        setEmails(mod.getAllEmails());
      })
      .catch((err) => {
        console.error('Failed to load email template previews:', err);
        if (!cancelled) setLoadError(err?.message || 'Unknown error');
      });
    return () => { cancelled = true; };
  }, []);

  // Wrap each rendered email body in a full HTML document for the iframe.
  // `base target="_blank"` so any link inside opens in a new tab instead of
  // navigating the iframe itself.
  const wrapDoc = (html) => `<!doctype html><html><head><meta charset="utf-8"><base target="_blank"></head><body style="margin:0;padding:24px;background:#f3f4f7;font-family:-apple-system,'Segoe UI',Helvetica,Arial,sans-serif;">${html}</body></html>`;

  // Auto-resize each iframe to fit its content. Re-runs whenever the emails
  // list mounts (i.e. once the module finishes loading).
  useEffectEmails(() => {
    if (!emailsRef.current || emails.length === 0) return;
    const iframes = emailsRef.current.querySelectorAll('iframe');
    const handlers = [];
    iframes.forEach((iframe) => {
      const onLoad = () => {
        try {
          const h = iframe.contentDocument.body.scrollHeight;
          iframe.style.height = (h + 8) + 'px';
        } catch (err) { /* cross-origin guard */ }
      };
      iframe.addEventListener('load', onLoad);
      handlers.push([iframe, onLoad]);
      // If already loaded by the time the listener attaches, fire once.
      if (iframe.contentDocument && iframe.contentDocument.readyState === 'complete') {
        onLoad();
      }
    });
    return () => handlers.forEach(([el, fn]) => el.removeEventListener('load', fn));
  }, [emails]);

  // Scroll-spy for the sidebar — highlights the email currently in view.
  useEffectEmails(() => {
    if (!emailsRef.current || emails.length === 0) return;
    const observer = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) setActiveId(entry.target.id);
      });
    }, { rootMargin: '0px 0px -70% 0px' });
    emailsRef.current.querySelectorAll('article.emp-card').forEach((a) => observer.observe(a));
    return () => observer.disconnect();
  }, [emails]);

  const onSidebarClick = (e, id) => {
    e.preventDefault();
    const target = document.getElementById(id);
    if (target) target.scrollIntoView({ behavior: 'smooth', block: 'start' });
    setActiveId(id);
  };

  return (
    <main className="page active emails-light" data-screen-label="09 Internal · Email templates">
      <style>{`
        .emails-light { background: #F7F8FA; }
        .emp-hero { padding: 140px 0 40px; }
        .emp-hero .container { max-width: 1280px; margin: 0 auto; padding: 0 32px; }
        .emp-hero .eyebrow {
          display: inline-flex; align-items: center; gap: 8px;
          font-family: var(--font-mono, ui-monospace, 'SF Mono', Menlo, Consolas, monospace);
          font-size: 11px; font-weight: 500; letter-spacing: 0.12em; text-transform: uppercase;
          color: var(--vf-ink-3);
        }
        .emp-hero .eyebrow .idx {
          color: var(--vf-blue);
          background: rgba(9, 94, 223, 0.10);
          padding: 4px 8px; border-radius: 999px;
          font-weight: 700; font-size: 10.5px; letter-spacing: 0.08em;
        }
        .emp-hero h1 {
          font-size: clamp(40px, 5.5vw, 72px); font-weight: 700; line-height: 1.0;
          letter-spacing: -0.025em; color: var(--vf-ink);
          margin: 14px 0 0; max-width: 18ch;
        }
        .emp-hero h1 em { color: var(--vf-blue); font-style: italic; font-weight: 500; }
        .emp-hero .lead {
          margin-top: 20px; max-width: 64ch;
          font-size: 17px; line-height: 1.6; color: var(--vf-ink-2);
        }
        .emp-layout {
          max-width: 1280px; margin: 0 auto; padding: 24px 32px 96px;
          display: grid; grid-template-columns: 240px 1fr; gap: 48px;
        }
        .emp-toc {
          position: sticky; top: 96px; align-self: start;
          max-height: calc(100vh - 128px); overflow-y: auto;
        }
        .emp-toc-label {
          font-family: var(--font-mono); font-size: 10.5px; font-weight: 700;
          letter-spacing: 0.12em; text-transform: uppercase; color: var(--vf-ink-4);
          margin: 0 0 14px;
        }
        .emp-toc ol { list-style: none; margin: 0; padding: 0; }
        .emp-toc li { margin: 0; }
        .emp-toc a {
          display: block; padding: 11px 14px; border-radius: 8px;
          color: var(--vf-ink-2); text-decoration: none;
          font-size: 13.5px; line-height: 1.4;
          border-left: 2px solid transparent;
          transition: background 120ms, color 120ms, border-color 120ms;
        }
        .emp-toc a:hover { background: #ffffff; color: var(--vf-ink); }
        .emp-toc a.is-active {
          background: #ffffff; color: var(--vf-ink);
          border-left-color: var(--vf-blue);
        }
        .emp-toc a strong { display: block; font-weight: 600; font-size: 13.5px; }
        .emp-toc a .ctx {
          display: block; margin-top: 3px;
          font-family: var(--font-mono); font-size: 10.5px;
          color: var(--vf-ink-4); letter-spacing: 0.04em;
        }
        .emp-toc-footnote {
          margin: 28px 0 0; padding-top: 18px;
          border-top: 1px solid var(--vf-line);
          font-size: 11.5px; color: var(--vf-ink-3); line-height: 1.55;
        }
        .emp-cards { min-width: 0; }
        .emp-card {
          background: #ffffff; border: 1px solid var(--vf-line); border-radius: 14px;
          margin: 0 0 32px; overflow: hidden;
          box-shadow: 0 1px 2px rgba(10, 15, 26, 0.03);
        }
        .emp-card header { padding: 26px 28px 22px; border-bottom: 1px solid var(--vf-line); }
        .emp-card-eyebrow {
          font-family: var(--font-mono); font-size: 10.5px; font-weight: 700;
          letter-spacing: 0.12em; text-transform: uppercase; color: var(--vf-blue);
          margin: 0 0 6px;
        }
        .emp-card h2 {
          margin: 0 0 18px; font-size: 21px; font-weight: 700; line-height: 1.2;
          letter-spacing: -0.015em; color: var(--vf-ink);
        }
        .emp-meta {
          display: grid; grid-template-columns: 80px 1fr; gap: 4px 18px;
          font-size: 13.5px; line-height: 1.55;
        }
        .emp-meta dt {
          font-family: var(--font-mono); font-size: 10.5px; font-weight: 700;
          letter-spacing: 0.08em; text-transform: uppercase; color: var(--vf-ink-4);
          margin: 0; padding-top: 4px;
        }
        .emp-meta dd { margin: 0; color: var(--vf-ink-2); }
        .emp-canvas { background: #F7F8FA; padding: 32px 28px; }
        .emp-card iframe {
          display: block; width: 100%; max-width: 600px; margin: 0 auto;
          border: 0; background: #ffffff; border-radius: 8px;
          box-shadow: 0 8px 32px rgba(10, 15, 26, 0.08);
        }
        .emp-loading {
          padding: 80px 28px; text-align: center;
          color: var(--vf-ink-3); font-size: 14px;
        }
        @media (max-width: 900px) {
          .emp-layout { grid-template-columns: 1fr; gap: 32px; padding: 16px 20px 64px; }
          .emp-toc { position: static; max-height: none; }
          .emp-hero { padding: 110px 0 28px; }
          .emp-hero .container { padding: 0 20px; }
          .emp-meta { grid-template-columns: 1fr; gap: 2px 0; }
          .emp-meta dt { padding-top: 12px; }
          .emp-card header { padding: 22px 20px 18px; }
          .emp-canvas { padding: 24px 16px; }
        }
      `}</style>

      <section className="emp-hero">
        <div className="container">
          <p className="eyebrow"><span className="idx">VF—9.0</span> Internal · Email templates</p>
          <h1>The automated emails Valley <em>sends</em></h1>
          <p className="lead">A reference for every transactional email that goes out to applicants, referees and consignors. Sample data shown below — in real sends, the recipient's actual name and submitted details slot in. Updated whenever the templates change.</p>
        </div>
      </section>

      <div className="emp-layout">
        <aside className="emp-toc">
          <p className="emp-toc-label">All templates</p>
          {emails.length === 0 ? (
            <p style={{ fontSize: '12px', color: 'var(--vf-ink-4)' }}>Loading…</p>
          ) : (
            <ol>
              {emails.map((e) => (
                <li key={e.id}>
                  <a
                    href={`#${e.id}`}
                    className={activeId === e.id ? 'is-active' : ''}
                    onClick={(ev) => onSidebarClick(ev, e.id)}
                  >
                    <strong>{e.name}</strong>
                    <span className="ctx">{e.source}</span>
                  </a>
                </li>
              ))}
            </ol>
          )}
          <p className="emp-toc-footnote">
            The shared chrome (logo, footer, security badge) is rendered live from <span style={{ fontFamily: 'var(--font-mono)', fontSize: '10.5px', color: 'var(--vf-ink-2)' }}>lib/resend.js</span>. The body of each template is mirrored on this page from source; updated in lockstep when emails ship.
          </p>
        </aside>

        <div className="emp-cards" ref={emailsRef}>
          {loadError && (
            <div className="emp-loading" style={{ color: '#c0392b' }}>
              Couldn't load the email previews module: {loadError}
            </div>
          )}
          {!loadError && emails.length === 0 && (
            <div className="emp-loading">Loading email previews…</div>
          )}
          {emails.map((e) => (
            <article key={e.id} id={e.id} className="emp-card">
              <header>
                <p className="emp-card-eyebrow">{e.eyebrow}</p>
                <h2>{e.name}</h2>
                <dl className="emp-meta">
                  <dt>Trigger</dt><dd>{e.trigger}</dd>
                  <dt>From</dt><dd>{e.from}</dd>
                  <dt>To</dt><dd>{e.to}</dd>
                  <dt>Subject</dt><dd>{e.subject}</dd>
                </dl>
              </header>
              <div className="emp-canvas">
                <iframe srcDoc={wrapDoc(e.html)} loading="lazy" title={e.name} />
              </div>
            </article>
          ))}
        </div>
      </div>

      <MegaFooter onGoto={onGoto} />
    </main>
  );
}

Object.assign(window, { EmailTemplatesPage });
