const { useState, useEffect } = React;

const SANITY_PROJECT = 'prwe0dj2';
const SANITY_DATASET = 'production';
const SANITY_QUERY = encodeURIComponent(
  `*[_type == "post" && published == true] | order(publishedAt desc) {
    "id": _id,
    title,
    "slug": slug.current,
    category,
    genre,
    readTime,
    summary,
    thumb,
    tone,
    big,
    publishedAt,
    body,
    headerImage { asset->{ url }, alt }
  }`
);

function App() {
  const [active, setActive] = useState('All');
  const [popupOpen, setPopupOpen] = useState(false);
  const [article, setArticle] = useState(null);
  const [mobileMenu, setMobileMenu] = useState(false);
  const [tweaksOpen, setTweaksOpen] = useState(false);
  const [tweaks, setTweaks] = useState(window.TWEAK_DEFAULTS);
  const [content, setContent] = useState([]);
  const [loading, setLoading] = useState(true);

  // Fetch published posts from Sanity CDN
  useEffect(() => {
    fetch(
      `https://${SANITY_PROJECT}.api.sanity.io/v2024-01-01/data/query/${SANITY_DATASET}?query=${SANITY_QUERY}`
    )
      .then(r => r.json())
      .then(r => setContent(r.result || []))
      .catch(() => setContent([]))
      .finally(() => setLoading(false));
  }, []);

  // 60-second popup trigger
  useEffect(() => {
    if (sessionStorage.getItem('ce_popup_seen')) return;
    const delay = (tweaks.popupDelaySec || 60) * 1000;
    const t = setTimeout(() => {
      setPopupOpen(true);
      sessionStorage.setItem('ce_popup_seen', '1');
    }, delay);
    return () => clearTimeout(t);
  }, [tweaks.popupDelaySec]);

  // Tweaks host protocol
  useEffect(() => {
    const handler = (e) => {
      if (e.data?.type === '__activate_edit_mode') setTweaksOpen(true);
      if (e.data?.type === '__deactivate_edit_mode') setTweaksOpen(false);
    };
    window.addEventListener('message', handler);
    window.parent.postMessage({ type: '__edit_mode_available' }, '*');
    return () => window.removeEventListener('message', handler);
  }, []);

  const updateTweak = (key, val) => {
    setTweaks((prev) => {
      const next = { ...prev, [key]: val };
      window.parent.postMessage({ type: '__edit_mode_set_keys', edits: { [key]: val } }, '*');
      return next;
    });
  };

  const filtered = active === 'All'
    ? content
    : content.filter((c) => c.category === active || c.genre === active);

  return (
    <div style={{ background: window.C.cream, minHeight: '100vh', color: window.C.charcoal }}>
      <window.TopNav onOpenMenu={() => setMobileMenu(true)} />

      <main className="ce-main" style={{
        display: 'grid',
        gridTemplateColumns: '220px 1fr',
        gap: 40,
        padding: '32px 40px 80px',
        maxWidth: 1320,
        margin: '0 auto'
      }}>
        <div className="ce-sidebar-wrap">
          <div style={{ position: 'sticky', top: 24 }}>
            <window.Sidebar active={active} setActive={setActive} openPopup={() => setPopupOpen(true)} />
          </div>
        </div>

        <section>
          {/* Hero strip */}
          <div style={{ marginBottom: 26 }}>
            <h1 style={{
              fontFamily: 'Instrument Serif, serif',
              fontSize: 'clamp(36px, 5vw, 56px)',
              lineHeight: 1.02,
              margin: 0,
              color: window.C.charcoal,
              fontWeight: 400,
              letterSpacing: -1,
              maxWidth: 760
            }}>
              Breakdowns of the best video ads,<br />
              TikToks & short-form creative on earth.
            </h1>
            <p style={{
              fontFamily: 'Inter, system-ui, sans-serif',
              fontSize: 15.5,
              color: 'rgba(3,68,62,0.7)',
              margin: '14px 0 0',
              maxWidth: 580,
              lineHeight: 1.5
            }}>Hand-picked by Danny. Read in 2–5 minutes. Free, every Tuesday.
            </p>
          </div>

          {/* Filter label */}
          <div className="ce-active-filter" style={{
            fontSize: 12, letterSpacing: 1.2, textTransform: 'uppercase',
            fontWeight: 600, color: 'rgba(3,68,62,0.55)',
            fontFamily: 'Inter, system-ui, sans-serif',
            marginBottom: 14
          }}>
            {loading
              ? 'Loading…'
              : `${filtered.length} ${active === 'All' ? 'examples' : `${active} examples`}`
            }
          </div>

          <div className="ce-masonry">
            {filtered.map((item) =>
              <window.Card key={item.id} item={item} onClick={() => setArticle(item)} />
            )}
            {!loading && filtered.length === 0 && (
              <p style={{
                fontFamily: 'Inter, system-ui, sans-serif',
                fontSize: 14,
                color: 'rgba(3,68,62,0.45)',
                margin: 0,
              }}>
                No examples yet — check back soon.
              </p>
            )}
          </div>

          {/* Footer */}
          <footer style={{
            marginTop: 64,
            paddingTop: 28,
            borderTop: '1px solid rgba(3,68,62,0.1)',
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
            flexWrap: 'wrap',
            gap: 16
          }}>
            <div style={{
              fontFamily: 'Instrument Serif, serif',
              fontSize: 22, color: window.C.charcoal
            }}>
              Creative Examples
            </div>
            <div style={{
              fontSize: 13, color: 'rgba(3,68,62,0.6)',
              fontFamily: 'Inter, system-ui, sans-serif'
            }}>
              © 2026 · Made in London · <a href="#" style={{ color: 'inherit' }}>Contact</a>
            </div>
          </footer>
        </section>
      </main>

      {/* Mobile menu drawer */}
      {mobileMenu &&
        <div
          onClick={() => setMobileMenu(false)}
          style={{
            position: 'fixed', inset: 0, background: 'rgba(3,68,62,0.4)', zIndex: 900
          }}>
          <div
            onClick={(e) => e.stopPropagation()}
            style={{
              position: 'absolute', left: 0, top: 0, bottom: 0,
              width: 280, maxWidth: '85vw',
              background: window.C.cream,
              padding: '24px 24px',
              overflowY: 'auto'
            }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
              <div style={{ fontFamily: 'Instrument Serif, serif', fontSize: 22 }}>Filters</div>
              <button onClick={() => setMobileMenu(false)} style={{ background: 'transparent', border: 'none', cursor: 'pointer' }}>
                <svg width="20" height="20" viewBox="0 0 24 24"><path d="M6 6l12 12M18 6L6 18" stroke={window.C.charcoal} strokeWidth="2" strokeLinecap="round" /></svg>
              </button>
            </div>
            <window.Sidebar active={active} setActive={(k) => { setActive(k); setMobileMenu(false); }} openPopup={() => { setMobileMenu(false); setPopupOpen(true); }} />
          </div>
        </div>
      }

      <window.EmailPopup open={popupOpen} onClose={() => setPopupOpen(false)} />
      <window.ArticlePopup article={article} onClose={() => setArticle(null)} />

      {/* Floating "newsletter" trigger */}
      <button
        onClick={() => setPopupOpen(true)}
        style={{
          position: 'fixed', bottom: 24, right: 24,
          background: window.C.charcoal, color: window.C.cream,
          border: 'none', borderRadius: 999,
          padding: '12px 20px',
          fontSize: 13, fontWeight: 600,
          fontFamily: 'Inter, system-ui, sans-serif',
          cursor: 'pointer',
          boxShadow: '0 8px 24px -8px rgba(3,68,62,0.5)',
          display: 'flex', alignItems: 'center', gap: 8,
          zIndex: 500
        }}>
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none"><path d="M3 7l9 6 9-6M3 7v10a1 1 0 0 0 1 1h16a1 1 0 0 0 1-1V7M3 7l1-1h16l1 1" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" /></svg>
        Get the newsletter
      </button>

      {/* Tweaks panel */}
      {tweaksOpen &&
        <div style={{
          position: 'fixed', bottom: 80, right: 24,
          background: '#ffffff',
          border: `1px solid rgba(3,68,62,0.15)`,
          borderRadius: 12,
          padding: 18,
          width: 260,
          zIndex: 1500,
          boxShadow: '0 12px 32px -8px rgba(3,68,62,0.25)',
          fontFamily: 'Inter, system-ui, sans-serif'
        }}>
          <div style={{
            fontFamily: 'Instrument Serif, serif', fontSize: 20,
            marginBottom: 14, color: window.C.charcoal
          }}>
            Tweaks
          </div>

          <label style={{ display: 'block', fontSize: 11, fontWeight: 600, letterSpacing: 1, textTransform: 'uppercase', color: 'rgba(3,68,62,0.6)', marginBottom: 6 }}>
            Popup delay
          </label>
          <input
            type="range" min="1" max="60" value={tweaks.popupDelaySec}
            onChange={(e) => updateTweak('popupDelaySec', +e.target.value)}
            style={{ width: '100%', marginBottom: 2 }} />
          <div style={{ fontSize: 12, color: 'rgba(3,68,62,0.7)', marginBottom: 16 }}>{tweaks.popupDelaySec}s</div>

          <label style={{ display: 'block', fontSize: 11, fontWeight: 600, letterSpacing: 1, textTransform: 'uppercase', color: 'rgba(3,68,62,0.6)', marginBottom: 6 }}>
            Card style
          </label>
          <select
            value={tweaks.cardStyle}
            onChange={(e) => updateTweak('cardStyle', e.target.value)}
            style={{ width: '100%', padding: 8, borderRadius: 6, border: `1px solid rgba(3,68,62,0.2)`, marginBottom: 16, fontSize: 13 }}>
            <option value="light">Light (cream)</option>
            <option value="dark">Dark (charcoal)</option>
          </select>

          <button
            onClick={() => { sessionStorage.removeItem('ce_popup_seen'); setPopupOpen(true); }}
            style={{
              width: '100%', background: window.C.coral, color: window.C.cream,
              border: 'none', borderRadius: 8, padding: '10px 14px',
              fontSize: 13, fontWeight: 600, cursor: 'pointer'
            }}>
            Preview popup now
          </button>
        </div>
      }

      {/* Global dark-card override */}
      {tweaks.cardStyle === 'dark' &&
        <style>{`
          article {
            background: ${window.C.charcoal} !important;
            border-color: rgba(255,241,218,0.1) !important;
          }
          article h3 { color: ${window.C.cream} !important; }
        `}</style>
      }
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
