// Royal Goyal website — shared bits: palette, header, footer, product card.
// Borrows the D6 colorways from window.APS_SKU.

const site = {
  paper:  '#efe6d4',
  paper2: '#e6dcc6',
  paper3: '#f4ede0',
  hanji:  '#e6d9bf',
  warm:   '#7a5c3a',
  warm2:  '#5e4527',
  ink:    '#1f1610',
  ink2:   '#0e0a06',
  rule:   'rgba(31,22,16,.18)',
  serif:  '"Cormorant Garamond", "Noto Serif KR", serif',
  mono:   '"JetBrains Mono", ui-monospace, monospace',
  han:    '"Noto Serif KR", serif',
  hanSans:'"Noto Sans KR", system-ui, sans-serif',
};

const PRICE = { hydrate: 38, recover: 42, sleep: 42, revive: 44, focus: 44 };

// ─────── small UI atoms ───────────────────────────────────────
function SiteSeal({ size = 36, fg = site.ink }) {
  return (
    <svg viewBox="0 0 60 60" style={{ width: size, height: size, display:'block' }}>
      <circle cx="30" cy="30" r="28" fill="none" stroke={fg} strokeWidth=".7" opacity=".8" />
      <circle cx="30" cy="30" r="24.5" fill="none" stroke={fg} strokeWidth=".4" opacity=".5" />
      <text x="30" y="37" textAnchor="middle" fontFamily={site.serif} fontStyle="italic" fontSize="20" fill={fg} fontWeight="500">RG</text>
    </svg>
  );
}

function SiteWordmark({ fg = site.ink, size = 22 }) {
  return (
    <div style={{display:'flex', alignItems:'center', gap:10, color: fg}}>
      <SiteSeal size={size + 12} fg={fg} />
      <div style={{display:'flex', flexDirection:'column', lineHeight:1}}>
        <span style={{fontFamily: site.serif, fontStyle:'italic', fontWeight:500, fontSize: size, letterSpacing:'-.01em'}}>Royal Goyal</span>
        <span style={{fontFamily: site.han, fontSize: size * .42, letterSpacing:'.32em', marginTop:4, opacity:.7}}>로얄 고얄</span>
      </div>
    </div>
  );
}

function SiteButton({ children, variant = 'solid', onClick, fg, bg, style }) {
  const v = variant === 'solid'
    ? { background: bg || site.ink, color: fg || site.paper, border: `1px solid ${bg || site.ink}` }
    : variant === 'outline'
      ? { background: 'transparent', color: fg || site.ink, border: `1px solid ${fg || site.ink}` }
      : { background: 'transparent', color: fg || site.ink, border: 'none', padding: 0 };
  return (
    <button onClick={onClick} style={{
      ...v, fontFamily: site.mono, fontSize: 11, letterSpacing:'.28em',
      textTransform:'uppercase', padding: variant === 'plain' ? 0 : '14px 22px',
      cursor:'pointer', borderRadius: 0, transition: 'all .15s ease',
      ...style,
    }}
    onMouseEnter={(e) => { if (variant !== 'plain') e.currentTarget.style.transform = 'translateY(-1px)'; }}
    onMouseLeave={(e) => { e.currentTarget.style.transform = 'translateY(0)'; }}
    >
      {children}
    </button>
  );
}

