// Main app — ties acts together, custom cursor, intro, lang toggle

const { ActHero, ActCraft, ActColors, ActMaalem, ActPackaging, ActContact, ActFooter, ProductPage } = window;
const PRODUCT_ROUTE_SLUGS = ['fes', 'chefchaouen', 'marrakech'];

function CustomCursor() {
  const { isTouch } = useResponsive();
  const dotRef = useRef(null);
  const ringRef = useRef(null);
  const targetRef = useRef({ x: 0, y: 0 });
  const ringRef2 = useRef({ x: 0, y: 0 });

  useEffect(() => {
    if (isTouch) return;
    const onMove = e => {
      targetRef.current = { x: e.clientX, y: e.clientY };
      if (dotRef.current) {
        dotRef.current.style.left = e.clientX + 'px';
        dotRef.current.style.top = e.clientY + 'px';
      }
    };
    const onHoverIn = e => {
      if (e.target.closest('a, button, [data-cursor="hover"]')) {
        ringRef.current?.classList.add('hover');
      }
    };
    const onHoverOut = e => {
      if (e.target.closest('a, button, [data-cursor="hover"]')) {
        ringRef.current?.classList.remove('hover');
      }
    };
    let raf;
    const animate = () => {
      ringRef2.current.x += (targetRef.current.x - ringRef2.current.x) * 0.15;
      ringRef2.current.y += (targetRef.current.y - ringRef2.current.y) * 0.15;
      if (ringRef.current) {
        ringRef.current.style.left = ringRef2.current.x + 'px';
        ringRef.current.style.top = ringRef2.current.y + 'px';
      }
      raf = requestAnimationFrame(animate);
    };
    animate();
    window.addEventListener('mousemove', onMove);
    document.addEventListener('mouseover', onHoverIn);
    document.addEventListener('mouseout', onHoverOut);
    return () => {
      window.removeEventListener('mousemove', onMove);
      document.removeEventListener('mouseover', onHoverIn);
      document.removeEventListener('mouseout', onHoverOut);
      cancelAnimationFrame(raf);
    };
  }, [isTouch]);

  // Bind existing DOM elements
  useEffect(() => {
    dotRef.current = document.getElementById('cursor-dot');
    ringRef.current = document.getElementById('cursor-ring');
  }, []);
  return null;
}

function Intro({ lang }) {
  const [done, setDone] = useState(false);
  const [phase, setPhase] = useState(0);
  useEffect(() => {
    const t1 = setTimeout(() => setPhase(1), 300);
    const t2 = setTimeout(() => setPhase(2), 1100);
    const t3 = setTimeout(() => setDone(true), 2400);
    return () => [t1,t2,t3].forEach(clearTimeout);
  }, []);

  const isAR = lang === 'ar';
  return (
    <div style={{
      position: 'fixed', inset: 0,
      background: '#000',
      zIndex: 1000,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      pointerEvents: done ? 'none' : 'all',
      transform: done ? 'translateY(-100%)' : 'translateY(0)',
      transition: 'transform 1.3s cubic-bezier(0.77,0,0.175,1)'
    }}>
      <div style={{ textAlign: 'center' }}>
        <div style={{
          fontFamily: isAR ? 'var(--font-ar)' : 'var(--font-mono)',
          fontSize: isAR ? 14 : 10,
          letterSpacing: isAR ? '0.05em' : '0.3em',
          color: 'var(--fg-dim)',
          marginBottom: 40,
          opacity: phase >= 1 ? 1 : 0,
          transition: 'opacity 0.8s'
        }}>
          {isAR ? 'المدينة القديمة، فاس — المغرب' : 'EST. MMXXIV — MÉDINA DE FÈS'}
        </div>
        <img
          src="images/logo-dark.png"
          alt=""
          style={{
            width: 'clamp(120px, 18vw, 220px)',
            height: 'auto',
            filter: 'invert(1)',
            opacity: phase >= 2 ? 1 : 0,
            transform: phase >= 2 ? 'translateY(0) scale(1)' : 'translateY(20px) scale(0.95)',
            transition: 'opacity 1s, transform 1.2s cubic-bezier(0.22,0.61,0.36,1)'
          }}
        />
        <div style={{
          fontFamily: 'var(--font-serif)',
          fontSize: 'clamp(24px, 4.2vw, 44px)',
          fontWeight: 400,
          letterSpacing: '0.12em',
          color: 'var(--fg)',
          marginTop: 24,
          opacity: phase >= 2 ? 1 : 0,
          transform: phase >= 2 ? 'translateY(0)' : 'translateY(14px)',
          transition: 'opacity 1s 0.18s, transform 1.2s 0.18s cubic-bezier(0.22,0.61,0.36,1)'
        }}>
          Belgham
        </div>
      </div>
    </div>
  );
}

