function NewsletterForm() {
  const [email, setEmail]   = React.useState('');
  const [done,  setDone]    = React.useState(false);
  const [err,   setErr]     = React.useState('');

  function submit(e) {
    e.preventDefault();
    if (!email.includes('@')) { setErr('Valid email required'); return; }
    window.UmbraDB?.saveSubscriber?.(email, 'homepage');
    setDone(true);
  }

  if (done) return (
    <div style={{ borderTop: '2px solid rgba(255,255,255,0.5)', paddingTop: 24 }}>
      <div style={{ fontFamily: "'Montserrat', sans-serif", fontSize: 26, fontStyle: 'italic', color: '#ffffff', marginBottom: 8 }}>You're in the shadow now.</div>
      <div style={{ fontFamily: "'Montserrat', sans-serif", fontSize: 12, color: 'rgba(255,255,255,0.4)', letterSpacing: '0.1em' }}>We'll be in touch — sparingly.</div>
    </div>
  );

  return (
    <form onSubmit={submit}>
      <div style={{ borderBottom: `1px solid ${err ? 'rgba(255,255,255,0.7)' : 'rgba(255,255,255,0.25)'}`, display: 'flex', alignItems: 'center', marginBottom: 12 }}>
        <input
          type="email" value={email} onChange={e => { setEmail(e.target.value); setErr(''); }}
          placeholder="your@email.com"
          style={{
            flex: 1, background: 'none', border: 'none', outline: 'none',
            fontFamily: "'Montserrat', sans-serif", fontSize: 12,
            color: '#ffffff', padding: '12px 0', letterSpacing: '0.04em',
          }}
          onFocus={e => e.target.closest('div').style.borderBottomColor = 'rgba(255,255,255,0.9)'}
          onBlur={e => e.target.closest('div').style.borderBottomColor = err ? 'rgba(255,255,255,0.7)' : 'rgba(255,255,255,0.25)'}
        />
        <button type="submit" style={{
          background: 'none', border: 'none', color: 'rgba(255,255,255,0.6)',
          fontFamily: "'Montserrat', sans-serif", fontSize: 12,
          letterSpacing: '0.18em', cursor: 'crosshair', padding: '0 0 0 16px',
          transition: 'color 0.15s',
        }}
        onMouseEnter={e => e.currentTarget.style.color = '#ffffff'}
        onMouseLeave={e => e.currentTarget.style.color = 'rgba(255,255,255,0.6)'}
        >SUBSCRIBE →</button>
      </div>
      {err && <div style={{ fontFamily: "'Montserrat', sans-serif", fontSize: 12, color: 'rgba(255,255,255,0.6)', letterSpacing: '0.1em' }}>{err}</div>}
      <div style={{ fontFamily: "'Montserrat', sans-serif", fontSize: 12, color: 'rgba(255,255,255,0.25)', letterSpacing: '0.12em', marginTop: 8 }}>
        No spam. Unsubscribe any time.
      </div>
    </form>
  );
}