// ─────── HEADER ───────────────────────────────────────────────
function SiteHeader({ page, setPage, cartCount, openCart }) {
  const vp = useViewport();
  const [menuOpen, setMenuOpen] = React.useState(false);
  const nav = [
    ['shop', 'Shop'],
    ['stack', 'Build a Stack'],
    ['journal', 'The Journal'],
    ['about', 'Our House'],
  ];

  if (vp.isMobile) {
    return (
      <header style={{position:'sticky', top:0, zIndex:40, background: site.paper, borderBottom:`.5px solid ${site.rule}`}}>
        <div style={{
          background: site.ink, color: site.paper, padding:'7px 16px',
          fontFamily: site.mono, fontSize:9, letterSpacing:'.26em',
          textAlign:'center', whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis',
        }}>
          PRE-LAUNCH · SS 26 · FIRST 500 GET 20% OFF
        </div>
        <div style={{padding:'14px 16px', display:'flex', alignItems:'center', justifyContent:'space-between', gap:12}}>
          <button onClick={() => setMenuOpen(true)} aria-label="Menu" style={{background:'transparent', border:'none', cursor:'pointer', padding:0, display:'flex', flexDirection:'column', gap:5}}>
            <span style={{width:22, height:1, background: site.ink, display:'block'}}></span>
            <span style={{width:22, height:1, background: site.ink, display:'block'}}></span>
            <span style={{width:16, height:1, background: site.ink, display:'block'}}></span>
          </button>
          <div onClick={() => setPage({page:'home'})} style={{cursor:'pointer'}}>
            <SiteWordmark size={16} />
          </div>
          <span onClick={openCart} style={{cursor:'pointer', fontFamily: site.mono, fontSize:10, letterSpacing:'.26em', display:'flex', gap:4, alignItems:'baseline'}}>
            Cart <span style={{fontFamily: site.serif, fontStyle:'italic', fontSize:13}}>({cartCount})</span>
          </span>
        </div>

        {/* mobile slide-down menu */}
        <div onClick={() => setMenuOpen(false)} style={{
          position:'fixed', inset:0, background:'rgba(15,10,6,.55)',
          zIndex:55, opacity: menuOpen ? 1 : 0, pointerEvents: menuOpen ? 'auto' : 'none',
          transition:'opacity .25s ease', WebkitBackdropFilter:'blur(2px)', backdropFilter:'blur(2px)',
        }}></div>
        <div style={{
          position:'fixed', top:0, left:0, right:0, zIndex:56, background: site.paper,
          transform: menuOpen ? 'translateY(0)' : 'translateY(-100%)',
          transition:'transform .3s cubic-bezier(.2,.7,.3,1)',
          padding:'18px 18px 28px',
          boxShadow:'0 18px 30px rgba(31,22,16,.18)',
        }}>
          <div style={{display:'flex', justifyContent:'space-between', alignItems:'center'}}>
            <SiteWordmark size={18} />
            <button onClick={() => setMenuOpen(false)} style={{background:'transparent', border:'none', cursor:'pointer', fontFamily: site.mono, fontSize:11, letterSpacing:'.28em'}}>CLOSE ✕</button>
          </div>
          <nav style={{display:'flex', flexDirection:'column', gap:18, marginTop:28, paddingBottom:8}}>
            {nav.map(([k, label])=>(
              <span key={k} onClick={() => { setPage({page:k}); setMenuOpen(false); }} style={{
                fontFamily: site.serif, fontStyle:'italic', fontWeight:500, fontSize:34, letterSpacing:'-.01em',
                color: site.ink, lineHeight:1, cursor:'pointer',
                borderBottom: page === k ? `.5px solid ${site.ink}` : '.5px solid transparent', paddingBottom:6,
              }}>{label}.</span>
            ))}
          </nav>
          <div style={{marginTop:24, paddingTop:16, borderTop:`.5px solid ${site.rule}`, display:'flex', justifyContent:'space-between', fontFamily: site.mono, fontSize:10, letterSpacing:'.26em', opacity:.7}}>
            <span>EN · KR</span><span>SEARCH</span><span>ACCOUNT</span>
          </div>
        </div>
      </header>
    );
  }

  return (
    <header style={{
      position:'sticky', top:0, zIndex:40, background: site.paper,
      borderBottom:`.5px solid ${site.rule}`,
    }}>
      {/* announcement bar */}
      <div style={{
        background: site.ink, color: site.paper, padding:'8px 32px',
        fontFamily: site.mono, fontSize:10, letterSpacing:'.32em',
        display:'flex', justifyContent:'space-between', alignItems:'center',
      }}>
        <span>FREE SHIPPING OVER $80  ·  KR + US</span>
        <span style={{opacity:.7}}>PRE-LAUNCH · SS 26 DROP — RESERVE YOUR PLACE</span>
        <span>SIGN UP — FIRST 500 GET 20% OFF →</span>
      </div>
      <div style={{
        maxWidth: 1400, margin:'0 auto', padding:'18px 32px',
        display:'flex', alignItems:'center', justifyContent:'space-between',
      }}>
        <div onClick={() => setPage({ page:'home' })} style={{cursor:'pointer'}}>
          <SiteWordmark size={20} />
        </div>
        <nav style={{display:'flex', gap:32, fontFamily: site.mono, fontSize:11, letterSpacing:'.26em', textTransform:'uppercase'}}>
          {nav.map(([k,label]) => (
            <span key={k} onClick={() => setPage({ page: k })} style={{
              cursor:'pointer', color: site.ink, paddingBottom:4,
              borderBottom: page === k ? `1px solid ${site.ink}` : '1px solid transparent',
              transition:'border-color .15s',
            }}>{label}</span>
          ))}
        </nav>
        <div style={{display:'flex', gap:18, alignItems:'center', fontFamily: site.mono, fontSize:11, letterSpacing:'.26em', textTransform:'uppercase'}}>
          <span style={{cursor:'pointer', opacity:.75}}>EN · KR</span>
          <span style={{cursor:'pointer', opacity:.75}}>Search</span>
          <span style={{cursor:'pointer', opacity:.75}}>Account</span>
          <span onClick={openCart} style={{cursor:'pointer', display:'flex', gap:6, alignItems:'baseline'}}>
            Cart <span style={{fontFamily: site.serif, fontStyle:'italic', fontSize:14}}>({cartCount})</span>
          </span>
        </div>
      </div>
    </header>
  );
}

