// Main App — orchestrates scroll progress, theme transitions, sections, cart.

const { useState, useEffect, useRef, useMemo } = React;

function App() {
  const [theme, setTheme]       = useState('onyx');         // committed theme
  const [hoverTheme, setHover]  = useState(null);           // preview theme
  const [view, setView]         = useState('home');         // 'home' | 'product'
  const [activeProduct, setAP]  = useState(null);
  const [cart, setCart]         = useState([]);
  const [cartOpen, setCartOpen] = useState(false);
  const [scrollY, setScrollY]   = useState(0);
  const [vh, setVh]             = useState(typeof window !== 'undefined' ? window.innerHeight : 800);
  const [orderDone, setOrderDone] = useState(false);

  // Apply theme to <html>
  const effectiveTheme = hoverTheme || theme;
  useEffect(() => {
    document.documentElement.setAttribute('data-theme', effectiveTheme);
  }, [effectiveTheme]);

  // Trigger flash animation on committed theme change
  useEffect(() => {
    const el = document.getElementById('themeFlash');
    if (!el) return;
    el.classList.remove('active');
    void el.offsetWidth;
    el.classList.add('active');
  }, [theme]);

  // Track scroll
  useEffect(() => {
    const onScroll = () => setScrollY(window.scrollY);
    const onResize = () => setVh(window.innerHeight);
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onResize);
    return () => {
      window.removeEventListener('scroll', onScroll);
      window.removeEventListener('resize', onResize);
    };
  }, []);

  // Section heights — landing 1vh, box-pin 4vh (long pin so the open box holds), then collection
  const landingH = vh;
  const boxPinH  = vh * 4;       // total scrollable for box section

  const landingProgress = Math.min(1, scrollY / (landingH * 0.8));
  // box section starts at landingH and runs for boxPinH
  const boxRaw = (scrollY - landingH) / boxPinH;
  // Remap: video scrubs through in the first 65% of scroll, then HOLDS open for the last 35%
  const scrubWindow = 0.65;
  const boxProgress = Math.max(0, Math.min(1, boxRaw / scrubWindow));

  const inBoxRange = scrollY >= landingH && scrollY < landingH + boxPinH;

  // Add to cart
  const addToCart = (p) => {
    setCart(prev => {
      const ex = prev.find(x => x.id === p.id);
      if (ex) return prev.map(x => x.id === p.id ? {...x, qty: x.qty+1} : x);
      return [...prev, { ...p, qty: 1 }];
    });
    setCartOpen(true);
  };
  const removeFromCart = (id) => setCart(prev => prev.filter(x => x.id !== id));
  const cartCount = cart.reduce((s, i) => s + i.qty, 0);

  // Selecting a product → commit theme + go to product view
  const selectProduct = (p) => {
    setAP(p);
    if (p.theme !== theme) setTheme(p.theme);
    setView('product');
    setTimeout(() => window.scrollTo({ top: 0, behavior: 'smooth' }), 50);
  };
  const backToHome = () => {
    setView('home');
    setTimeout(() => {
      const el = document.getElementById('collection');
      if (el) window.scrollTo({ top: el.offsetTop - 80, behavior: 'smooth' });
    }, 50);
  };

  const onNav = (id) => {
    if (id === 'top') {
      window.scrollTo({ top: 0, behavior: 'smooth' });
      return;
    }
    if (view === 'product') setView('home');
    setTimeout(() => {
      const el = document.getElementById(id);
      if (el) window.scrollTo({ top: el.offsetTop - 60, behavior: 'smooth' });
    }, 50);
  };

  const onComplete = () => {
    setOrderDone(true);
    setTimeout(() => {
      setCart([]);
      setOrderDone(false);
      setCartOpen(false);
    }, 2600);
  };

  // Open cart should temporarily switch to onyx for the discreet checkout vibe
  const checkoutTheme = cartOpen ? 'onyx' : effectiveTheme;
  useEffect(() => {
    document.documentElement.setAttribute('data-theme', checkoutTheme);
  }, [checkoutTheme]);

  return (
    <>
      <Nav cartCount={cartCount} onNav={onNav}
           currentSection={view === 'product' ? 'collection' : null}
           onCartClick={() => setCartOpen(true)}/>

      {view === 'home' && (
        <>
          {/* Landing */}
          <Landing scrollProgress={landingProgress}
                   onScrollHint={() => window.scrollTo({top: vh, behavior:'smooth'})}/>

          {/* Box opening — pinned, scroll scrubs the video */}
          <div style={{ height: boxPinH, position: 'relative' }}>
            <div style={{ position: 'sticky', top: 0, height: '100vh' }}>
              <BoxOpening progress={boxProgress}/>
            </div>
          </div>

          {/* Brand quote — pause beat */}
          <Quote/>

          {/* Craftsmanship triptych — three real-photo details */}
          <Craftsmanship/>

          {/* Collection */}
          <Collection products={PRODUCTS}
                      activeId={hoverTheme ? PRODUCTS.find(p => p.theme === hoverTheme)?.id : null}
                      onHover={setHover}
                      onSelect={selectProduct}/>

          {/* Story */}
          <Story/>

          <Journal/>
        </>
      )}

      {view === 'product' && activeProduct && (
        <Product product={activeProduct} onAdd={addToCart} onBack={backToHome}/>
      )}

      <Footer/>

      <Checkout open={cartOpen} items={cart}
                onClose={() => setCartOpen(false)}
                onRemove={removeFromCart}
                onComplete={onComplete}/>

      {orderDone && (
        <div style={{
          position:'fixed', inset: 0, zIndex: 300,
          background: 'rgba(10,8,7,0.92)',
          display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center',
          gap: 24, animation: 'fadeIn 400ms',
        }}>
          <div style={{color:'var(--gold)'}}><Monogram size={56}/></div>
          <h2 className="serif" style={{fontSize: 64, color:'var(--gold)', fontStyle:'italic'}}>Thank you.</h2>
          <p style={{color:'var(--ink-soft)', maxWidth: 420, textAlign:'center', lineHeight: 1.7}}>
            Your moment is on its way. Discreetly. Quietly. With care.
          </p>
        </div>
      )}
    </>
  );
}