function Nav({ cartCount, onLogoClick, onNavigate, page, onCartClick, onJoinClick }) {
  const links = [
    { id: 'home',   label: 'HOME'   },
    { id: 'shop',   label: 'SHOP'   },
    { id: 'about',  label: 'ABOUT'  },
    { id: 'ritual', label: 'RITUAL' },
  ];
  return (
    <header style={{
      position: 'fixed', top: 0, left: 0, right: 0, zIndex: 1000,
      display: 'grid', gridTemplateColumns: '1fr auto 1fr',
      alignItems: 'center',
      padding: '20px 48px',
      borderBottom: '1px solid rgba(255,255,255,0.07)',
      background: 'rgba(0,0,0,0.9)',
      backdropFilter: 'blur(14px)',
    }}>
      {/* Logo + wordmark */}
      <button onClick={onLogoClick} style={{
        background: 'none', border: 'none', padding: 0,
        cursor: 'crosshair', display: 'flex', alignItems: 'center', gap: 10,
      }}>
        <img
          src="logo.png"
          alt=""
          style={{ height: 32, width: 'auto', display: 'block', filter: 'brightness(0) invert(1)' }}
          onError={e => e.currentTarget.style.display = 'none'}
        />
        <span style={{
          color: '#ffffff',
          fontFamily: "'Montserrat', sans-serif", fontSize: 13,
          letterSpacing: '0.45em', fontWeight: 900,
        }}>UMBRA</span>
      </button>

      {/* Nav links */}
      <nav style={{ display: 'flex', gap: 36 }}>
        {links.map(l => {
          const active = page === l.id || (l.id === 'home' && page === 'detail');
          return (
            <button key={l.id} onClick={() => onNavigate(l.id)} className="link-draw" style={{
              background: 'none', border: 'none', padding: 0,
              fontFamily: "'Montserrat', sans-serif", fontSize: 12,
              letterSpacing: '0.24em', cursor: 'crosshair',
              color: active ? '#ffffff' : 'rgba(255,255,255,0.35)',
              paddingBottom: 2,
              transition: 'color 0.2s',
            }}
            onMouseEnter={e => { if (!active) e.currentTarget.style.color = 'rgba(255,255,255,0.85)'; }}
            onMouseLeave={e => { if (!active) e.currentTarget.style.color = 'rgba(255,255,255,0.35)'; }}
            >{l.label}</button>
          );
        })}
      </nav>

      {/* Cart + Join */}
      <div style={{ display: 'flex', justifyContent: 'flex-end', alignItems: 'center', gap: 20 }}>
        <button onClick={onJoinClick} style={{
          background: 'none', border: '1px solid rgba(255,255,255,0.3)',
          fontFamily: "'Montserrat', sans-serif", fontSize: 12,
          letterSpacing: '0.22em', cursor: 'crosshair',
          color: 'rgba(255,255,255,0.6)', padding: '6px 14px',
          transition: 'all 0.18s',
        }}
        onMouseEnter={e => { e.currentTarget.style.background = '#ffffff'; e.currentTarget.style.color = '#000000'; e.currentTarget.style.borderColor = '#ffffff'; }}
        onMouseLeave={e => { e.currentTarget.style.background = 'none'; e.currentTarget.style.color = 'rgba(255,255,255,0.6)'; e.currentTarget.style.borderColor = 'rgba(255,255,255,0.3)'; }}
        >JOIN</button>
        <button onClick={onCartClick} style={{
          background: 'none', border: 'none',
          fontFamily: "'Montserrat', sans-serif", fontSize: 12,
          letterSpacing: '0.15em', cursor: 'crosshair',
          color: cartCount > 0 ? '#ffffff' : 'rgba(255,255,255,0.32)',
          transition: 'color 0.25s', padding: '4px 0',
        }}
        onMouseEnter={e => e.currentTarget.style.color = '#ffffff'}
        onMouseLeave={e => { if (cartCount === 0) e.currentTarget.style.color = 'rgba(255,255,255,0.32)'; }}
        >
          CART{cartCount > 0 && (
            <span style={{ marginLeft: 6, fontFamily: "'Montserrat', sans-serif", fontSize: 12, background: '#ffffff', color: '#000000', padding: '2px 5px' }}>{cartCount}</span>
          )}
        </button>
      </div>
    </header>
  );
}

function ProductRow({ coffee, onSelect, density }) {
  const [hovered, setHovered] = React.useState(false);
  const compact = density === 'compact';

  return (
    <div
      onClick={() => onSelect(coffee)}
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
      style={{
        borderTop: '1px solid rgba(255,255,255,0.1)',
        padding: compact ? '26px 48px' : '38px 48px',
        cursor: 'crosshair',
        background: hovered ? '#ffffff' : 'transparent',
        transition: 'background 0.45s cubic-bezier(0.25,0.46,0.45,0.94)',
        display: 'grid',
        gridTemplateColumns: '56px 1fr auto',
        alignItems: 'center', gap: '32px',
      }}
    >
      <span style={{
        fontFamily: "'Montserrat', sans-serif", fontSize: 12,
        letterSpacing: '0.12em',
        color: hovered ? 'rgba(0,0,0,0.3)' : 'rgba(255,255,255,0.28)',
        transition: 'color 0.18s',
      }}>{coffee.index}</span>

      <div>
        <div style={{
          fontFamily: "'Montserrat', sans-serif",
          fontSize: compact ? 26 : 34, fontWeight: 900,
          letterSpacing: '-0.01em', lineHeight: 1,
          color: hovered ? '#000000' : '#ffffff',
          transition: 'color 0.18s',
        }}>{coffee.name}</div>
        <div style={{
          fontFamily: "'Montserrat', sans-serif",
          fontSize: 12, letterSpacing: '0.16em',
          color: hovered ? 'rgba(0,0,0,0.42)' : 'rgba(255,255,255,0.36)',
          transition: 'color 0.18s', marginTop: 7,
          textTransform: 'uppercase',
        }}>{coffee.origin} · {coffee.process}</div>
      </div>

      <div style={{ display: 'flex', alignItems: 'center', gap: 28 }}>
        <div style={{ textAlign: 'right' }}>
          <div style={{
            fontFamily: "'Montserrat', sans-serif", fontSize: 20,
            fontWeight: 700, letterSpacing: '-0.01em',
            color: hovered ? '#000000' : '#ffffff',
            transition: 'color 0.18s',
          }}>{coffee.altitude.toLocaleString()}m</div>
          <div style={{
            fontFamily: "'Montserrat', sans-serif", fontSize: 12,
            letterSpacing: '0.12em', textTransform: 'uppercase',
            color: hovered ? 'rgba(0,0,0,0.35)' : 'rgba(255,255,255,0.25)',
            transition: 'color 0.18s', marginTop: 3,
          }}>altitude</div>
        </div>
        <span style={{
          fontFamily: "'Montserrat', sans-serif", fontSize: 16,
          color: hovered ? '#000000' : 'rgba(255,255,255,0.35)',
          transition: 'color 0.18s, transform 0.22s',
          transform: hovered ? 'translateX(5px)' : 'translateX(0)',
          display: 'inline-block',
        }}>→</span>
      </div>
    </div>
  );
}

