// ============================================================
// Casa IS — page sections
// ============================================================
const { useState: useS, useEffect: useE, useRef: useR, useMemo } = React;

// ---------------- NAV ----------------
function Nav({ lang, setLang, active, onNavigate, cartCount = 0, onCartClick }) {
  return (
    <nav className="nav">
      <div className="nav__brand wordmark" onClick={() => onNavigate('home')} style={{ cursor: 'pointer' }}>
        casa IS
        <sup>est. '24</sup>
      </div>
      <div className="nav__links">
        {NAV_ITEMS.map((it) => (
          <button
            key={it.id}
            className={active === it.id ? 'is-active' : ''}
            onClick={() => onNavigate(it.id)}
          >
            {t(lang, it)}
          </button>
        ))}
      </div>
      <div className="nav__right">
        <div className="lang-toggle" role="tablist" aria-label="language">
          <button className={lang === 'es' ? 'is-active' : ''} onClick={() => setLang('es')}>ES</button>
          <button className={lang === 'en' ? 'is-active' : ''} onClick={() => setLang('en')}>EN</button>
        </div>
        <button className="nav__cart" aria-label="cart" onClick={onCartClick}>
          <span>{lang === 'es' ? 'Bolsa' : 'Bag'}</span>
          <span style={{ opacity: cartCount > 0 ? 1 : 0.55, color: cartCount > 0 ? 'var(--accent)' : undefined }}>({cartCount})</span>
        </button>
      </div>
    </nav>
  );
}

// ---------------- HERO ----------------
function Hero({ lang, variant = 'framed' }) {
  return (
    <section id="home" data-screen-label="Hero" className={`hero hero--${variant}`}>
      {variant === 'framed' && (
        <div className="hero__inner">
          <div className="hero__frame">
            <div>
              <div className="label" style={{ marginBottom: 18, opacity: 0.55 }}>
                {lang === 'es' ? 'Galería sin paredes · est. 2024' : 'Gallery without walls · est. 2024'}
              </div>
              <div className="hero__name wordmark">
                casa IS
                <span className="by">{t(lang, HERO.by)}</span>
              </div>
              <p className="hero__tagline">{t(lang, HERO.tagline)}</p>
              <div style={{ display: 'flex', gap: 12, marginTop: 28, flexWrap: 'wrap' }}>
                <a href="#collections" className="btn btn--solid">
                  {lang === 'es' ? 'Ver colecciones' : 'Browse collections'}
                </a>
                <a href="#commissions" className="btn">
                  {lang === 'es' ? 'Encargar una pieza' : 'Commission a piece'}
                </a>
              </div>
            </div>
            <Placeholder
              src="assets/isabel-portrait.png"
              alt="Isabel Sofía Lara Díaz"
              label={lang === 'es' ? 'retrato · isabel sofía' : 'portrait · isabel sofía'}
              className="hero__portrait"
            />
          </div>
        </div>
      )}

      {variant === 'asym' && (
        <div className="hero__inner">
          <div className="label" style={{ opacity: 0.55, marginBottom: 8 }}>
            {lang === 'es' ? 'Estudio · Bogotá' : 'Studio · Bogotá'}
          </div>
          <div className="hero__title-block">
            <div className="hero__name wordmark">
              casa IS<span style={{ fontSize: '0.18em', verticalAlign: 'super', marginLeft: 8, opacity: 0.5, fontStyle: 'normal', letterSpacing: '0.2em', fontFamily: 'var(--sans)' }}>™</span>
            </div>
            <Placeholder src="assets/isabel-portrait.png" alt="Isabel Sofía" label={lang === 'es' ? 'retrato' : 'portrait'} className="hero__portrait" />
          </div>
          <div className="hero__by-line">
            <div className="serif italic" style={{ fontSize: 'clamp(20px, 2vw, 28px)' }}>
              {t(lang, HERO.by)} —
              <span style={{ opacity: 0.7 }}> {t(lang, HERO.tagline)}</span>
            </div>
            <div style={{ display: 'flex', gap: 12 }}>
              <a href="#collections" className="btn btn--accent">
                {lang === 'es' ? 'Colecciones' : 'Collections'}
              </a>
            </div>
          </div>
        </div>
      )}

      {variant === 'bleed' && (
        <div className="hero__inner">
          <Placeholder
            src="assets/isabel-portrait.png"
            alt="Isabel Sofía"
            label={lang === 'es' ? 'retrato · isabel sofía' : 'portrait · isabel sofía'}
            className="hero__portrait"
          />
          <div className="hero__overlay">
            <div className="label" style={{ marginBottom: 18, opacity: 0.85 }}>
              {lang === 'es' ? 'Galería sin paredes' : 'Gallery without walls'}
            </div>
            <div className="hero__name wordmark">casa IS</div>
            <p className="hero__tagline" style={{ marginLeft: 'auto', marginRight: 'auto' }}>
              {t(lang, HERO.tagline)}
            </p>
            <div style={{ marginTop: 28, display: 'flex', gap: 12, justifyContent: 'center', flexWrap: 'wrap' }}>
              <a href="#collections" className="btn btn--light">
                {lang === 'es' ? 'Ver colecciones' : 'Browse collections'}
              </a>
            </div>
          </div>
        </div>
      )}

      {variant !== 'bleed' && (
        <div className="hero__scroll">
          <span>{t(lang, HERO.scroll)}</span>
        </div>
      )}
    </section>
  );
}