function Progress() { return null; }

const WAITLIST_JOINED_KEY = 'belgham-waitlist-joined';
const WAITLIST_DISMISSED_KEY = 'belgham-waitlist-dismissed';

function WaitlistForm({ lang, source, variant = 'modal', onDone }) {
  const content = window.CONTENT[lang].waitlist;
  const isRTL = lang === 'ar';
  const isSection = variant === 'section';
  const [email, setEmail] = useState('');
  const [status, setStatus] = useState('idle');
  const [joined, setJoined] = useState(false);
  const [message, setMessage] = useState('');

  useEffect(() => {
    const syncJoined = () => {
      setJoined(!!localStorage.getItem(WAITLIST_JOINED_KEY));
    };
    syncJoined();
    window.addEventListener('belgham:waitlist-joined', syncJoined);
    window.addEventListener('storage', syncJoined);
    return () => {
      window.removeEventListener('belgham:waitlist-joined', syncJoined);
      window.removeEventListener('storage', syncJoined);
    };
  }, []);

  const submit = async event => {
    event.preventDefault();
    const normalized = email.trim().toLowerCase();
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(normalized)) {
      setMessage(content.error);
      return;
    }

    setStatus('submitting');
    setMessage('');

    try {
      const response = await fetch('/api/waitlist', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          email: normalized,
          lang,
          source
        })
      });

      if (!response.ok) throw new Error('waitlist failed');

      localStorage.setItem(WAITLIST_JOINED_KEY, normalized);
      localStorage.removeItem(WAITLIST_DISMISSED_KEY);
      window.dispatchEvent(new CustomEvent('belgham:waitlist-joined'));
      setJoined(true);
      setStatus('success');
      if (onDone) onDone();
    } catch (error) {
      setStatus('idle');
      setMessage(content.serverError);
    }
  };

  if (joined || status === 'success') {
    return (
      <div style={{ fontFamily: isRTL ? 'var(--font-ar)' : 'var(--font-sans)' }}>
        <div className="mono" style={{
          color: 'var(--yellow)',
          fontSize: 10,
          letterSpacing: isRTL ? '0' : '0.22em',
          marginBottom: 18,
          fontFamily: isRTL ? 'var(--font-ar)' : 'var(--font-mono)'
        }}>
          {content.eyebrow}
        </div>
        <h2 style={{
          fontFamily: isRTL ? 'var(--font-ar)' : 'var(--font-serif)',
          fontWeight: 400,
          fontSize: isSection ? 'clamp(36px, 5vw, 72px)' : 'clamp(34px, 4.2vw, 52px)',
          lineHeight: 0.96,
          marginBottom: 18
        }}>
          {content.successTitle}
        </h2>
        <p style={{
          color: 'rgba(250,250,247,0.68)',
          lineHeight: 1.7,
          fontSize: isSection ? 16 : 15,
          maxWidth: isSection ? 460 : 360
        }}>
          {content.successBody}
        </p>
      </div>
    );
  }

  return (
    <form onSubmit={submit} style={{
      width: '100%',
      display: 'flex',
      flexDirection: isSection ? 'row' : 'column',
      gap: isSection ? 10 : 12,
      alignItems: 'stretch'
    }}>
      <label style={{ display: 'block', flex: '1 1 auto', minWidth: 0 }}>
        <span style={{ position: 'absolute', width: 1, height: 1, overflow: 'hidden', clip: 'rect(0 0 0 0)' }}>
          {content.placeholder}
        </span>
        <input
          type="email"
          autoComplete="email"
          inputMode="email"
          value={email}
          onChange={event => setEmail(event.target.value)}
          placeholder={content.placeholder}
          style={{
            width: '100%',
            minHeight: 58,
            border: '1px solid rgba(250,250,247,0.2)',
            background: 'linear-gradient(180deg, rgba(255,255,255,0.075), rgba(255,255,255,0.035))',
            color: 'var(--fg)',
            padding: '0 18px',
            fontSize: 16,
            outline: 'none',
            fontFamily: 'var(--font-sans)',
            direction: 'ltr',
            textAlign: isRTL ? 'right' : 'left',
            boxShadow: 'inset 0 1px 0 rgba(255,255,255,0.08)'
          }}
        />
      </label>
      <button
        type="submit"
        data-cursor="hover"
        disabled={status === 'submitting'}
        style={{
          minHeight: 58,
          flex: isSection ? '0 0 auto' : '1 1 auto',
          border: '1px solid rgba(250,250,247,0.82)',
          background: 'linear-gradient(135deg, #fafaf7 0%, #d8c39a 48%, #fafaf7 100%)',
          backgroundSize: '180% 180%',
          color: '#07070a',
          padding: isSection ? '0 28px' : '0 18px',
          fontFamily: isRTL ? 'var(--font-ar)' : 'var(--font-mono)',
          fontSize: isRTL ? 15 : 11,
          letterSpacing: isRTL ? '0' : '0.18em',
          textTransform: isRTL ? 'none' : 'uppercase',
          opacity: status === 'submitting' ? 0.72 : 1,
          cursor: 'none',
          whiteSpace: 'nowrap',
          boxShadow: '0 18px 40px rgba(233,185,58,0.16)'
        }}
      >
        {status === 'submitting' ? content.submitting : content.submit}
      </button>
      {message && (
        <div style={{
          flexBasis: '100%',
          color: 'var(--yellow)',
          fontSize: 13,
          lineHeight: 1.5,
          fontFamily: isRTL ? 'var(--font-ar)' : 'var(--font-sans)'
        }}>
          {message}
        </div>
      )}
    </form>
  );
}

