// Monjez landing — shared presentational helpers + global video modal.
const { useState, useEffect, useRef, useContext } = React;

const MAXW = 1180;

// ---- i18n ----
window.STR = { ar: window.STR_AR, en: window.STR_EN };
window.LangContext = React.createContext({ lang: 'ar', setLang: () => {} });
window.useT = function () { const ctx = useContext(window.LangContext); return window.STR[ctx.lang] || window.STR.ar; };
window.useLang = function () { return useContext(window.LangContext); };

function Container({ children, style = {}, narrow = false }) {
  return (
    <div style={{ maxWidth: narrow ? 940 : MAXW, margin: '0 auto', padding: '0 28px', ...style }}>
      {children}
    </div>
  );
}

// Uppercase wide-tracking kicker
function Eyebrow({ children, color = 'var(--blue-400)', style = {} }) {
  return (
    <div style={{
      fontFamily: 'var(--font-body)', fontSize: 12.5, fontWeight: 600,
      letterSpacing: '0.16em', textTransform: 'uppercase', color, ...style,
    }}>{children}</div>
  );
}

// Gradient-clipped emphasis word (blue → teal), used sparingly in big headlines
function Accent({ children, from = '#9B82FF', to = '#A78BFA' }) {
  return (
    <span style={{
      background: `linear-gradient(100deg, ${from}, ${to})`,
      WebkitBackgroundClip: 'text', backgroundClip: 'text',
      WebkitTextFillColor: 'transparent', color: 'transparent',
    }}>{children}</span>
  );
}

// Reveal-on-scroll wrapper
function Reveal({ children, delay = 0, y = 18, style = {} }) {
  const ref = useRef(null);
  const [seen, setSeen] = useState(false);
  useEffect(() => {
    const el = ref.current; if (!el) return;
    if (typeof IntersectionObserver === 'undefined') { setSeen(true); return; }
    const io = new IntersectionObserver((es) => {
      es.forEach((e) => { if (e.isIntersecting) { setSeen(true); io.disconnect(); } });
    }, { threshold: 0.12, rootMargin: '0px 0px -8% 0px' });
    io.observe(el);
    return () => io.disconnect();
  }, []);
  return (
    <div ref={ref} style={{
      opacity: seen ? 1 : 0,
      transform: seen ? 'none' : `translateY(${y}px)`,
      transition: `opacity .6s cubic-bezier(.2,.6,.2,1) ${delay}s, transform .6s cubic-bezier(.2,.6,.2,1) ${delay}s`,
      ...style,
    }}>{children}</div>
  );
}

function SectionHead({ eyebrow, eyebrowColor, title, sub, align = 'center', maxTitle = 720, style = {} }) {
  const ta = align === 'center' ? 'center' : 'start';
  return (
    <div style={{ textAlign: ta, maxWidth: align === 'center' ? maxTitle : 'none', margin: align === 'center' ? '0 auto' : 0, ...style }}>
      {eyebrow && <Eyebrow color={eyebrowColor} style={{ marginBottom: 16 }}>{eyebrow}</Eyebrow>}
      <h2 style={{
        fontFamily: 'var(--font-display)', fontWeight: 600,
        fontSize: 'clamp(30px, 4.4vw, 46px)', lineHeight: 1.06, letterSpacing: '-0.03em',
        margin: 0, textWrap: 'balance',
      }}>{title}</h2>
      {sub && <p style={{
        fontSize: 17.5, lineHeight: '29px', color: 'var(--text-secondary)',
        maxWidth: align === 'center' ? 600 : 560, margin: align === 'center' ? '18px auto 0' : '18px 0 0',
      }}>{sub}</p>}
    </div>
  );
}

function scrollToId(id) {
  const el = document.getElementById(id);
  if (el) window.scrollTo({ top: el.getBoundingClientRect().top + window.scrollY - 76, behavior: 'smooth' });
}
function playVideo(src) {
  window.dispatchEvent(new CustomEvent('monjez:play', { detail: { src: src || '' } }));
}

// Framed app-window chrome (mac dots + url)
function WindowChrome({ url = 'app.monjez.com', children, style = {} }) {
  return (
    <div style={{
      borderRadius: 'var(--radius-xl)', border: '1px solid var(--border-strong)',
      background: 'var(--graphite)', boxShadow: 'var(--shadow-lg)', overflow: 'hidden', ...style,
    }}>
      <div style={{ height: 40, borderBottom: '1px solid var(--border-subtle)', display: 'flex', alignItems: 'center', gap: 7, padding: '0 16px', background: 'var(--graphite-600)' }}>
        {['#EF4444', '#F59E0B', '#A78BFA'].map((c) => <span key={c} style={{ width: 11, height: 11, borderRadius: '50%', background: c, opacity: 0.85 }} />)}
        <span style={{ marginLeft: 12, fontSize: 12.5, color: 'var(--text-muted)', fontFamily: 'var(--font-mono)' }}>{url}</span>
      </div>
      {children}
    </div>
  );
}