// ---------------- COLLECTIONS ----------------
function Countdown({ target, lang }) {
  const [now, setNow] = useS(() => Date.now());
  useE(() => {
    const id = setInterval(() => setNow(Date.now()), 1000);
    return () => clearInterval(id);
  }, []);
  const diff = Math.max(0, new Date(target).getTime() - now);
  const days = Math.floor(diff / 86400000);
  const hours = Math.floor((diff % 86400000) / 3600000);
  const mins = Math.floor((diff % 3600000) / 60000);
  const secs = Math.floor((diff % 60000) / 1000);
  const pad = (n) => String(n).padStart(2, '0');
  const L = lang === 'es'
    ? { d: 'días', h: 'horas', m: 'min', s: 'seg' }
    : { d: 'days', h: 'hours', m: 'min', s: 'sec' };
  return (
    <div className="countdown__clock">
      <div className="countdown__unit"><span className="v">{pad(days)}</span><span className="l">{L.d}</span></div>
      <div className="countdown__unit"><span className="v">{pad(hours)}</span><span className="l">{L.h}</span></div>
      <div className="countdown__unit"><span className="v">{pad(mins)}</span><span className="l">{L.m}</span></div>
      <div className="countdown__unit"><span className="v">{pad(secs)}</span><span className="l">{L.s}</span></div>
    </div>
  );
}