// ─────── FOOTER ───────────────────────────────────────────────
function SiteFooter() {
  const vp = useViewport();
  return (
    <footer style={{background: site.ink, color: site.paper, padding: vp.isMobile ? '40px 18px 28px' : '56px 32px 32px', fontFamily: site.mono, fontSize:11, letterSpacing:'.22em'}}>
      <div style={{maxWidth: 1400, margin:'0 auto'}}>
        <div style={{
          display:'grid',
          gridTemplateColumns: vp.isMobile ? '1fr 1fr' : '1.4fr 1fr 1fr 1fr 1fr',
          gap: vp.isMobile ? 32 : 48,
          paddingBottom: vp.isMobile ? 32 : 48,
          borderBottom:'.5px solid rgba(239,230,212,.18)',
        }}>
          <div style={{gridColumn: vp.isMobile ? '1 / -1' : 'auto'}}>
            <SiteWordmark size={24} fg={site.paper} />
            <div style={{fontFamily: site.serif, fontStyle:'italic', fontSize:24, lineHeight:1.25, marginTop:24, maxWidth:300, letterSpacing:'-.005em'}}>
              “Twenty grams of focused intent. Tear, and continue.”
            </div>
            <div style={{marginTop:24, display:'flex', gap:16, opacity:.7}}>
              <span>IG</span><span>TT</span><span>YT</span><span>NL</span>
            </div>
          </div>
          {[
            ['Shop', ['All Formulas','Hydrate · No. 01','Recover · No. 02','Sleep · No. 03','Revive · No. 04','Focus · No. 05','Build a Stack']],
            ['Learn', ['The Journal','Ingredients','Lab Notes','Hanbang & Us','FAQ']],
            ['House', ['Our Story','Sustainability','Press','Wholesale','Contact']],
            ['Service', ['Shipping','Returns','Subscriptions','Account','Get Help']],
          ].map(([h, items])=>(
            <div key={h}>
              <div style={{fontSize:10, letterSpacing:'.32em', opacity:.55}}>{h.toUpperCase()}</div>
              <div style={{marginTop:16, display:'flex', flexDirection:'column', gap:10, fontFamily: site.serif, fontStyle:'italic', fontSize:16, letterSpacing:'.01em', opacity:.92}}>
                {items.map((i)=>(<span key={i} style={{cursor:'pointer'}}>{i}</span>))}
              </div>
            </div>
          ))}
        </div>
        <div style={{marginTop:24, display:'flex', justifyContent:'space-between', opacity:.6, fontSize:10, letterSpacing:'.28em', flexWrap:'wrap', gap:'10px 24px'}}>
          <span>© 2026 ROYAL GOYAL CO., LTD.  ·  로얄 고얄  ·  SEOUL</span>
          <span>PRIVACY  ·  TERMS  ·  KFDA · 식약처</span>
          <span>SITE BY THE HOUSE</span>
        </div>
      </div>
    </footer>
  );
}