function Quote() {
  return (
    <section style={{
      padding: '160px 56px',
      borderTop: '1px solid var(--hairline)',
      borderBottom: '1px solid var(--hairline)',
      textAlign: 'center',
    }}>
      <div className="micro" style={{color:'var(--gold)', marginBottom: 32}}>The promise</div>
      <p className="serif" style={{
        fontSize: 'clamp(36px, 4.5vw, 64px)', lineHeight: 1.2,
        maxWidth: 1000, margin: '0 auto',
        fontStyle:'italic', color:'var(--ink)',
      }}>
        “Beautiful on the outside. Yours on the inside.”
      </p>
      <div className="mini" style={{color:'var(--ink-mute)', marginTop: 32}}>
        — Discrete Pleasures, est. 2024
      </div>
    </section>
  );
}

function Story() {
  return (
    <section id="story" data-screen-label="05 Story" style={{
      padding: '140px 56px', maxWidth: 1480, margin: '0 auto',
    }}>
      <div style={{display:'grid', gridTemplateColumns:'1fr 1.1fr', gap: 80, alignItems:'center'}}>
        <div>
          <div className="micro" style={{color:'var(--gold)', marginBottom: 20}}>Our Story</div>
          <h2 className="serif" style={{fontSize: 'clamp(48px, 6vw, 88px)', lineHeight: 0.95, marginBottom: 32}}>
            Made for the<br/>
            <em style={{fontStyle:'italic', color:'var(--gold)'}}>most personal</em><br/>
            moments.
          </h2>
          <p style={{fontSize: 16, color:'var(--ink-soft)', lineHeight: 1.8, marginBottom: 20, maxWidth: 480}}>
            We believe wellness is private, and pleasure is a quiet kind of luxury — not loud,
            not performative, just yours. Every Discrete Pleasures product is engineered to be
            beautiful on the outside and a little secret on the inside.
          </p>
          <p style={{fontSize: 16, color:'var(--ink-soft)', lineHeight: 1.8, maxWidth: 480}}>
            Body-safe materials. Whisper-quiet motors. Packaging worth keeping.
            And shipping that never reveals itself.
          </p>
        </div>
        <div style={{
          aspectRatio: '5/6',
          border: '1px solid var(--hairline)',
          overflow: 'hidden',
          position: 'relative',
        }}>
          <img src="assets/closeup-logo.jpg" alt="Gold-foil monogram detail"
               style={{width:'100%', height:'100%', objectFit:'cover'}}/>
          <div className="micro" style={{
            position:'absolute', bottom: 20, left: 24,
            color:'var(--gold)', letterSpacing:'0.3em',
            background:'rgba(0,0,0,0.4)', padding:'6px 12px', backdropFilter:'blur(6px)',
          }}>
            Gold foil · Hand-stamped
          </div>
        </div>
      </div>
    </section>
  );
}