function HomePage({ coffees, onSelect, tweaks }) {
  const [heroVisible, setHeroVisible] = React.useState(false);
  const [manifestoVisible, setManifestoVisible] = React.useState(false);
  const [mouse, setMouse] = React.useState({ x: 0, y: 0 });
  const manifestoRef = React.useRef(null);

  React.useEffect(() => {
    const t = setTimeout(() => setHeroVisible(true), 80);
    const obs = new IntersectionObserver(
      ([e]) => { if (e.isIntersecting) setManifestoVisible(true); },
      { threshold: 0.25 }
    );
    if (manifestoRef.current) obs.observe(manifestoRef.current);
    return () => { clearTimeout(t); obs.disconnect(); };
  }, []);

  function onMouseMove(e) {
    setMouse({
      x: (e.clientX / window.innerWidth - 0.5) * 24,
      y: (e.clientY / window.innerHeight - 0.5) * 12,
    });
  }

  const trans = 'opacity 1.1s ease, transform 1.1s cubic-bezier(0.16, 1, 0.3, 1)';

  return (
    <div onMouseMove={onMouseMove}>

      {/* ── HERO ── */}
      <section style={{
        height: '100vh', display: 'flex', flexDirection: 'column',
        justifyContent: 'center', alignItems: 'center',
        position: 'relative', overflow: 'hidden', paddingTop: 80,
      }}>
        {/* Background roastery image — grayscale + parallax */}
        <div style={{
          position: 'absolute', inset: '-10%',
          backgroundImage: 'url(roastery.jpg)',
          backgroundSize: 'cover', backgroundPosition: 'center',
          filter: 'grayscale(100%) brightness(0.58) contrast(1.05)',
          transform: `translate(${mouse.x * 0.06}px, ${mouse.y * 0.06}px) scale(1.12)`,
          transition: 'transform 2s cubic-bezier(0.25,0.46,0.45,0.94)',
          opacity: heroVisible ? 1 : 0,
          transition: 'opacity 1.6s ease, transform 2s cubic-bezier(0.25,0.46,0.45,0.94)',
          willChange: 'transform',
        }} />

        {/* Dark vignette overlay — deepens toward edges */}
        <div style={{
          position: 'absolute', inset: 0, pointerEvents: 'none',
          background: 'radial-gradient(ellipse at center, rgba(0,0,0,0.15) 0%, rgba(0,0,0,0.72) 100%)',
        }} />

        {/* Bottom fade into black */}
        <div style={{
          position: 'absolute', bottom: 0, left: 0, right: 0, height: '35%',
          background: 'linear-gradient(to bottom, transparent, #000000)',
          pointerEvents: 'none',
        }} />

        {/* Main UMBRA */}
        <h1 className="apple-hero-title" style={{
          fontFamily: "'Montserrat', sans-serif",
          fontSize: 'clamp(72px, 17vw, 260px)',
          fontWeight: 900, letterSpacing: '0.14em', lineHeight: 1,
          color: '#ffffff',
          opacity: heroVisible ? 1 : 0,
          transform: heroVisible
            ? `translate(${mouse.x * 0.28}px, ${mouse.y * 0.28}px)`
            : `translate(${mouse.x * 0.28}px, ${(mouse.y * 0.28) + 48}px)`,
          transition: heroVisible
            ? 'opacity 1s cubic-bezier(0.25,0.46,0.45,0.94), transform 1.2s cubic-bezier(0.25,0.46,0.45,0.94)'
            : 'none',
          whiteSpace: 'nowrap', userSelect: 'none', position: 'relative',
        }}>UMBRA</h1>

        {/* Subtitle */}
        <div style={{
          fontFamily: "'Montserrat', sans-serif", fontSize: 12,
          letterSpacing: '0.3em', color: 'rgba(255,255,255,0.38)',
          textTransform: 'uppercase', marginTop: 24, textAlign: 'center',
          opacity: heroVisible ? 1 : 0,
          transform: heroVisible ? 'translateY(0)' : 'translateY(20px)',
          transition: 'opacity 1s cubic-bezier(0.25,0.46,0.45,0.94) 0.35s, transform 1s cubic-bezier(0.25,0.46,0.45,0.94) 0.35s',
          fontWeight: 500,
        }}>
          Specialty Coffee Roasters &nbsp;·&nbsp; Makassar, Indonesia &nbsp;·&nbsp; Est. 2021
        </div>

        {/* Thin divider line — fades in */}
        <div style={{
          width: 'clamp(80px,12vw,180px)', height: 1,
          background: 'rgba(255,255,255,0.18)', marginTop: 36,
          opacity: heroVisible ? 1 : 0,
          transform: heroVisible ? 'scaleX(1)' : 'scaleX(0)',
          transformOrigin: 'center',
          transition: 'opacity 0.9s ease 0.6s, transform 0.9s cubic-bezier(0.25,0.46,0.45,0.94) 0.6s',
        }} />

        {/* Scroll cue */}
        <div style={{
          position: 'absolute', bottom: 40, left: '50%',
          transform: 'translateX(-50%)',
          opacity: heroVisible ? 0.3 : 0,
          transition: 'opacity 1s ease 1s',
          display: 'flex', flexDirection: 'column',
          alignItems: 'center', gap: 10,
          fontFamily: "'Montserrat', sans-serif",
          fontSize: 12, letterSpacing: '0.3em', color: '#ffffff', fontWeight: 500,
        }}>
          <span>SCROLL</span>
          <div style={{ width: 1, height: 44, background: 'rgba(255,255,255,0.4)', animation: 'scrollPulse 2.2s ease-in-out infinite' }} />
        </div>
      </section>

      {/* ── MANIFESTO ── */}
      <section ref={manifestoRef} style={{
        padding: '110px 48px',
        maxWidth: 860, marginLeft: 'auto',
        borderTop: '1px solid rgba(255,255,255,0.07)',
        opacity: manifestoVisible ? 1 : 0,
        transform: manifestoVisible ? 'translateY(0)' : 'translateY(36px)',
        transition: 'opacity 1s ease, transform 1s ease',
      }}>
        <div style={{
          fontFamily: "'Montserrat', sans-serif", fontSize: 12,
          letterSpacing: '0.35em', color: 'rgba(255,255,255,0.28)',
          marginBottom: 32, textTransform: 'uppercase',
        }}>Manifesto</div>
        <blockquote style={{
          fontFamily: "'Montserrat', sans-serif",
          fontSize: 'clamp(20px, 2.6vw, 34px)',
          fontWeight: 400, fontStyle: 'italic',
          lineHeight: 1.65, color: '#ffffff',
          borderLeft: '2px solid rgba(255,255,255,0.25)',
          paddingLeft: 32, margin: 0,
        }}>
          {[
            '"Umbra: from Latin, the darkest shadow.',
            'The shadow cast by a sun-grown cherry.',
            'The shadow inside the cup.',
            'We source where altitude writes the flavour —',
            'and roast to the edge of darkness."',
          ].map((line, i) => (
            <span key={i} className="reveal-line">
              <span className="reveal-line-inner" style={{ animationDelay: `${i * 0.11}s` }}>
                {line}
              </span>
            </span>
          ))}
        </blockquote>
      </section>

      {/* ── PRODUCT GRID ── */}
      <section style={{ paddingBottom: 0 }}>
        <div style={{
          display: 'flex', justifyContent: 'space-between',
          alignItems: 'baseline',
          padding: '0 48px 22px',
          borderBottom: '1px solid rgba(255,255,255,0.07)',
        }}>
          <div style={{
            fontFamily: "'Montserrat', sans-serif", fontSize: 12,
            letterSpacing: '0.32em', color: 'rgba(255,255,255,0.28)',
            textTransform: 'uppercase',
          }}>Current Harvest — {new Date().getFullYear()}</div>
          <div style={{
            fontFamily: "'Montserrat', sans-serif", fontSize: 12,
            letterSpacing: '0.15em', color: 'rgba(255,255,255,0.18)',
          }}>4 Origins</div>
        </div>

        <div>
          {coffees.map((c, i) => (
            <div key={c.id} style={{ opacity: 0, animation: `rowReveal 0.6s ease ${i * 0.09 + 0.2}s forwards` }}>
              <ProductRow coffee={c} onSelect={onSelect} density={tweaks?.gridDensity} />
            </div>
          ))}
          <div style={{ borderTop: '1px solid rgba(255,255,255,0.1)' }} />
        </div>
      </section>

      {/* ── NEWSLETTER ── */}
      <section style={{
        borderTop: '1px solid rgba(255,255,255,0.07)',
        padding: '72px 48px',
        display: 'grid',
        gridTemplateColumns: '1fr 1fr',
        gap: 80, alignItems: 'center',
      }}>
        <div>
          <div style={{ fontFamily: "'Montserrat', sans-serif", fontSize: 12, letterSpacing: '0.35em', color: 'rgba(255,255,255,0.28)', marginBottom: 16, textTransform: 'uppercase' }}>The Dispatch</div>
          <h2 style={{ fontFamily: "'Montserrat', sans-serif", fontSize: 'clamp(28px, 3.2vw, 44px)', fontWeight: 900, letterSpacing: '-0.02em', color: '#ffffff', lineHeight: 1.05, marginBottom: 16 }}>
            Stay in<br/><em style={{ fontStyle: 'italic' }}>the shadow.</em>
          </h2>
          <p style={{ fontFamily: "'Montserrat', sans-serif", fontSize: 12, lineHeight: 1.9, color: 'rgba(255,255,255,0.4)', maxWidth: 320 }}>
            New arrivals, roast dates, and the occasional manifesto. Never frequent — always worth opening.
          </p>
        </div>
        <NewsletterForm />
      </section>

      {/* ── FOOTER ── */}
      <footer style={{
        padding: '80px 48px 48px',
        borderTop: '1px solid rgba(255,255,255,0.07)',
        display: 'grid',
        gridTemplateColumns: '1fr 1fr 1fr',
        gap: 40,
        marginTop: 80,
      }}>
        <div>
          <div style={{ fontFamily: "'Montserrat', sans-serif", fontSize: 22, fontWeight: 900, letterSpacing: '0.22em', marginBottom: 18 }}>UMBRA</div>
          <div style={{ fontFamily: "'Montserrat', sans-serif", fontSize: 12, lineHeight: 2, color: 'rgba(255,255,255,0.32)' }}>
            Specialty Coffee Roasters<br />Makassar, South Sulawesi<br />Indonesia
          </div>
        </div>
        <div>
          <div style={{ fontFamily: "'Montserrat', sans-serif", fontSize: 12, letterSpacing: '0.3em', color: 'rgba(255,255,255,0.28)', marginBottom: 18, textTransform: 'uppercase' }}>Roastery</div>
          <div style={{ fontFamily: "'Montserrat', sans-serif", fontSize: 12, lineHeight: 2, color: 'rgba(255,255,255,0.44)' }}>
            Jl. Penghibur No. 12<br />Makassar 90111<br />+62 411 000 0000
          </div>
        </div>
        <div style={{ textAlign: 'right', display: 'flex', alignItems: 'flex-end', justifyContent: 'flex-end' }}>
          <div style={{ fontFamily: "'Montserrat', sans-serif", fontSize: 12, letterSpacing: '0.15em', color: 'rgba(255,255,255,0.18)', lineHeight: 2 }}>
            © UMBRA COFFEE {new Date().getFullYear()}<br />All Rights Reserved
          </div>
        </div>
      </footer>

    </div>
  );
}

Object.assign(window, { Nav, ProductRow, HomePage });