// Circular play button
function PlayButton({ size = 76, onClick }) {
  const [h, setH] = useState(false);
  return (
    <button onClick={onClick} onMouseEnter={() => setH(true)} onMouseLeave={() => setH(false)}
      aria-label="Play video"
      style={{
        width: size, height: size, borderRadius: '50%', border: '1px solid var(--border-strong)',
        background: h ? 'var(--accent)' : 'rgba(11,16,32,0.55)', backdropFilter: 'blur(6px)',
        display: 'grid', placeItems: 'center', cursor: 'pointer',
        boxShadow: h ? '0 0 40px rgba(37,99,235,0.55)' : '0 8px 28px rgba(0,0,0,0.4)',
        transition: 'background .18s ease, box-shadow .25s ease, transform .12s ease',
        transform: h ? 'scale(1.05)' : 'scale(1)', color: '#fff',
      }}>
      <window.IconPlay size={size * 0.34} />
    </button>
  );
}

// Global video modal — opens on window 'monjez:play'
function VideoModal() {
  const [open, setOpen] = useState(false);
  const [src, setSrc] = useState('');
  useEffect(() => {
    const onPlay = (e) => { setSrc(e.detail && e.detail.src || ''); setOpen(true); };
    const onKey = (e) => { if (e.key === 'Escape') setOpen(false); };
    window.addEventListener('monjez:play', onPlay);
    window.addEventListener('keydown', onKey);
    return () => { window.removeEventListener('monjez:play', onPlay); window.removeEventListener('keydown', onKey); };
  }, []);
  useEffect(() => { document.body.style.overflow = open ? 'hidden' : ''; }, [open]);
  if (!open) return null;
  return (
    <div onClick={() => setOpen(false)} style={{
      position: 'fixed', inset: 0, zIndex: 200, background: 'rgba(7,11,22,0.86)', backdropFilter: 'blur(8px)',
      display: 'grid', placeItems: 'center', padding: 28, animation: 'mjFade .2s ease',
    }}>
      <div onClick={(e) => e.stopPropagation()} style={{ width: 'min(1000px, 100%)' }}>
        <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: 12 }}>
          <button onClick={() => setOpen(false)} aria-label="Close"
            style={{ width: 40, height: 40, borderRadius: '50%', border: '1px solid var(--border-strong)', background: 'var(--white-04)', color: 'var(--cloud-white)', display: 'grid', placeItems: 'center', cursor: 'pointer' }}>
            <window.IconX size={18} />
          </button>
        </div>
        <div style={{ position: 'relative', aspectRatio: '16 / 9', borderRadius: 'var(--radius-lg)', overflow: 'hidden', border: '1px solid var(--border-strong)', background: '#000', boxShadow: 'var(--shadow-lg)' }}>
          {src ? (
            <iframe src={src} title="Monjez video" allow="autoplay; fullscreen" allowFullScreen
              style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', border: 0 }} />
          ) : (
            <div style={{ position: 'absolute', inset: 0, display: 'grid', placeItems: 'center', textAlign: 'center', background: 'radial-gradient(80% 100% at 50% 0%, rgba(37,99,235,0.22), transparent 60%), var(--graphite)' }}>
              <div>
                <div style={{ fontFamily: 'var(--font-mono)', fontSize: 12.5, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--blue-400)', marginBottom: 14 }}>Video placeholder</div>
                <div style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 26, marginBottom: 10 }}>Your Loom embed goes here</div>
                <div style={{ color: 'var(--text-secondary)', fontSize: 15, maxWidth: 420, margin: '0 auto' }}>
                  Paste your Loom embed URL into <span style={{ fontFamily: 'var(--font-mono)', color: 'var(--cloud-white)' }}>LOOM_EMBED</span> in <span style={{ fontFamily: 'var(--font-mono)', color: 'var(--cloud-white)' }}>js/data.jsx</span>. It plays right here — no leaving the page.
                </div>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, {
  Container, Eyebrow, Accent, Reveal, SectionHead, WindowChrome, PlayButton, VideoModal,
  scrollToId, playVideo, MJ_MAXW: MAXW,
});

// Alias DS components onto window so sibling babel scripts can use <window.Card> etc.
(function aliasDS() {
  const NS = window.MonjezDesignSystem_019de9;
  if (!NS) return setTimeout(aliasDS, 20);
  Object.assign(window, { Card: NS.Card, MetricCard: NS.MetricCard });
})();