// ---------------- SCROLL STRIP (horizontal product carousel) ----------------
function ScrollStrip({ lang }) {
  const trackRef = useR(null);
  const allPrints = PRINTS.filter(p => p.shopifyHandle && !p.comingSoon);

  const scroll = (dir) => {
    if (trackRef.current) {
      trackRef.current.scrollBy({ left: dir * 260, behavior: 'smooth' });
    }
  };

  return (
    <div className="scroll-strip">
      <div className="scroll-strip__header">
        <div className="scroll-strip__title">
          {lang === 'es' ? 'Todos los prints' : 'All prints'} ({allPrints.length})
        </div>
        <div className="scroll-strip__arrows">
          <button onClick={() => scroll(-1)} aria-label="Previous">&#8249;</button>
          <button onClick={() => scroll(1)} aria-label="Next">&#8250;</button>
        </div>
      </div>
      <div className="scroll-strip__track" ref={trackRef}>
        {allPrints.map((p) => {
          const img = shopifyImage(p.shopifyHandle) || p.image || '';
          const price = shopifyPrice(p.shopifyHandle) || p.price;
          return (
            <div key={p.id} className="scroll-strip__item" onClick={() => quickBuy(p.shopifyHandle)}>
              {img ? <img src={img} alt={t(lang, p.title)} loading="lazy" /> : <Placeholder palette={p.palette} ratio="1" />}
              <div className="scroll-strip__item-title">{t(lang, p.title)}</div>
              <div className="scroll-strip__item-price">{price}</div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function Collections({ lang, onOpenItem }) {
  const [tab, setTab] = useS('originals'); // 'originals' | 'prints'
  const [openCollection, setOpenCollection] = useS(null); // print collection id when drilling in

  // When user switches top tab, reset drill-down
  useE(() => { setOpenCollection(null); }, [tab]);

  const collectionMeta = openCollection ? PRINT_COLLECTIONS.find(c => c.id === openCollection) : null;
  const drillItems = openCollection ? PRINTS.filter(p => p.collection === openCollection) : [];

  function scrollToIsHouse() {
    const el = document.getElementById('is-house');
    if (el) {
      const y = el.getBoundingClientRect().top + window.scrollY - 64;
      window.scrollTo({ top: y, behavior: 'smooth' });
    }
  }

  return (
    <section id="collections" data-screen-label="Collections" className="section">
      <div className="wrap">
        <SectionHead
          lang={lang}
          eyebrow={{ es: 'Colecciones', en: 'Collections' }}
          head={{
            es: ['Descubre por', 'colección.'],
            en: ['Discover by', 'collection.'],
          }}
          body={{
            es: 'Piezas originales y prints curados. Cada obra trae su propia conversación.',
            en: 'Original pieces and curated prints. Every work brings its own conversation.',
          }}
        />

        {/* Top-level: Originals / Prints */}
        <div className="col-tabs">
          <button
            className={tab === 'originals' ? 'is-active' : ''}
            onClick={() => setTab('originals')}
          >
            {lang === 'es' ? 'Piezas originales' : 'Original Pieces'}
            <span className="count">· {ORIGINALS.length}</span>
          </button>
          <button
            className={tab === 'prints' ? 'is-active' : ''}
            onClick={() => setTab('prints')}
          >
            {lang === 'es' ? 'Prints' : 'Prints'}
            <span className="count">· {PRINT_COLLECTIONS.length} {lang === 'es' ? 'colecciones' : 'collections'}</span>
          </button>
        </div>

        {/* ===== ORIGINALS -- COMING SOON ===== */}
        {tab === 'originals' && (
          <div className="fade-in" key="originals">
            <div className="coming-soon">
              <div className="coming-soon__label">
                {lang === 'es' ? 'Lanzamiento proximo' : 'Upcoming release'}
              </div>
              <h2 className="coming-soon__title">
                Coming Soon
              </h2>
              <div className="coming-soon__collection">
                <em>{t(lang, ORIGINALS_COLLECTION.title)}</em>
              </div>
              <p style={{ color: 'var(--cream)', opacity: 0.75, fontSize: 18, fontFamily: 'var(--serif)', fontStyle: 'italic', maxWidth: '50ch', margin: '0 auto' }}>
                {t(lang, ORIGINALS_COLLECTION.body)}
              </p>

              <div style={{ margin: '40px 0' }}>
                <Countdown target={ORIGINALS_RELEASE} lang={lang} />
              </div>

              <div style={{ fontSize: 14, color: 'var(--cream)', opacity: 0.55, marginBottom: 8 }}>
                {ORIGINALS.length} {lang === 'es' ? 'piezas' : 'pieces'} {'\u00b7'} $500-$3,500 {'\u00b7'} 1/1
              </div>

              <div className="coming-soon__cta">
                <p>{lang === 'es'
                  ? 'Suscribete al boletin para acceso 48h antes del lanzamiento publico.'
                  : 'Subscribe to the newsletter for 48h early access before the public drop.'}</p>
                <a href="#is-house" className="btn btn--solid" onClick={(e) => { e.preventDefault(); scrollToIsHouse(); }}>
                  {lang === 'es' ? 'Obtener acceso anticipado' : 'Get early access'}
                </a>
              </div>
            </div>
          </div>
        )}

        {/* ===== PRINTS VIEW ===== */}
        {tab === 'prints' && !openCollection && (
          <div className="fade-in" key="prints-list">
            {/* Horizontal scroll strip - all prints */}
            <ScrollStrip lang={lang} />

            <div style={{ marginBottom: 36, display: 'flex', justifyContent: 'space-between', alignItems: 'end', gap: 24, flexWrap: 'wrap' }}>
              <div className="serif italic" style={{ fontSize: 22, maxWidth: '46ch', opacity: 0.78 }}>
                {lang === 'es'
                  ? 'Cuatro colecciones temáticas. Cada una habla en su propio tono.'
                  : 'Four thematic collections. Each one speaks in its own tone.'}
              </div>
              <div className="label" style={{ opacity: 0.55 }}>
                {lang === 'es' ? 'A4 · A3 · A2 · desde $27' : 'A4 · A3 · A2 · from $27'}
              </div>
            </div>

            <div className="collection-grid">
              {PRINT_COLLECTIONS.map((c, i) => {
                const count = PRINTS.filter(p => p.collection === c.id).length;
                const palettes = {
                  bts: ['#7D2027', '#231F20'],
                  still: ['#FAE3B1', '#998731'],
                  atelier: ['#673C34', '#FAE3B1'],
                  memory: ['#5FABC2', '#673C34'],
                };
                // Use first real print image as cover when available
                const cover = PRINTS.find(p => p.collection === c.id && p.image)?.image;
                return (
                  <div
                    key={c.id}
                    className="collection-card"
                    onClick={() => setOpenCollection(c.id)}
                  >
                    <div className="collection-card__media">
                      <Placeholder palette={palettes[c.id]} label={c.id} src={cover} alt={c.en} />
                    </div>
                    <div className="collection-card__body">
                      <div>
                        <div className="collection-card__num">0{i + 1}</div>
                        <div className="collection-card__title">
                          <em>{t(lang, c)}</em>
                        </div>
                        <div className="collection-card__sub">{t(lang, c.sub)}</div>
                      </div>
                      <div className="collection-card__meta">
                        <span>{count} {lang === 'es' ? (count === 1 ? 'pieza' : 'piezas') : (count === 1 ? 'piece' : 'pieces')}</span>
                        <span className="collection-card__arrow">→</span>
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        )}

        {/* ===== PRINTS DRILL-DOWN ===== */}
        {tab === 'prints' && openCollection && (
          <div className="fade-in" key={`drill-${openCollection}`}>
            <button className="col-back" onClick={() => setOpenCollection(null)}>
              ← {lang === 'es' ? 'Todas las colecciones' : 'All collections'}
            </button>
            <div style={{ marginBottom: 36, display: 'flex', justifyContent: 'space-between', alignItems: 'end', gap: 24, flexWrap: 'wrap' }}>
              <div>
                <div className="label" style={{ color: 'var(--accent)', marginBottom: 10 }}>
                  {lang === 'es' ? 'Colección' : 'Collection'}
                </div>
                <h3 className="h-section" style={{ fontSize: 'clamp(32px, 3.5vw, 48px)' }}>
                  <em>{t(lang, collectionMeta)}</em>
                </h3>
                <div className="serif italic" style={{ fontSize: 18, opacity: 0.72, marginTop: 8, maxWidth: '46ch' }}>
                  {t(lang, collectionMeta.sub)}
                </div>
              </div>
              <div className="label" style={{ opacity: 0.55 }}>
                {drillItems.length} {lang === 'es' ? 'piezas' : 'pieces'} · $27–$67
              </div>
            </div>
            <div className="col-grid">
              {drillItems.map((it) => (
                <ProductCard key={it.id} item={it} lang={lang} onOpen={onOpenItem} />
              ))}
            </div>
          </div>
        )}
      </div>
    </section>
  );
}

// ---------------- IS HOUSE (IS CLUB + OPEN HOUSE) ----------------
function IsHouse({ lang }) {
  const [email, setEmail] = useS('');
  const [msg, setMsg] = useS(null);
  const [plan, setPlan] = useS('yearly');
  const [newsletter, setNewsletter] = useS('is-club');
  const valuesRef = useR(null);

  // Animate value cards on scroll
  useE(() => {
    if (!valuesRef.current) return;
    const cards = valuesRef.current.querySelectorAll('.is-club-value');
    const obs = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          const idx = Array.from(cards).indexOf(entry.target);
          setTimeout(() => entry.target.classList.add('is-visible'), idx * 200);
          obs.unobserve(entry.target);
        }
      });
    }, { threshold: 0.2 });
    cards.forEach(c => obs.observe(c));
    return () => obs.disconnect();
  }, [newsletter]);

  async function submit(e) {
    e.preventDefault();
    const ok = /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email.trim());
    const data = newsletter === 'open-house' ? OPEN_HOUSE : IS_CLUB;
    if (!ok) {
      setMsg({ type: 'err', text: t(lang, data.form.err) });
      return;
    }
    const result = await subscribeToNewsletter(email.trim(), lang, newsletter);
    if (result.ok) {
      setMsg({ type: 'ok', text: t(lang, data.form.ok) });
      setEmail('');
    } else {
      setMsg({ type: 'err', text: result.error || 'Error' });
    }
  }

  // Get some print images for the preview strip
  const previewPrints = PRINTS.filter(p => p.shopifyHandle && !p.comingSoon).slice(0, 6);

  return (
    <section id="is-house" data-screen-label="Newsletter" className="section is-club-hero">
      <div className="wrap">
        {/* Toggle: IS Club vs Open House */}
        <div className="is-club-toggle">
          <button
            className={newsletter === 'is-club' ? 'is-active' : ''}
            onClick={() => { setNewsletter('is-club'); setMsg(null); }}
          >
            The IS Club
          </button>
          <button
            className={newsletter === 'open-house' ? 'is-active' : ''}
            onClick={() => { setNewsletter('open-house'); setMsg(null); }}
          >
            {lang === 'es' ? 'Boletin Gratis' : 'Free Newsletter'}
          </button>
        </div>

        {newsletter === 'is-club' ? (
          <>
            {/* IS Club Hero Header */}
            <div className="is-club-hero__head">
              <h2>
                The IS<br /><em>Club.</em>
              </h2>
              <p>{lang === 'es'
                ? 'Tu puerta al taller. Un print exclusivo cada mes, acceso anticipado, y cartas desde el estudio.'
                : 'Your door to the studio. One exclusive print every month, early access, and letters from the studio.'}</p>
            </div>

            {/* Value Cards */}
            <div className="is-club-values" ref={valuesRef}>
              <div className="is-club-value">
                <div className="is-club-value__num">01</div>
                <div className="is-club-value__title">
                  {lang === 'es' ? 'Print Exclusivo' : 'Exclusive Print'}
                </div>
                <div className="is-club-value__desc">
                  {lang === 'es'
                    ? 'Un print de arte original entregado a tu puerta cada mes. Solo para miembros.'
                    : 'An original art print delivered to your door every month. Members only.'}
                </div>
              </div>
              <div className="is-club-value">
                <div className="is-club-value__num">02</div>
                <div className="is-club-value__title">
                  {lang === 'es' ? 'Acceso Anticipado' : 'Early Access'}
                </div>
                <div className="is-club-value__desc">
                  {lang === 'es'
                    ? '48 horas antes de cada lanzamiento publico. Tu siempre primero.'
                    : '48 hours before every public drop. You always first.'}
                </div>
              </div>
              <div className="is-club-value">
                <div className="is-club-value__num">03</div>
                <div className="is-club-value__title">
                  {lang === 'es' ? 'Detras del Taller' : 'Behind the Studio'}
                </div>
                <div className="is-club-value__desc">
                  {lang === 'es'
                    ? 'Cartas personales, videos del proceso, bocetos sin editar. La conversacion que continua.'
                    : 'Personal letters, process videos, unedited sketches. The conversation that continues.'}
                </div>
              </div>
            </div>

            {/* Print Preview Strip */}
            <div className="is-club-prints">
              {previewPrints.map(p => {
                const img = shopifyImage(p.shopifyHandle);
                return img ? <img key={p.id} src={img} alt={t(lang, p.title)} loading="lazy" /> : null;
              })}
            </div>

            {/* Pricing */}
            <div className="is-club-pricing">
              <div
                className={'is-club-price-card' + (plan === 'monthly' ? ' is-active' : '')}
                onClick={() => setPlan('monthly')}
              >
                <div style={{ fontSize: 13, opacity: 0.6, letterSpacing: '0.1em', textTransform: 'uppercase' }}>
                  {lang === 'es' ? 'Mensual' : 'Monthly'}
                </div>
                <div className="is-club-price-card__amount">$18</div>
                <div className="is-club-price-card__period">/ {lang === 'es' ? 'mes' : 'month'}</div>
              </div>
              <div
                className={'is-club-price-card is-featured' + (plan === 'yearly' ? ' is-active' : '')}
                onClick={() => setPlan('yearly')}
              >
                <div className="is-club-price-card__badge">
                  {lang === 'es' ? 'AHORRA 2 MESES' : 'SAVE 2 MONTHS'}
                </div>
                <div style={{ fontSize: 13, opacity: 0.6, letterSpacing: '0.1em', textTransform: 'uppercase' }}>
                  {lang === 'es' ? 'Anual' : 'Yearly'}
                </div>
                <div className="is-club-price-card__amount">$180</div>
                <div className="is-club-price-card__period">/ {lang === 'es' ? 'ano' : 'year'}</div>
                <div className="is-club-price-card__sub">
                  {lang === 'es' ? 'Solo $15/mes' : 'Just $15/month'}
                </div>
              </div>
            </div>
          </>
        ) : (
          /* Open House (free newsletter) */
          <div className="is-club-hero__head">
            <h2>
              The Open<br /><em>House.</em>
            </h2>
            <p>{lang === 'es'
              ? 'Historias semanales desde el estudio, proceso, y acceso temprano. Gratis.'
              : 'Weekly stories from the studio, process, and early access. Free.'}</p>
          </div>
        )}

        {/* Email Form */}
        <div className="is-club-form">
          <form onSubmit={submit}>
            <div style={{ fontSize: 13, opacity: 0.65, marginBottom: 12, color: 'var(--cream)', letterSpacing: '0.1em', textTransform: 'uppercase' }}>
              {newsletter === 'is-club'
                ? (lang === 'es' ? 'Reserva tu lugar' : 'Reserve your spot')
                : (lang === 'es' ? 'Unete al boletin' : 'Join the newsletter')}
            </div>
            <div className="is-club-form__row">
              <input
                type="email"
                placeholder={lang === 'es' ? 'tu correo' : 'your email'}
                value={email}
                onChange={(e) => setEmail(e.target.value)}
              />
              <button type="submit">
                {newsletter === 'is-club'
                  ? (lang === 'es' ? 'Reservar' : 'Reserve')
                  : (lang === 'es' ? 'Suscribir' : 'Subscribe')}
              </button>
            </div>
            {msg && (
              <div style={{ marginTop: 12, fontSize: 13, color: 'var(--cream)', opacity: msg.type === 'ok' ? 0.9 : 0.7 }}>
                {msg.text}
              </div>
            )}
          </form>
        </div>
      </div>
    </section>
  );
}

// ---------------- SHOP ----------------
function Shop({ lang, onOpenItem }) {
  const [cat, setCat] = useS('merch');
  const items = SHOP_ITEMS[cat];
  return (
    <section id="shop" data-screen-label="Shop" className="section">
      <div className="wrap">
        <SectionHead
          lang={lang}
          center
          eyebrow={{ es: 'Compra ahora', en: 'Shop now' }}
          head={{
            es: ['Tus favoritos,', 'recién reabastecidos.'],
            en: ['Your favorites,', 'freshly in stock.'],
          }}
          body={{
            es: 'Tres niveles, una misma mano. Llévalo a casa.',
            en: 'Three tiers, one same hand. Take it home.',
          }}
        />
        <div className="shop-tabs">
          {SHOP_CATEGORIES.map((c) => (
            <button
              key={c.id}
              className={cat === c.id ? 'is-active' : ''}
              onClick={() => setCat(c.id)}
            >
              {t(lang, c.label)}
              <span className="price-range">{c.range}</span>
            </button>
          ))}
        </div>
        <div className="col-grid">
          {items.map((it) => (
            <ProductCard key={it.id} item={it} lang={lang} onOpen={onOpenItem} />
          ))}
        </div>
        <div style={{ textAlign: 'center', marginTop: 56 }}>
          <a href="#collections" className="btn">
            {lang === 'es' ? 'Ver todo el catálogo' : 'See full catalog'} →
          </a>
        </div>
      </div>
    </section>
  );
}

// ---------------- COMMISSIONS ----------------
function Commissions({ lang }) {
  const [step, setStep] = useS(0);
  const [data, setData] = useS({ name: '', email: '', size: '', medium: '', story: '' });
  const [done, setDone] = useS(false);
  const totalSteps = 3;

  const [sending, setSending] = useS(false);

  async function submitCommission(formData) {
    setSending(true);
    try {
      // Formspree endpoint — replace YOUR_FORM_ID with real Formspree form ID
      // Create one free at https://formspree.io (forwards to Isabel's email)
      const res = await fetch('https://formspree.io/f/YOUR_FORM_ID', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
        body: JSON.stringify({
          name: formData.name,
          email: formData.email,
          size: formData.size,
          medium: formData.medium,
          story: formData.story,
          _subject: 'Nueva carta de encargo — casa IS',
        }),
      });
      return res.ok;
    } catch { return false; }
    finally { setSending(false); }
  }

  async function next() {
    if (step < totalSteps - 1) setStep(s => s + 1);
    else {
      const ok = await submitCommission(data);
      setDone(true);
      if (!ok) console.warn('Commission form submission failed — data may not have been sent');
    }
  }
  function back() { if (step > 0) setStep(s => s - 1); }
  function update(k, v) { setData(d => ({ ...d, [k]: v })); }

  const canAdvance = (() => {
    if (step === 0) return data.name.trim() && /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(data.email);
    if (step === 1) return data.size && data.medium;
    if (step === 2) return data.story.trim().length > 6;
    return false;
  })();

  return (
    <section id="commissions" data-screen-label="Commissions" className="section commissions">
      <div className="wrap cm-grid">
        <div>
          <div className="sec-head__rule" style={{ color: 'var(--cream)', marginBottom: 18 }}>
            <span className="line" style={{ background: 'var(--cream)' }} />
            <span className="label">{t(lang, COMMISSIONS.eyebrow)}</span>
          </div>
          <h2 className="h-section">
            {COMMISSIONS.head[lang][0]}<br />
            <em>{COMMISSIONS.head[lang][1]}</em>
          </h2>
          <p className="serif italic" style={{ fontSize: 18, lineHeight: 1.55, opacity: 0.9, maxWidth: '40ch', marginTop: 18 }}>
            {t(lang, COMMISSIONS.body)}
          </p>
          <ul style={{ listStyle: 'none', padding: 0, marginTop: 36, display: 'grid', gap: 14, fontSize: 14 }}>
            {[
              { es: 'Carta inicial — me cuentas tu historia.', en: 'Opening letter — you tell me your story.' },
              { es: 'Boceto y conversación — definimos juntas.', en: 'Sketch and conversation — we shape it together.' },
              { es: 'Pintura · 4 a 8 semanas.', en: 'Painting · 4 to 8 weeks.' },
              { es: 'Entrega con una carta escrita a mano.', en: 'Delivery with a handwritten letter.' },
            ].map((row, i) => (
              <li key={i} style={{ display: 'grid', gridTemplateColumns: '32px 1fr', alignItems: 'baseline', gap: 8 }}>
                <span className="serif italic" style={{ opacity: 0.7 }}>0{i + 1}</span>
                <span>{t(lang, row)}</span>
              </li>
            ))}
          </ul>
        </div>

        <div className="cm-form">
          <div className="cm-steps">
            {COMMISSIONS.steps.map((s, i) => (
              <span key={s.id} className={`${i === step ? 'is-active' : ''} ${i < step ? 'is-done' : ''}`}>
                <span className="dot">{i < step ? '✓' : s.id}</span>
                <span>{t(lang, s.label)}</span>
              </span>
            ))}
          </div>

          {done ? (
            <div className="cm-step" style={{ minHeight: 280 }}>
              <h3><em>{lang === 'es' ? 'Carta recibida.' : 'Letter received.'}</em></h3>
              <p>
                {lang === 'es'
                  ? `Gracias, ${data.name.split(' ')[0]}. Te escribiré en 2–3 días desde el estudio.`
                  : `Thank you, ${data.name.split(' ')[0]}. I'll write you within 2–3 days from the studio.`}
              </p>
              <p style={{ fontSize: 14, opacity: 0.65, marginTop: 8 }}>
                {lang === 'es'
                  ? 'Mientras tanto, puedes ver el proceso de otras piezas.'
                  : 'In the meantime, browse the process behind other pieces.'}
              </p>
              <div style={{ display: 'flex', gap: 12, marginTop: 24, flexWrap: 'wrap' }}>
                <button className="btn btn--accent" onClick={() => document.getElementById('collections')?.scrollIntoView({ behavior: 'smooth' })}>
                  {lang === 'es' ? 'Ver colecciones' : 'Browse collections'}
                </button>
                <button className="btn" style={{ borderColor: 'var(--red)', color: 'var(--red)' }} onClick={() => document.getElementById('is-house')?.scrollIntoView({ behavior: 'smooth' })}>
                  {lang === 'es' ? 'Unirme al boletín' : 'Join the newsletter'}
                </button>
              </div>
            </div>
          ) : (
            <>
              {step === 0 && (
                <div className="cm-step">
                  <h3>{lang === 'es' ? <>Cuéntame <em>quién eres</em>.</> : <>Tell me <em>who you are</em>.</>}</h3>
                  <p>{lang === 'es' ? 'Empezamos por lo simple.' : 'We start with the simple part.'}</p>
                  <div className="cm-fields">
                    <div className="cm-field">
                      <label>{lang === 'es' ? 'Nombre' : 'Name'}</label>
                      <input value={data.name} onChange={(e) => update('name', e.target.value)} placeholder={lang === 'es' ? 'Tu nombre completo' : 'Your full name'} />
                    </div>
                    <div className="cm-field">
                      <label>{lang === 'es' ? 'Correo' : 'Email'}</label>
                      <input type="email" value={data.email} onChange={(e) => update('email', e.target.value)} placeholder="hola@ejemplo.com" />
                    </div>
                  </div>
                </div>
              )}
              {step === 1 && (
                <div className="cm-step">
                  <h3>{lang === 'es' ? <>Imagina <em>la pieza</em>.</> : <>Imagine <em>the piece</em>.</>}</h3>
                  <p>{lang === 'es' ? 'Todo se puede cambiar después.' : 'Everything can change later.'}</p>
                  <div className="cm-fields">
                    <div className="cm-field">
                      <label>{lang === 'es' ? 'Tamaño' : 'Size'}</label>
                      <div className="cm-options" style={{ marginTop: 8 }}>
                        {COMMISSIONS.sizeOpts.map((o) => (
                          <button
                            key={o.id}
                            type="button"
                            className={data.size === o.id ? 'is-active' : ''}
                            onClick={() => update('size', o.id)}
                          >
                            <span className="label">{t(lang, o.label)}</span>
                            <span>{t(lang, o.sub)}</span>
                          </button>
                        ))}
                      </div>
                    </div>
                    <div className="cm-field">
                      <label>{lang === 'es' ? 'Medio' : 'Medium'}</label>
                      <div className="cm-options" style={{ gridTemplateColumns: 'repeat(3,1fr)', marginTop: 8 }}>
                        {COMMISSIONS.mediumOpts.map((o) => (
                          <button
                            key={o.id}
                            type="button"
                            className={data.medium === o.id ? 'is-active' : ''}
                            onClick={() => update('medium', o.id)}
                          >
                            <span>{t(lang, o.label)}</span>
                          </button>
                        ))}
                      </div>
                    </div>
                  </div>
                </div>
              )}
              {step === 2 && (
                <div className="cm-step">
                  <h3>{lang === 'es' ? <>Escríbeme <em>la carta</em>.</> : <>Write me <em>the letter</em>.</>}</h3>
                  <p>{lang === 'es' ? '¿Qué quieres recordar, esconder o decir sin palabras?' : 'What do you want to remember, hide, or say without words?'}</p>
                  <div className="cm-fields">
                    <div className="cm-field">
                      <label>{lang === 'es' ? 'Tu historia' : 'Your story'}</label>
                      <textarea
                        rows={6}
                        value={data.story}
                        onChange={(e) => update('story', e.target.value)}
                        placeholder={lang === 'es' ? 'Una memoria, un momento, una sensación…' : 'A memory, a moment, a feeling…'}
                      />
                    </div>
                  </div>
                </div>
              )}

              <div className="cm-nav">
                <button
                  className="btn btn--sm"
                  type="button"
                  onClick={back}
                  disabled={step === 0}
                  style={{ opacity: step === 0 ? 0.3 : 1, pointerEvents: step === 0 ? 'none' : 'auto', borderColor: 'var(--red)', color: 'var(--red)' }}
                >
                  ← {lang === 'es' ? 'Atrás' : 'Back'}
                </button>
                <div className="progress">
                  {Array.from({ length: totalSteps }).map((_, i) => (
                    <span key={i} className={i <= step ? 'is-on' : ''} />
                  ))}
                </div>
                <button
                  className="btn btn--sm"
                  type="button"
                  onClick={next}
                  disabled={!canAdvance || sending}
                  style={{ background: canAdvance ? 'var(--red)' : 'transparent', color: canAdvance ? 'var(--cream)' : 'var(--red)', borderColor: 'var(--red)', opacity: (canAdvance && !sending) ? 1 : 0.5 }}
                >
                  {sending
                    ? (lang === 'es' ? 'Enviando...' : 'Sending...')
                    : step === totalSteps - 1
                      ? (lang === 'es' ? 'Enviar carta' : 'Send letter')
                      : (lang === 'es' ? 'Siguiente' : 'Next')} →
                </button>
              </div>
            </>
          )}
        </div>
      </div>
    </section>
  );
}

// ---------------- ABOUT ----------------
function About({ lang }) {
  return (
    <section id="about" data-screen-label="About" className="section about">
      <div className="wrap ab-grid">
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <img
            src="assets/isabel-studio-v2.png"
            alt={lang === 'es' ? 'Isabel Sofia en el taller' : 'Isabel Sofia in the studio'}
            loading="lazy"
            style={{
              width: '100%',
              maxWidth: 720,
              objectFit: 'contain',
              background: 'transparent',
            }}
          />
        </div>
        <div>
          <div className="sec-head__rule" style={{ color: 'var(--cream)', marginBottom: 18 }}>
            <span className="line" style={{ background: 'var(--cream)' }} />
            <span className="label">{t(lang, ABOUT.eyebrow)}</span>
          </div>
          <h2 className="h-section">
            {ABOUT.head[lang][0]}<br />
            <em>{ABOUT.head[lang][1]}</em>
          </h2>
          <p className="serif italic" style={{ fontSize: 19, lineHeight: 1.55, opacity: 0.92, marginTop: 18, maxWidth: '46ch' }}>
            {t(lang, ABOUT.body)}
          </p>
          <p className="serif italic" style={{ fontSize: 14, opacity: 0.6, marginTop: 22 }}>
            — {t(lang, FOOTER.mantra)}
          </p>

          <div className="ab-layers">
            {ABOUT.layers.map((l) => (
              <div key={l.num} className="ab-layer">
                <div className="num">{l.num}</div>
                <h4>{l[lang].name}</h4>
                <p>{l[lang].desc}</p>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

// ---------------- FOOTER ----------------
const FOOTER_LINKS = {
  'Merch': '#shop',
  'Prints': '#collections',
  'Originals': '#collections',
  'IS House': '#is-house',
  'Commissions': '#commissions',
  'About Isabel': '#about',
  'Newsletter': '#is-house',
  'Press': 'mailto:hola@casais.studio',
  'Pinterest': 'https://pinterest.com/isabelsofiald',
  'Instagram': 'https://instagram.com/isabelsofiald',
  'Contact': 'mailto:hola@casais.studio',
  // ES equivalents
  'Merch': '#shop',
  'Prints': '#collections',
  'Originales': '#collections',
  'IS House': '#is-house',
  'Encargos': '#commissions',
  'Sobre Isabel': '#about',
  'Boletín': '#is-house',
  'Prensa': 'mailto:hola@casais.studio',
  'Pinterest': 'https://pinterest.com/isabelsofiald',
  'Instagram': 'https://instagram.com/isabelsofiald',
  'Contacto': 'mailto:hola@casais.studio',
};

function Footer({ lang }) {
  const getHref = (item) => {
    const label = t(lang, item);
    return FOOTER_LINKS[label] || '#';
  };
  const isExternal = (href) => href.startsWith('http') || href.startsWith('mailto:');

  return (
    <footer className="footer">
      <div className="ft-grid">
        <div>
          <div className="brand wordmark">casa IS</div>
          <p className="mantra">{t(lang, FOOTER.mantra)}</p>
        </div>
        {FOOTER.cols.map((c, i) => (
          <div key={i}>
            <h5>{t(lang, c.h)}</h5>
            <ul>
              {c.items.map((it, j) => {
                const href = getHref(it);
                const ext = isExternal(href);
                return (
                  <li key={j}>
                    <a
                      href={href}
                      {...(ext ? { target: '_blank', rel: 'noopener noreferrer' } : {})}
                      onClick={!ext ? (e) => {
                        e.preventDefault();
                        const el = document.getElementById(href.replace('#', ''));
                        if (el) el.scrollIntoView({ behavior: 'smooth' });
                      } : undefined}
                    >
                      {t(lang, it)}
                    </a>
                  </li>
                );
              })}
            </ul>
          </div>
        ))}
      </div>
      <div className="legal">
        <span>© 2026 casa IS · isabel sofía lara díaz</span>
        <span>Bogotá / sin paredes</span>
      </div>
    </footer>
  );
}

Object.assign(window, {
  Nav, Hero, Collections, IsHouse, Shop, Commissions, About, Footer,
});
