// ─── Press Modal ─────────────────────────────────────────────
// Opens when window.OPEN_PRESS === true or hash === '#press'.
// Fetches press data lazily from /api/press-data on first open.

function PressModal() {
  const [open, setOpen] = React.useState(
    !!(window.OPEN_PRESS || window.location.hash === '#press')
  );
  const [pressData, setPressData] = React.useState(null);
  const [loading, setLoading]     = React.useState(false);
  const [showCommunity, setShowCommunity] = React.useState(false);
  const [searchTerm, setSearchTerm]       = React.useState('');
  const [typeFilter, setTypeFilter]       = React.useState('');
  const [copied, setCopied]               = React.useState(false);

  // Hash / modal event / popstate listeners
  React.useEffect(() => {
    function onHash()   { if (window.location.hash === '#press') setOpen(true); }
    function onModal(e) { if (e.detail === 'press') setOpen(true); }
    function onPop()    { if (!window.location.pathname.includes('press')) setOpen(false); }
    window.addEventListener('hashchange', onHash);
    window.addEventListener('not:modal',  onModal);
    window.addEventListener('popstate',   onPop);
    return () => {
      window.removeEventListener('hashchange', onHash);
      window.removeEventListener('not:modal',  onModal);
      window.removeEventListener('popstate',   onPop);
    };
  }, []);

  // ESC key
  React.useEffect(() => {
    function onKey(e) { if (e.key === 'Escape') handleClose(); }
    if (open) document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [open]);

  // Lazy-fetch press data on first open
  React.useEffect(() => {
    if (!open || pressData || loading) return;
    setLoading(true);
    fetch('/api/press-data', {
      headers: {
        'Accept': 'application/json',
        'X-Requested-With': 'XMLHttpRequest',
        'X-Application-Request': 'true',
      },
    })
      .then(r => r.json())
      .then(data => { setPressData(data); setLoading(false); })
      .catch(() => setLoading(false));
  }, [open, pressData, loading]);

  function handleClose() {
    setOpen(false);
    if (window.location.pathname.includes('press')) {
      if (window.history.state && window.history.state.notModal) {
        history.back();
      } else {
        history.pushState({}, '', '/');
      }
    } else {
      history.pushState({}, '', window.location.pathname + window.location.search);
    }
  }

  function copyEmail() {
    navigator.clipboard.writeText('jesse@networkoftime.com').then(() => {
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    });
  }

  const LOGOS = {
    'Morning Brew':         '/images/press-morningbrew.svg',
    'Scriptnotes Podcast':  '/images/press-scriptnotes.png',
    'Internet Is Beautiful':'/images/press-iib.png',
    'Heise Online':         '/images/press-heise.png',
  };

  function OutletLogo({ outlet }) {
    if (LOGOS[outlet]) return <img src={LOGOS[outlet]} alt={outlet} className="prs-logo-img" />;
    return <div className="prs-logo-placeholder">{outlet}</div>;
  }

  if (!open) return null;

  const featured  = (pressData && Array.isArray(pressData.featured))  ? pressData.featured  : [];
  const selected  = (pressData && Array.isArray(pressData.selected))  ? pressData.selected  : [];
  const community = (pressData && Array.isArray(pressData.community)) ? pressData.community : [];

  const filteredCommunity = community.filter(item => {
    const text = (item.outlet + ' ' + item.title + ' ' + item.type).toLowerCase();
    return (!searchTerm || text.includes(searchTerm.toLowerCase()))
        && (!typeFilter || item.type === typeFilter);
  });

  return (
    <div className="abt-overlay" onClick={handleClose}>
      <div className="abt-panel prs-panel" onClick={e => e.stopPropagation()}>

        <div className="abt-head">
          <span className="abt-label">Press</span>
          <button className="abt-close" onClick={handleClose}>✕ close</button>
        </div>

        <div className="abt-body">

          {/* Hero */}
          <div className="prs-hero">
            <h1 className="prs-title">Press</h1>
            <p className="prs-sub">Coverage and mentions of Network of Time</p>
            <p className="prs-updated mono">Updated August 12, 2025</p>
          </div>

          {!pressData && <p className="prs-loading mono">Loading…</p>}

          {pressData && (
            <>
              {/* Featured logos */}
              {featured.length > 0 && (
                <div className="prs-featured">
                  {featured.map((item, i) => (
                    <a key={i} href={item.url} target="_blank" rel="noopener noreferrer" className="prs-logo-item">
                      <OutletLogo outlet={item.outlet} />
                      <div className="prs-logo-outlet mono">{item.outlet}</div>
                      <div className="prs-logo-date mono">{item.date}</div>
                    </a>
                  ))}
                </div>
              )}

              {/* Selected Coverage */}
              {selected.length > 0 && (
                <>
                  <h2 className="prs-section-head">Selected Coverage</h2>
                  <div className="prs-cards">
                    {selected.map((item, i) => (
                      <a key={i} href={item.url} target="_blank" rel="noopener noreferrer" className="prs-card">
                        <div className="prs-card-outlet mono">{item.outlet}</div>
                        <div className="prs-card-title">{item.title}</div>
                        <div className="prs-card-date mono">{item.date}</div>
                        {item.quote && <div className="prs-card-quote">"{item.quote}"</div>}
                      </a>
                    ))}
                  </div>
                </>
              )}

              {/* Community mentions */}
              {community.length > 0 && (
                <div className="prs-community">
                  <h2 className="prs-section-head">Community Mentions</h2>
                  <button className="prs-toggle mono" onClick={() => setShowCommunity(v => !v)}>
                    {showCommunity ? 'Hide' : 'Show'} community mentions ({community.length})
                  </button>
                  {showCommunity && (
                    <div className="prs-community-content">
                      <div className="prs-controls">
                        <input
                          type="text"
                          className="sbt-input prs-search"
                          placeholder="Search mentions…"
                          value={searchTerm}
                          onChange={e => setSearchTerm(e.target.value)}
                        />
                        <select
                          className="sbt-input prs-filter"
                          value={typeFilter}
                          onChange={e => setTypeFilter(e.target.value)}
                        >
                          <option value="">All types</option>
                          <option value="newsletter">Newsletter</option>
                          <option value="podcast">Podcast</option>
                          <option value="radio">Radio</option>
                          <option value="tech-media">Tech Media</option>
                          <option value="blog">Blog</option>
                        </select>
                      </div>
                      <div className="prs-table-wrap">
                        <table className="prs-table">
                          <thead>
                            <tr>
                              <th>Date</th>
                              <th>Outlet</th>
                              <th>Title</th>
                              <th>Type</th>
                              <th>Lang</th>
                              <th></th>
                            </tr>
                          </thead>
                          <tbody>
                            {filteredCommunity.map((item, i) => (
                              <tr key={i}>
                                <td className="mono">{item.date}</td>
                                <td>{item.outlet}</td>
                                <td>{item.title}</td>
                                <td className="mono">{item.type}</td>
                                <td className="mono">{item.language}</td>
                                <td>
                                  <a href={item.url} target="_blank" rel="noopener noreferrer" className="prs-link">→</a>
                                </td>
                              </tr>
                            ))}
                          </tbody>
                        </table>
                      </div>
                    </div>
                  )}
                </div>
              )}

              {/* Press Kit */}
              <div className="prs-kit">
                <h2 className="prs-section-head">Press Kit & Contact</h2>
                <div className="prs-kit-grid">
                  <div className="prs-kit-item">
                    <div className="prs-kit-label mono">Logo Pack</div>
                    <p>Download our logo in SVG and PNG formats.</p>
                    <a href="/press-assets/networkoftime-logo-pack.zip" className="sbt-btn">Download</a>
                  </div>
                  <div className="prs-kit-item prs-kit-boilerplate">
                    <div className="prs-kit-label mono">Boilerplate</div>
                    <p>Network of Time is a web project that reveals how people across eras and scenes are connected in the real world. The site builds chains between any two names using only verifiable photographs and records, with each step cited to its source. Visitors can explore random chains, search specific pairings, and browse people pages — an interactive map of history's hidden proximity. As of August 2025, the database includes over 16,300 people and 13,000 photographs.</p>
                  </div>
                  <div className="prs-kit-item">
                    <div className="prs-kit-label mono">Contact</div>
                    <p>For press inquiries and media requests</p>
                    <div className="prs-email-row">
                      <a href="mailto:jesse@networkoftime.com" className="prs-email">jesse@networkoftime.com</a>
                      <button className="prs-copy mono" onClick={copyEmail} title="Copy email">
                        {copied ? '✓' : '⧉'}
                      </button>
                    </div>
                  </div>
                </div>
              </div>

              <div className="prs-footnote mono">
                We welcome tips about new coverage at jesse@networkoftime.com
              </div>
            </>
          )}

        </div>
      </div>
    </div>
  );
}

Object.assign(window, { PressModal });