function WaitlistModal({ lang, suppressAutoOpen = false }) {
  const content = window.CONTENT[lang].waitlist;
  const { isPhone, isTablet } = useResponsive();
  const isRTL = lang === 'ar';
  const [open, setOpen] = useState(false);
  const [joined, setJoined] = useState(false);

  useEffect(() => {
    const show = () => {
      setJoined(!!localStorage.getItem(WAITLIST_JOINED_KEY));
      setOpen(true);
    };
    const hasJoined = localStorage.getItem(WAITLIST_JOINED_KEY);
    const hasDismissed = localStorage.getItem(WAITLIST_DISMISSED_KEY);
    const timer = suppressAutoOpen ? null : setTimeout(() => {
      if (!hasJoined && !hasDismissed) show();
    }, 2900);

    window.addEventListener('belgham:open-waitlist', show);
    return () => {
      if (timer) clearTimeout(timer);
      window.removeEventListener('belgham:open-waitlist', show);
    };
  }, [suppressAutoOpen]);

  useEffect(() => {
    if (!open) return;
    const onKey = event => {
      if (event.key === 'Escape') close();
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open]);

  const close = () => {
    localStorage.setItem(WAITLIST_DISMISSED_KEY, '1');
    setOpen(false);
  };

  if (!open) return null;

  return (
    <div
      role="dialog"
      aria-modal="true"
      aria-labelledby="waitlist-title"
      style={{
        position: 'fixed',
        inset: 0,
        zIndex: 1200,
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        padding: isPhone ? '18px' : '40px',
        background: 'radial-gradient(circle at 72% 45%, rgba(233,185,58,0.17), transparent 30%), rgba(0,0,0,0.74)',
        backdropFilter: 'blur(22px) saturate(140%)',
        WebkitBackdropFilter: 'blur(22px) saturate(140%)',
        direction: isRTL ? 'rtl' : 'ltr'
      }}
      onMouseDown={event => {
        if (event.target === event.currentTarget) close();
      }}
    >
      <div
        style={{
          width: isPhone ? 'min(100%, 370px)' : 'min(100%, 920px)',
          minHeight: isPhone ? 'auto' : 520,
          maxHeight: isPhone ? 'calc(100svh - 36px)' : 'none',
          display: 'grid',
          gridTemplateColumns: isPhone ? '1fr' : isTablet ? '1fr 0.78fr' : '1.04fr 0.96fr',
          background: 'linear-gradient(145deg, rgba(16,16,18,0.98), rgba(5,5,7,0.98))',
          border: '1px solid rgba(250,250,247,0.18)',
          boxShadow: '0 38px 120px rgba(0,0,0,0.62)',
          color: 'var(--fg)',
          position: 'relative',
          overflow: 'hidden',
          overflowY: isPhone ? 'auto' : 'hidden',
          fontFamily: isRTL ? 'var(--font-ar)' : 'var(--font-sans)'
        }}
      >
        <button
          type="button"
          aria-label={content.close}
          data-cursor="hover"
          onClick={close}
          style={{
            position: 'absolute',
            top: isPhone ? 14 : 18,
            right: isRTL ? 'auto' : (isPhone ? 14 : 18),
            left: isRTL ? (isPhone ? 14 : 18) : 'auto',
            zIndex: 5,
            width: 36,
            height: 36,
            borderRadius: '50%',
            border: '1px solid rgba(250,250,247,0.42)',
            background: isPhone ? 'rgba(5,5,6,0.72)' : 'rgba(255,255,255,0.04)',
            color: 'var(--fg)',
            fontSize: 20,
            lineHeight: '34px',
            boxShadow: isPhone ? '0 10px 24px rgba(0,0,0,0.42)' : 'none',
            backdropFilter: 'blur(10px)',
            WebkitBackdropFilter: 'blur(10px)',
            cursor: 'none'
          }}
        >
          ×
        </button>

        {isPhone && (
          <div style={{
            position: 'relative',
            height: 156,
            overflow: 'hidden',
            borderBottom: '1px solid rgba(250,250,247,0.12)',
            background: '#050506'
          }}>
            <img
              src="images/city-bg-fes-tannery.webp"
              alt=""
              style={{
                position: 'absolute',
                inset: 0,
                width: '100%',
                height: '100%',
                objectFit: 'cover',
                opacity: 0.34,
                filter: 'contrast(1.08) saturate(0.86)'
              }}
            />
            <div style={{
              position: 'absolute',
              inset: 0,
              background: 'linear-gradient(180deg, rgba(5,5,6,0.18), rgba(5,5,6,0.86)), radial-gradient(circle at 62% 48%, rgba(233,185,58,0.32), transparent 42%)'
            }} />
            <img
              src="images/belgha-360/frame-001.webp"
              alt=""
              style={{
                position: 'absolute',
                left: isRTL ? '38%' : '62%',
                top: '52%',
                width: 'min(76vw, 300px)',
                transform: `translate(-50%, -50%) rotate(${isRTL ? 7 : -7}deg)`,
                filter: 'drop-shadow(0 24px 34px rgba(0,0,0,0.62))'
              }}
            />
            <div className="mono" style={{
              position: 'absolute',
              left: 22,
              right: 22,
              bottom: 16,
              display: 'flex',
              justifyContent: 'space-between',
              color: 'rgba(250,250,247,0.58)',
              fontSize: 9,
              letterSpacing: isRTL ? 0 : '0.14em',
              fontFamily: isRTL ? 'var(--font-ar)' : 'var(--font-mono)'
            }}>
              <span>{isRTL ? 'أصفر فاس' : 'FÈS YELLOW'}</span>
              <span>{isRTL ? 'الإصدار ٠١' : 'DROP 01'}</span>
            </div>
          </div>
        )}

        <div style={{
          padding: isPhone ? '24px 22px 22px' : '54px 52px 44px',
          display: 'flex',
          flexDirection: 'column',
          justifyContent: 'center',
          minWidth: 0
        }}>
          {joined ? (
            <div style={{ fontFamily: isRTL ? 'var(--font-ar)' : 'var(--font-sans)' }}>
              <div className="mono" style={{
                color: 'var(--yellow)',
                fontSize: 10,
                letterSpacing: isRTL ? '0' : '0.22em',
                marginBottom: 18,
                fontFamily: isRTL ? 'var(--font-ar)' : 'var(--font-mono)'
              }}>
                {content.eyebrow}
              </div>
              <h2 id="waitlist-title" style={{
                fontFamily: isRTL ? 'var(--font-ar)' : 'var(--font-serif)',
                fontWeight: 400,
                fontSize: isPhone ? 34 : 'clamp(46px, 5vw, 68px)',
                lineHeight: 0.92,
                marginBottom: isPhone ? 16 : 20,
                maxWidth: 520
              }}>
                {content.successTitle}
              </h2>
              <p style={{
                color: 'rgba(250,250,247,0.68)',
                lineHeight: 1.75,
                fontSize: isPhone ? 15 : 16,
                maxWidth: 430,
                marginBottom: 28
              }}>
                {content.successBody}
              </p>
              <button
                type="button"
                data-cursor="hover"
                onClick={close}
                style={{
                  minHeight: 56,
                  border: '1px solid rgba(250,250,247,0.82)',
                  background: 'linear-gradient(135deg, #fafaf7 0%, #d8c39a 48%, #fafaf7 100%)',
                  color: '#07070a',
                  padding: '0 24px',
                  fontFamily: isRTL ? 'var(--font-ar)' : 'var(--font-mono)',
                  fontSize: isRTL ? 15 : 11,
                  letterSpacing: isRTL ? '0' : '0.18em',
                  textTransform: isRTL ? 'none' : 'uppercase',
                  cursor: 'none'
                }}
              >
                {content.close}
              </button>
            </div>
          ) : (
            <>
              <div className="mono" style={{
                color: 'var(--yellow)',
                fontSize: 10,
                letterSpacing: isRTL ? '0' : '0.22em',
                marginBottom: 18,
                fontFamily: isRTL ? 'var(--font-ar)' : 'var(--font-mono)'
              }}>
                {content.eyebrow}
              </div>
              <h2 id="waitlist-title" style={{
                fontFamily: isRTL ? 'var(--font-ar)' : 'var(--font-serif)',
                fontWeight: 400,
                fontSize: isPhone ? 36 : 'clamp(52px, 5.6vw, 78px)',
                lineHeight: 0.9,
                marginBottom: isPhone ? 16 : 22,
                maxWidth: 520
              }}>
                {content.title}
              </h2>
              <p style={{
                color: 'rgba(250,250,247,0.68)',
                lineHeight: 1.75,
                fontSize: isPhone ? 15 : 16,
                maxWidth: 430,
                marginBottom: isPhone ? 22 : 30
              }}>
                {content.body}
              </p>
              <WaitlistForm
                lang={lang}
                source="opening-popup"
                onDone={() => setJoined(true)}
              />
              <div style={{ color: 'rgba(250,250,247,0.44)', fontSize: 12, marginTop: 16, lineHeight: 1.5 }}>
                {content.privacy}
              </div>
            </>
          )}
        </div>

        {!isPhone && (
          <div style={{
            position: 'relative',
            minHeight: 520,
            borderLeft: isRTL ? 'none' : '1px solid rgba(250,250,247,0.1)',
            borderRight: isRTL ? '1px solid rgba(250,250,247,0.1)' : 'none',
            overflow: 'hidden',
            background: '#050506'
          }}>
            <img
              src="images/city-bg-fes-tannery.webp"
              alt=""
              style={{
                position: 'absolute',
                inset: 0,
                width: '100%',
                height: '100%',
                objectFit: 'cover',
                opacity: 0.32,
                filter: 'contrast(1.08) saturate(0.86)'
              }}
            />
            <div style={{
              position: 'absolute',
              inset: 0,
              background: 'linear-gradient(180deg, rgba(5,5,6,0.28), rgba(5,5,6,0.84)), radial-gradient(circle at 48% 52%, rgba(233,185,58,0.24), transparent 38%)'
            }} />
            <img
              src="images/belgha-360/frame-001.webp"
              alt=""
              style={{
                position: 'absolute',
                left: '50%',
                top: '49%',
                width: 'min(88%, 430px)',
                transform: 'translate(-50%, -50%) rotate(-8deg)',
                filter: 'drop-shadow(0 38px 54px rgba(0,0,0,0.62))'
              }}
            />
            <div className="mono" style={{
              position: 'absolute',
              left: 30,
              right: 30,
              bottom: 28,
              display: 'flex',
              justifyContent: 'space-between',
              gap: 18,
              color: 'rgba(250,250,247,0.62)',
              fontSize: 10,
              letterSpacing: isRTL ? 0 : '0.16em',
              fontFamily: isRTL ? 'var(--font-ar)' : 'var(--font-mono)'
            }}>
              <span>{isRTL ? 'رابط خاص' : 'PRIVATE LINK'}</span>
              <span>{isRTL ? 'إصدار محدود' : 'LIMITED DROP'}</span>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

function WaitlistSection({ lang }) {
  const content = window.CONTENT[lang].waitlist;
  const { isPhone, isTablet } = useResponsive();
  const isRTL = lang === 'ar';

  return (
    <section id="whitelist" style={{
      position: 'relative',
      minHeight: isPhone ? '92svh' : '96vh',
      overflow: 'hidden',
      background: '#050506',
      color: 'var(--fg)',
      direction: isRTL ? 'rtl' : 'ltr'
    }}>
      <img
        src="images/city-bg-fes-tannery.webp"
        alt=""
        style={{
          position: 'absolute',
          inset: 0,
          width: '100%',
          height: '100%',
          objectFit: 'cover',
          opacity: isPhone ? 0.28 : 0.36,
          filter: 'contrast(1.08) saturate(0.92)'
        }}
      />
      <div style={{
        position: 'absolute',
        inset: 0,
        background: isPhone
          ? 'linear-gradient(180deg, rgba(5,5,6,0.82), rgba(5,5,6,0.95) 58%, rgba(5,5,6,0.98)), radial-gradient(circle at 50% 24%, rgba(233,185,58,0.18), transparent 44%)'
          : 'linear-gradient(90deg, rgba(5,5,6,0.95) 0%, rgba(5,5,6,0.76) 48%, rgba(5,5,6,0.9) 100%), radial-gradient(circle at 75% 58%, rgba(233,185,58,0.22), transparent 34%)'
      }} />
      <img
        src="images/packaging-open-angle-clean.png"
        alt=""
        style={{
          position: 'absolute',
          right: isRTL ? 'auto' : (isPhone ? '-28vw' : '5vw'),
          left: isRTL ? (isPhone ? '-28vw' : '5vw') : 'auto',
          bottom: isPhone ? '-3vh' : '5vh',
          width: isPhone ? '108vw' : isTablet ? '54vw' : '48vw',
          maxWidth: 820,
          opacity: isPhone ? 0.26 : 0.56,
          transform: isRTL ? 'scaleX(-1) rotate(1.5deg)' : 'rotate(1.5deg)',
          filter: 'saturate(0.86) brightness(0.78) contrast(1.08) drop-shadow(0 42px 70px rgba(0,0,0,0.68))',
          pointerEvents: 'none'
        }}
      />

      <div style={{
        position: 'relative',
        zIndex: 1,
        minHeight: isPhone ? '92svh' : '96vh',
        display: 'grid',
        gridTemplateColumns: isPhone ? '1fr' : 'minmax(0, 0.9fr) minmax(360px, 0.76fr)',
        alignItems: 'center',
        gap: isPhone ? 30 : '8vw',
        padding: isPhone ? '86px 24px 54px' : isTablet ? '12vh 6vw' : '13vh 7vw',
        maxWidth: 1680,
        margin: '0 auto'
      }}>
        <div style={{ maxWidth: isPhone ? 'none' : 760 }}>
          <div className="mono" style={{
            color: 'var(--yellow)',
            fontSize: 10,
            letterSpacing: isRTL ? '0' : '0.24em',
            marginBottom: 24,
            fontFamily: isRTL ? 'var(--font-ar)' : 'var(--font-mono)'
          }}>
            {content.sectionEyebrow}
          </div>
          <h2 style={{
            fontFamily: isRTL ? 'var(--font-ar)' : 'var(--font-serif)',
            fontWeight: 400,
            fontSize: isPhone ? 'clamp(48px, 14vw, 72px)' : isTablet ? 'clamp(62px, 8vw, 104px)' : 'clamp(82px, 8.6vw, 140px)',
            lineHeight: 0.86,
            maxWidth: isPhone ? 500 : 880,
            marginBottom: isPhone ? 24 : 34
          }}>
            {content.sectionTitle}
          </h2>
          <p style={{
            color: 'rgba(250,250,247,0.68)',
            fontSize: isPhone ? 15 : 17,
            lineHeight: 1.78,
            maxWidth: 560,
            fontFamily: isRTL ? 'var(--font-ar)' : 'var(--font-sans)',
            marginBottom: isPhone ? 24 : 34
          }}>
            {content.sectionBody}
          </p>
          <div style={{
            width: '100%',
            maxWidth: isPhone ? 'none' : 620,
            marginBottom: isPhone ? 18 : 24
          }}>
            <WaitlistForm lang={lang} source="pre-footer-section" variant={isPhone ? 'modal' : 'section'} />
            <div style={{
              marginTop: 14,
              color: 'rgba(250,250,247,0.46)',
              fontSize: 12,
              lineHeight: 1.6,
              fontFamily: isRTL ? 'var(--font-ar)' : 'var(--font-sans)'
            }}>
              {content.privacy}
            </div>
          </div>
          <div className="mono" style={{
            color: 'rgba(250,250,247,0.5)',
            fontSize: isPhone ? 9 : 10,
            letterSpacing: isRTL ? '0' : '0.14em',
            lineHeight: 1.8,
            maxWidth: 620,
            fontFamily: isRTL ? 'var(--font-ar)' : 'var(--font-mono)'
          }}>
            {content.sectionNote}
          </div>
        </div>

        <div style={{
          display: isPhone ? 'none' : 'block',
          alignSelf: 'stretch',
          minHeight: isTablet ? 420 : 560
        }} aria-hidden="true" />
      </div>
    </section>
  );
}

function Nav({ lang, setLang }) {
  const content = window.CONTENT[lang];
  const { isPhone, isTablet } = useResponsive();
  const openWaitlist = () => {
    window.dispatchEvent(new CustomEvent('belgham:open-waitlist'));
  };
  return (
    <nav style={{
      position: 'fixed', top: 0, left: 0, right: 0,
      padding: isPhone
        ? 'calc(18px + env(safe-area-inset-top)) max(20px, env(safe-area-inset-right)) 14px max(20px, env(safe-area-inset-left))'
        : isTablet ? '22px 30px' : '20px 40px',
      display: 'flex', justifyContent: 'space-between', alignItems: 'center',
      zIndex: 800,
      mixBlendMode: 'difference',
      color: '#fff',
      flexDirection: lang === 'ar' ? 'row-reverse' : 'row'
    }}>
      <a href="#top" aria-label="Belgham" style={{ display: 'flex', alignItems: 'center', height: isPhone ? 32 : 36 }}>
        <img src="images/logo-dark.png" alt="Belgham" style={{
          height: isPhone ? 31 : 36, width: 'auto', display: 'block',
          filter: 'invert(1)'
        }} />
      </a>
      <div style={{
        display: isPhone ? 'none' : 'flex',
        gap: isTablet ? 20 : 32,
        alignItems: 'center',
        fontSize: 11,
        letterSpacing: lang === 'ar' ? '0.05em' : '0.2em',
        textTransform: lang === 'ar' ? 'none' : 'uppercase',
        fontFamily: lang === 'ar' ? 'var(--font-ar)' : 'var(--font-mono)',
        flexDirection: lang === 'ar' ? 'row-reverse' : 'row'
      }}>
        <a href="#craft" data-cursor="hover" style={{ color: 'inherit', textDecoration: 'none', opacity: 0.8 }}>{content.navCraft}</a>
        <a href="#collection" data-cursor="hover" style={{ color: 'inherit', textDecoration: 'none', opacity: 0.8 }}>{content.navCollection}</a>
        <a href="#about" data-cursor="hover" style={{ color: 'inherit', textDecoration: 'none', opacity: 0.8 }}>{content.navAbout}</a>
        <a href="#contact" data-cursor="hover" style={{ color: 'inherit', textDecoration: 'none', opacity: 0.8 }}>{content.navContact}</a>
        <button onClick={openWaitlist} data-cursor="hover" style={{
          display: 'inline-flex',
          alignItems: 'center',
          justifyContent: 'center',
          minHeight: 44,
          background: 'rgba(255,255,255,0.08)',
          border: '1px solid rgba(255,255,255,0.42)',
          color: 'inherit',
          font: 'inherit',
          letterSpacing: 'inherit',
          lineHeight: 1,
          textTransform: 'inherit',
          opacity: 1,
          padding: '0 18px',
          cursor: 'none'
        }}>{content.navWaitlist}</button>
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: isPhone ? 8 : 10, fontSize: isPhone ? 11 : 12, letterSpacing: '0.1em' }}>
        {isPhone && (
          <button onClick={openWaitlist} data-cursor="hover" style={{
            display: 'inline-flex',
            alignItems: 'center',
            justifyContent: 'center',
            minHeight: 38,
            background: 'linear-gradient(135deg, rgba(255,255,255,0.2), rgba(255,255,255,0.05))',
            border: '1px solid rgba(255,255,255,0.5)',
            color: 'inherit',
            fontFamily: lang === 'ar' ? 'var(--font-ar)' : 'var(--font-mono)',
            fontSize: lang === 'ar' ? 13 : 10,
            letterSpacing: lang === 'ar' ? '0' : '0.12em',
            textTransform: lang === 'ar' ? 'none' : 'uppercase',
            lineHeight: 1,
            padding: '0 11px',
            cursor: isPhone ? 'auto' : 'none'
          }}>{content.navWaitlist}</button>
        )}
        <button onClick={() => setLang('en')} data-cursor="hover" style={{
          background: 'none', border: 'none', color: 'inherit',
          fontFamily: 'var(--font-mono)', fontSize: isPhone ? 11 : 12,
          opacity: lang === 'en' ? 1 : 0.4, padding: '8px 3px', cursor: isPhone ? 'auto' : 'none'
        }}>EN</button>
        <span style={{ opacity: 0.4 }}>/</span>
        <button onClick={() => setLang('ar')} data-cursor="hover" style={{
          background: 'none', border: 'none', color: 'inherit',
          fontFamily: 'var(--font-ar)', fontSize: isPhone ? 17 : 18,
          opacity: lang === 'ar' ? 1 : 0.4, padding: '8px 3px', cursor: isPhone ? 'auto' : 'none'
        }}>ع</button>
      </div>
    </nav>
  );
}

function App() {
  const [tweaks, setTweak] = window.useTweaks({
    motionIntensity: 'standard',
    heroColorway: 'fes',
    showCallouts: true,
    cursorStyle: 'minimal'
  });
  const [lang, setLang] = useState('en');
  const [productIndex, setProductIndex] = useState(null);

  useEffect(() => {
    document.documentElement.lang = lang;
    document.documentElement.classList.toggle('rtl', lang === 'ar');
    document.body.style.direction = lang === 'ar' ? 'rtl' : 'ltr';
  }, [lang]);

  useEffect(() => {
    const syncProductRoute = () => {
      const slug = window.location.hash.replace(/^#product-/, '');
      const index = PRODUCT_ROUTE_SLUGS.indexOf(slug);
      setProductIndex(window.location.hash.startsWith('#product-') && index >= 0 ? index : null);
    };

    syncProductRoute();
    window.addEventListener('hashchange', syncProductRoute);
    window.addEventListener('popstate', syncProductRoute);
    return () => {
      window.removeEventListener('hashchange', syncProductRoute);
      window.removeEventListener('popstate', syncProductRoute);
    };
  }, []);

  const openProduct = useCallback(index => {
    const slug = PRODUCT_ROUTE_SLUGS[index] || PRODUCT_ROUTE_SLUGS[0];
    window.history.pushState(null, '', `#product-${slug}`);
    setProductIndex(index);
  }, []);

  const closeProduct = useCallback(() => {
    window.history.pushState(null, '', '#collection');
    setProductIndex(null);
  }, []);

  // Remove original HTML placeholder intro overlay
  useEffect(() => {
    const intro = document.getElementById('intro');
    if (intro) intro.remove();
    const nav = document.querySelector('nav.nav');
    if (nav) nav.remove();
  }, []);

  return (
    <>
      <Intro lang={lang} />
      <CustomCursor />
      <Progress />
      <Nav lang={lang} setLang={setLang} />
      <WaitlistModal lang={lang} suppressAutoOpen={productIndex !== null} />

      <ActHero lang={lang} tweaks={tweaks} />
      <ActCraft lang={lang} />
      <ActColors lang={lang} tweaks={tweaks} onDiscoverProduct={openProduct} />
      <ActMaalem lang={lang} />
      <ActPackaging lang={lang} />
      <WaitlistSection lang={lang} />
      <ActContact lang={lang} />
      <ActFooter lang={lang} />

      {productIndex !== null && ProductPage && (
        <ProductPage lang={lang} productIndex={productIndex} onClose={closeProduct} />
      )}

      <window.TweaksPanel title="Tweaks">
        <window.TweakSection label="Hero" />
        <window.TweakRadio
          label="Door colorway"
          value={tweaks.heroColorway}
          options={['fes', 'chefchaouen', 'marrakech']}
          onChange={v => setTweak('heroColorway', v)}
        />
        <window.TweakSection label="Motion" />
        <window.TweakToggle
          label="Show 360° callouts"
          value={tweaks.showCallouts}
          onChange={v => setTweak('showCallouts', v)}
        />
      </window.TweaksPanel>
    </>
  );
}

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