// ─────── PRODUCT CARD ────────────────────────────────────────
function ProductCard({ skuId, setPage }) {
  const sku = SKU_BY_ID[skuId];
  const cw  = APS_SKU[skuId];
  const [hover, setHover] = React.useState(false);
  return (
    <div
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      onClick={() => setPage({ page:'pdp', skuId })}
      className="rg-card-lift"
      style={{cursor:'pointer', display:'flex', flexDirection:'column', gap:14}}
    >
      {/* tile that shows the pouch on its colorway */}
      <div style={{
        position:'relative', aspectRatio:'4 / 5', background: site.paper2, overflow:'hidden',
        border:`.5px solid ${site.rule}`,
        backgroundImage: hover ? `radial-gradient(circle at 50% 60%, ${cw.bg}55, ${site.paper2})` : undefined,
        transition:'background .35s ease',
      }}>
        <div style={{position:'absolute', top:16, left:16, fontFamily: site.mono, fontSize:9, letterSpacing:'.28em', opacity:.7}}>NO. {sku.no}</div>
        <div style={{position:'absolute', top:16, right:16, fontFamily: site.mono, fontSize:9, letterSpacing:'.28em', opacity:.7}}>SHADE · {cw.shade}</div>
        <div style={{position:'absolute', inset:0, display:'flex', alignItems:'center', justifyContent:'center'}}>
          <div style={{width:'34%', aspectRatio:'1 / 3.3', boxShadow:'0 18px 30px rgba(31,22,16,.22), 0 4px 8px rgba(31,22,16,.12)', transform: hover ? 'translateY(-8px) rotate(-2deg)' : 'rotate(-3deg)', transition:'transform .35s ease'}}>
            <StickApoStamp skuId={skuId} />
          </div>
        </div>
        <div style={{position:'absolute', bottom:16, left:16, right:16, display:'flex', justifyContent:'space-between', alignItems:'center', fontFamily: site.mono, fontSize:9, letterSpacing:'.28em', opacity:.7}}>
          <span>{sku.timeOfDay.toUpperCase()}</span>
          <span>10 × 20 G</span>
        </div>
      </div>
      <div style={{display:'flex', justifyContent:'space-between', alignItems:'baseline'}}>
        <div>
          <div style={{fontFamily: site.serif, fontStyle:'italic', fontWeight:500, fontSize:28, lineHeight:1, letterSpacing:'-.01em'}}>{sku.enLong}.</div>
          <div style={{fontFamily: site.han, fontSize:13, letterSpacing:'.22em', marginTop:4, opacity:.75}}>{sku.krFull}</div>
        </div>
        <div style={{textAlign:'right', display:'flex', flexDirection:'column', gap:4, alignItems:'flex-end'}}>
          <div style={{fontFamily: site.mono, fontSize:11, letterSpacing:'.22em', opacity:.7}}>${PRICE[skuId]}</div>
          <div style={{fontFamily: site.mono, fontSize:9, letterSpacing:'.24em', opacity:.55}}>{sku.role.toUpperCase()}</div>
        </div>
      </div>
    </div>
  );
}