function Craftsmanship() {
  const items = [
    { src: 'assets/closeup-logo.jpg',  k: '01', l: 'Gold foil monogram',  s: 'Hand-stamped on every closure.' },
    { src: 'assets/ribbon-tab.jpg',    k: '02', l: 'Satin ribbon pull',   s: 'A quiet gesture, every time.' },
    { src: 'assets/satin-pouch.jpg',   k: '03', l: 'Silk-touch pouch',    s: 'Foil-stamped. Pull-string close.' },
  ];
  return (
    <section data-screen-label="03b Craftsmanship" style={{
      padding: '140px 56px 100px', maxWidth: 1480, margin: '0 auto',
    }}>
      <div style={{textAlign:'center', maxWidth: 720, margin: '0 auto 72px'}}>
        <div className="micro" style={{color:'var(--gold)', marginBottom: 24}}>02 — In the details</div>
        <h2 className="serif" style={{
          fontSize: 'clamp(48px, 6vw, 80px)', lineHeight: 0.95,
          letterSpacing: '-0.01em', marginBottom: 24,
        }}>
          The way it <em style={{fontStyle:'italic', color:'var(--gold)'}}>opens.</em>
        </h2>
        <p style={{fontSize: 16, color:'var(--ink-soft)', lineHeight: 1.7}}>
          Every surface considered. Every closure intentional.
        </p>
      </div>
      <div style={{display:'grid', gridTemplateColumns:'repeat(3, 1fr)', gap: 24}}>
        {items.map(it => (
          <figure key={it.k} style={{margin: 0, display:'flex', flexDirection:'column', gap: 20}}>
            <div style={{
              aspectRatio:'4/5', overflow:'hidden',
              border: '1px solid var(--hairline)', position:'relative',
            }}>
              <img src={it.src} alt={it.l}
                   style={{width:'100%', height:'100%', objectFit:'cover'}}/>
            </div>
            <figcaption>
              <div className="micro" style={{color:'var(--gold)', marginBottom: 8}}>{it.k}</div>
              <div className="serif" style={{fontSize: 24, marginBottom: 6, letterSpacing:'0.005em'}}>
                {it.l}
              </div>
              <div style={{fontSize: 13, color:'var(--ink-mute)', lineHeight: 1.6}}>
                {it.s}
              </div>
            </figcaption>
          </figure>
        ))}
      </div>
    </section>
  );
}

function Journal() {
  const posts = [
    { t:'On stillness', s:'A short essay on slowing down.', e:'4 min read' },
    { t:'Materials we love', s:'Why we chose medical-grade silicone.', e:'3 min read' },
    { t:'Designing for privacy', s:'How we think about discretion.', e:'5 min read' },
  ];
  return (
    <section id="journal" data-screen-label="06 Journal" style={{
      padding: '120px 56px', maxWidth: 1480, margin: '0 auto',
      borderTop: '1px solid var(--hairline)',
    }}>
      <div style={{display:'flex', justifyContent:'space-between', alignItems:'flex-end', marginBottom: 60}}>
        <div>
          <div className="micro" style={{color:'var(--gold)', marginBottom: 20}}>The Journal</div>
          <h2 className="serif" style={{fontSize: 'clamp(40px, 5vw, 72px)', lineHeight: 1, letterSpacing:'-0.01em'}}>
            <em style={{fontStyle:'italic'}}>Quiet</em> reading.
          </h2>
        </div>
        <button className="mini" style={{color:'var(--gold)', display:'flex', alignItems:'center', gap: 8}}>
          All articles <Icon.arrow/>
        </button>
      </div>
      <div style={{display:'grid', gridTemplateColumns:'repeat(3, 1fr)', gap: 24}}>
        {posts.map((p, i) => (
          <article key={p.t} style={{
            border: '1px solid var(--hairline)',
            padding: 32, minHeight: 280,
            display:'flex', flexDirection:'column', justifyContent:'space-between',
            transition: 'all 400ms',
          }}>
            <div className="micro" style={{color:'var(--ink-mute)'}}>0{i+1} · Essay</div>
            <div>
              <h3 className="serif" style={{fontSize: 32, lineHeight: 1.1, marginBottom: 12, marginTop: 60}}>
                {p.t}
              </h3>
              <p style={{fontSize: 14, color:'var(--ink-soft)', marginBottom: 24}}>{p.s}</p>
              <div className="mini" style={{
                color:'var(--gold)', display:'flex', alignItems:'center', gap: 8,
                paddingTop: 16, borderTop:'1px solid var(--hairline)',
              }}>
                <span>{p.e}</span><span style={{marginLeft:'auto'}}>Read →</span>
              </div>
            </div>
          </article>
        ))}
      </div>
    </section>
  );
}

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