// ─────── CART DRAWER ─────────────────────────────────────────
function SiteCart({ open, close, cart, removeItem, setPage }) {
  const total = cart.reduce((s,i) => s + PRICE[i.skuId] * i.qty, 0);
  const drop = useDrop();
  const vp = useViewport();
  return (
    <>
      <div onClick={close} style={{
        position:'fixed', inset:0, background:'rgba(15,10,6,.5)', zIndex:60,
        opacity: open ? 1 : 0, pointerEvents: open ? 'auto':'none',
        transition:'opacity .25s ease',
      }}></div>
      <aside style={{
        position:'fixed', top:0, right:0, bottom:0,
        width: vp.isMobile ? '100%' : 440,
        background: site.paper,
        zIndex:61, transform: open ? 'translateX(0)' : 'translateX(105%)',
        transition:'transform .3s cubic-bezier(.2,.7,.3,1)',
        display:'flex', flexDirection:'column',
      }}>
        <div style={{padding:'24px 28px', display:'flex', justifyContent:'space-between', alignItems:'center', borderBottom:`.5px solid ${site.rule}`}}>
          <div>
            <div style={{fontFamily: site.mono, fontSize:10, letterSpacing:'.32em', opacity:.6}}>YOUR RESERVATION</div>
            <div style={{fontFamily: site.serif, fontStyle:'italic', fontWeight:500, fontSize:28, marginTop:2}}>The list.</div>
          </div>
          <span onClick={close} style={{cursor:'pointer', fontFamily: site.mono, fontSize:11, letterSpacing:'.28em'}}>CLOSE ✕</span>
        </div>
        <div style={{flex:1, overflowY:'auto', padding:'8px 28px'}}>
          {cart.length === 0 && (
            <div style={{padding:'40px 0', textAlign:'center'}}>
              <div style={{fontFamily: site.serif, fontStyle:'italic', fontSize:22, opacity:.8}}>“The cart is patient.”</div>
              <div style={{fontFamily: site.mono, fontSize:10, letterSpacing:'.28em', opacity:.55, marginTop:14}}>NOTHING HERE YET</div>
              <SiteButton variant="outline" style={{marginTop:22}} onClick={() => { close(); drop.open('cart-empty'); }}>Sign up for drop release →</SiteButton>
            </div>
          )}
          {cart.map((item, i) => {
            const sku = SKU_BY_ID[item.skuId];
            const cw  = APS_SKU[item.skuId];
            return (
              <div key={i} style={{display:'grid', gridTemplateColumns:'72px 1fr auto', gap:16, alignItems:'center', padding:'18px 0', borderBottom:`.5px solid ${site.rule}`}}>
                <div style={{width:72, height:96, background: cw.bg, padding:8, display:'flex', alignItems:'center', justifyContent:'center'}}>
                  <div style={{width:'70%', height:'92%'}}><StickApoStamp skuId={item.skuId} /></div>
                </div>
                <div>
                  <div style={{fontFamily: site.mono, fontSize:9, letterSpacing:'.24em', opacity:.55}}>NO. {sku.no} · {sku.role.toUpperCase()}</div>
                  <div style={{fontFamily: site.serif, fontStyle:'italic', fontSize:22, lineHeight:1.05, marginTop:4}}>{sku.enLong}</div>
                  <div style={{fontFamily: site.mono, fontSize:10, letterSpacing:'.24em', opacity:.6, marginTop:6}}>QTY {item.qty}  ·  10 × 20 G</div>
                </div>
                <div style={{display:'flex', flexDirection:'column', alignItems:'flex-end', gap:6}}>
                  <div style={{fontFamily: site.mono, fontSize:12, letterSpacing:'.22em'}}>${PRICE[item.skuId] * item.qty}</div>
                  <span onClick={() => removeItem(i)} style={{cursor:'pointer', fontFamily: site.mono, fontSize:9, letterSpacing:'.24em', opacity:.5}}>REMOVE</span>
                </div>
              </div>
            );
          })}
        </div>
        <div style={{borderTop:`.5px solid ${site.rule}`, padding:'20px 28px'}}>
          <div style={{display:'flex', justifyContent:'space-between', fontFamily: site.mono, fontSize:11, letterSpacing:'.22em', opacity:.7}}>
            <span>SUBTOTAL</span><span>${total}</span>
          </div>
          <div style={{display:'flex', justifyContent:'space-between', fontFamily: site.mono, fontSize:11, letterSpacing:'.22em', opacity:.7, marginTop:6}}>
            <span>SHIPPING</span><span>{total >= 80 || total === 0 ? 'FREE' : '$8'}</span>
          </div>
          <div style={{display:'flex', justifyContent:'space-between', fontFamily: site.serif, fontStyle:'italic', fontSize:24, marginTop:14}}>
            <span>Total</span><span>${total + (total >= 80 || total === 0 ? 0 : 8)}.00</span>
          </div>
          <SiteButton style={{width:'100%', marginTop:18}} onClick={() => { close(); drop.open('cart'); }}>Sign up for drop release →</SiteButton>
          <div style={{marginTop:10, fontFamily: site.mono, fontSize:9, letterSpacing:'.24em', opacity:.55, textAlign:'center'}}>PRE-LAUNCH · ESTIMATED PRICES · DROP OPENS SS 26</div>
        </div>
      </aside>
    </>
  );
}

Object.assign(window, { site, PRICE, SiteSeal, SiteWordmark, SiteButton, SiteHeader, SiteFooter, ProductCard, SiteCart });
