// Stack Builder — pick a formula for each slot of the day, get a custom
// monthly subscription. Interactive: click a slot, then pick a formula.

const SLOTS = [
  { id:'morning',   time:'06:30', label:'Morning',    note:'Wake. Sharpen.', recommended:'focus' },
  { id:'midday',    time:'11:00', label:'Midday',     note:'Replace what coffee took.', recommended:'hydrate' },
  { id:'training',  time:'17:30', label:'Training',   note:'During or right after the last set.', recommended:'recover' },
  { id:'winddown',  time:'22:00', label:'Wind Down',  note:'Before the room goes dark.', recommended:'sleep' },
  { id:'rescue',    time:'AS NEEDED', label:'Rescue', note:'Before, during, after.', recommended:'revive' },
];

function PageStack({ setPage, addToCart }) {
  const drop = useDrop();
  const vp = useViewport();
  const [stack, setStack] = React.useState(() => {
    const o = {};
    SLOTS.forEach(s => { o[s.id] = s.recommended; });
    return o;
  });
  const [activeSlot, setActiveSlot] = React.useState('morning');
  const [cadence, setCadence] = React.useState(4); // weeks

  const sticksPerSlot = 30; // monthly
  const subPrice = Math.round(
    Object.values(stack).reduce((sum, id) => id ? sum + PRICE[id] * .85 : sum, 0)
  );
  const totalSticks = Object.values(stack).filter(Boolean).length * sticksPerSlot;

  const setSlot = (slotId, skuId) => {
    setStack(prev => ({...prev, [slotId]: prev[slotId] === skuId ? null : skuId}));
  };

  const activeStickId = stack[activeSlot];

  return (
    <div style={{background: site.paper, color: site.ink}}>
      {/* hero */}
      <section style={{borderBottom:`.5px solid ${site.rule}`, position:'relative', overflow:'hidden'}}>
        <div style={{position:'absolute', inset:0, opacity:.05,
          backgroundImage:`repeating-linear-gradient(0deg, ${site.ink} 0 .5px, transparent .5px 28px),
                           repeating-linear-gradient(90deg, ${site.ink} 0 .5px, transparent .5px 28px)`}}></div>
        <div style={{maxWidth:1400, margin:'0 auto', padding: vp.isMobile ? '40px 18px 28px' : '72px 32px 48px', position:'relative'}}>
          <div style={{fontFamily: site.mono, fontSize:11, letterSpacing:'.32em', color: site.warm}}>BUILD A STACK · SUBSCRIPTION</div>
          <h1 style={{fontFamily: site.serif, fontStyle:'italic', fontWeight:500, fontSize: vp.isMobile ? 52 : 96, lineHeight:.92, letterSpacing:'-.025em', margin:'14px 0 0'}}>Design your day,<br/>in five sticks.</h1>
          <p style={{fontFamily: site.serif, fontStyle:'italic', fontSize: vp.isMobile ? 16 : 20, lineHeight:1.4, marginTop:18, maxWidth:600, opacity:.85}}>
            Pick one formula for each slot of your day. We'll ship a fresh box every {cadence} weeks — 15% off the apothecary price, cancel any time.
          </p>
        </div>
      </section>

      <section style={{padding: vp.isMobile ? '32px 18px 56px' : '48px 32px 80px'}}>
        <div style={{maxWidth:1400, margin:'0 auto', display:'grid', gridTemplateColumns: vp.isMobile ? '1fr' : '1.4fr 1fr', gap: vp.isMobile ? 32 : 64, alignItems:'start'}}>

          {/* LEFT — builder */}
          <div>
            {/* slot strip */}
            <div style={{display:'grid', gridTemplateColumns: vp.isMobile ? 'repeat(2, 1fr)' : 'repeat(5, 1fr)', gap: vp.isMobile ? 10 : 14}}>
              {SLOTS.map((slot)=>{
                const filled = stack[slot.id];
                const cw = filled ? APS_SKU[filled] : null;
                const isActive = activeSlot === slot.id;
                return (
                  <div key={slot.id} onClick={() => setActiveSlot(slot.id)} style={{
                    cursor:'pointer', padding:'18px 14px', minHeight:220,
                    background: cw ? cw.bg : site.paper2,
                    color: cw ? cw.fg : site.ink,
                    border: isActive ? `2px solid ${site.ink}` : `.5px solid ${site.rule}`,
                    display:'flex', flexDirection:'column', justifyContent:'space-between',
                    transition:'all .2s ease', position:'relative',
                  }}>
                    <div>
                      <div style={{fontFamily: site.mono, fontSize:9, letterSpacing:'.28em', opacity:.7}}>{slot.time}</div>
                      <div style={{fontFamily: site.serif, fontStyle:'italic', fontWeight:500, fontSize:24, lineHeight:1, marginTop:6}}>{slot.label}.</div>
                    </div>
                    {filled ? (
                      <div>
                        <div style={{width:34, height:108, margin:'10px auto 0', boxShadow:'0 8px 16px rgba(0,0,0,.18)'}}>
                          <StickApoStamp skuId={filled} />
                        </div>
                        <div style={{fontFamily: site.mono, fontSize:8, letterSpacing:'.24em', opacity:.78, marginTop:8, textAlign:'center'}}>NO. {SKU_BY_ID[filled].no}  ·  {SKU_BY_ID[filled].en}</div>
                      </div>
                    ) : (
                      <div style={{display:'flex', alignItems:'center', justifyContent:'center', flex:1, opacity:.45}}>
                        <div style={{width:40, height:40, borderRadius:'50%', border:`1px dashed ${site.ink}`, display:'flex', alignItems:'center', justifyContent:'center', fontFamily: site.mono, fontSize:18}}>+</div>
                      </div>
                    )}
                  </div>
                );
              })}
            </div>

            {/* active-slot detail + formula picker */}
            <div style={{marginTop:32, padding:'28px 28px', border:`.5px solid ${site.rule}`, background: site.paper3}}>
              <div style={{display:'flex', justifyContent:'space-between', alignItems:'baseline'}}>
                <div>
                  <div style={{fontFamily: site.mono, fontSize:10, letterSpacing:'.32em', opacity:.6}}>EDITING SLOT · {SLOTS.find(s=>s.id===activeSlot).time}</div>
                  <div style={{fontFamily: site.serif, fontStyle:'italic', fontWeight:500, fontSize:42, marginTop:4, lineHeight:1, letterSpacing:'-.02em'}}>{SLOTS.find(s=>s.id===activeSlot).label}.</div>
                  <div style={{fontFamily: site.serif, fontStyle:'italic', fontSize:17, opacity:.78, marginTop:8}}>{SLOTS.find(s=>s.id===activeSlot).note}</div>
                </div>
                {activeStickId && (
                  <button onClick={() => setStack(p=>({...p, [activeSlot]:null}))} style={{background:'transparent', border:'none', cursor:'pointer', fontFamily: site.mono, fontSize:10, letterSpacing:'.28em', opacity:.7}}>− CLEAR SLOT</button>
                )}
              </div>

              <div style={{marginTop:24, display:'grid', gridTemplateColumns: vp.isMobile ? 'repeat(2, 1fr)' : 'repeat(5, 1fr)', gap:14}}>
                {SKUS.map((sku)=>{
                  const picked = activeStickId === sku.id;
                  const cw = APS_SKU[sku.id];
                  return (
                    <div key={sku.id} onClick={() => setSlot(activeSlot, sku.id)} style={{
                      cursor:'pointer', padding:'14px 12px',
                      background: picked ? cw.bg : site.paper, color: picked ? cw.fg : site.ink,
                      border: picked ? `1px solid ${cw.fg}` : `.5px solid ${site.rule}`,
                      transition:'all .15s ease',
                      display:'flex', flexDirection:'column', gap:6,
                    }}>
                      <div style={{display:'flex', justifyContent:'space-between', alignItems:'baseline'}}>
                        <span style={{fontFamily: site.mono, fontSize:9, letterSpacing:'.26em', opacity:.7}}>NO. {sku.no}</span>
                        {picked && <span style={{fontFamily: site.mono, fontSize:9, letterSpacing:'.22em', opacity:.85}}>✓ PICKED</span>}
                      </div>
                      <div style={{fontFamily: site.serif, fontStyle:'italic', fontWeight:500, fontSize:24, lineHeight:1, marginTop:4}}>{sku.enLong}.</div>
                      <div style={{fontFamily: site.han, fontSize:11, letterSpacing:'.2em', opacity:.78}}>{sku.krFull}</div>
                      <div style={{fontFamily: site.serif, fontStyle:'italic', fontSize:13, lineHeight:1.3, opacity:.82, marginTop:8}}>“{sku.fn}.”</div>
                      <div style={{display:'flex', justifyContent:'space-between', marginTop:8, fontFamily: site.mono, fontSize:9, letterSpacing:'.22em', opacity:.65}}>
                        <span>{sku.role.toUpperCase()}</span>
                        <span>${Math.round(PRICE[sku.id]*.85)}/BOX</span>
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>

            {/* presets */}
            <div style={{marginTop:32}}>
              <div style={{fontFamily: site.mono, fontSize:10, letterSpacing:'.32em', opacity:.55}}>OR START FROM A PRESET</div>
              <div style={{display:'grid', gridTemplateColumns: vp.isMobile ? '1fr' : 'repeat(3, 1fr)', gap:14, marginTop:14}}>
                {[
                  { name:'The Office Day',  preset:{morning:'focus', midday:'hydrate', training:null, winddown:'sleep', rescue:null} },
                  { name:'The Athlete',     preset:{morning:'focus', midday:'hydrate', training:'recover', winddown:'sleep', rescue:null} },
                  { name:'The Diplomat',    preset:{morning:'focus', midday:'hydrate', training:null, winddown:'sleep', rescue:'revive'} },
                ].map((p)=>(
                  <button key={p.name} onClick={() => setStack(p.preset)} style={{
                    background:'transparent', border:`.5px solid ${site.rule}`, padding:'18px 18px',
                    fontFamily: site.serif, fontStyle:'italic', fontSize:20, color: site.ink,
                    cursor:'pointer', textAlign:'left', letterSpacing:'-.01em',
                  }}>
                    {p.name}.
                    <div style={{fontFamily: site.mono, fontSize:9, letterSpacing:'.26em', opacity:.55, marginTop:6}}>
                      {Object.values(p.preset).filter(Boolean).length} FORMULAS
                    </div>
                  </button>
                ))}
              </div>
            </div>
          </div>

          {/* RIGHT — summary card */}
          <div style={{position: vp.isMobile ? 'static' : 'sticky', top:140}}>
            <div style={{background: site.ink, color: site.paper, padding:'32px 30px'}}>
              <div style={{fontFamily: site.mono, fontSize:10, letterSpacing:'.32em', opacity:.6}}>YOUR RITUAL</div>
              <div style={{fontFamily: site.serif, fontStyle:'italic', fontWeight:500, fontSize:44, lineHeight:1, marginTop:6, letterSpacing:'-.02em'}}>A custom day.</div>

              <div style={{marginTop:24, display:'flex', flexDirection:'column', gap:0, borderTop:'.5px solid rgba(239,230,212,.18)'}}>
                {SLOTS.map((slot)=>{
                  const filled = stack[slot.id];
                  const sku = filled ? SKU_BY_ID[filled] : null;
                  const cw  = filled ? APS_SKU[filled] : null;
                  return (
                    <div key={slot.id} style={{display:'grid', gridTemplateColumns:'auto 1fr auto', gap:14, padding:'14px 0', borderBottom:'.5px solid rgba(239,230,212,.18)', alignItems:'center'}}>
                      <div style={{fontFamily: site.mono, fontSize:9, letterSpacing:'.26em', opacity:.55, width:64}}>{slot.time}</div>
                      <div>
                        {sku ? (
                          <>
                            <div style={{fontFamily: site.serif, fontStyle:'italic', fontSize:22, lineHeight:1.05}}>{sku.enLong}.</div>
                            <div style={{fontFamily: site.mono, fontSize:9, letterSpacing:'.24em', opacity:.55, marginTop:2}}>NO. {sku.no} · {sku.role.toUpperCase()}</div>
                          </>
                        ) : (
                          <div style={{fontFamily: site.serif, fontStyle:'italic', fontSize:18, opacity:.5}}>— empty —</div>
                        )}
                      </div>
                      {sku && <div style={{width:8, height:32, background: cw.bg}}></div>}
                    </div>
                  );
                })}
              </div>

              <div style={{marginTop:24, display:'flex', flexDirection:'column', gap:8}}>
                <div style={{display:'flex', justifyContent:'space-between', fontFamily: site.mono, fontSize:11, letterSpacing:'.22em', opacity:.7}}>
                  <span>STICKS / MONTH</span><span>{totalSticks}</span>
                </div>
                <div style={{display:'flex', justifyContent:'space-between', fontFamily: site.mono, fontSize:11, letterSpacing:'.22em', opacity:.7}}>
                  <span>CADENCE</span>
                  <span style={{display:'flex', gap:8}}>
                    {[2,4,6].map((w)=>(
                      <span key={w} onClick={() => setCadence(w)} style={{cursor:'pointer', opacity: cadence === w ? 1 : .5, borderBottom: cadence === w ? `1px solid ${site.paper}` : '1px solid transparent'}}>{w}W</span>
                    ))}
                  </span>
                </div>
                <div style={{display:'flex', justifyContent:'space-between', fontFamily: site.mono, fontSize:11, letterSpacing:'.22em', opacity:.7}}>
                  <span>SUBSCRIBER DISCOUNT</span><span>−15%</span>
                </div>
              </div>

              <div style={{marginTop:24, padding:'18px 0', borderTop:'.5px solid rgba(239,230,212,.18)', borderBottom:'.5px solid rgba(239,230,212,.18)', display:'flex', justifyContent:'space-between', alignItems:'baseline'}}>
                <span style={{fontFamily: site.serif, fontStyle:'italic', fontSize:24}}>Per cycle</span>
                <span style={{fontFamily: site.serif, fontStyle:'italic', fontSize:44, letterSpacing:'-.01em'}}>${subPrice}</span>
              </div>

              <button onClick={() => drop.open('stack')} className="rg-btn" style={{
                width:'100%', marginTop:18, padding:'18px',
                background: site.paper, color: site.ink, border:'none',
                fontFamily: site.mono, fontSize:11, letterSpacing:'.28em',
                cursor:'pointer', textTransform:'uppercase',
                display:'inline-flex', alignItems:'center', justifyContent:'space-between', gap:10,
              }}>
                <span>Sign up for drop release</span>
                <span style={{display:'flex', alignItems:'center', gap:10}}>
                  <span style={{opacity:.55, fontSize:10}}>EST. ${subPrice}/CYCLE</span>
                  <AnimatedArrow />
                </span>
              </button>

              <div style={{marginTop:14, fontFamily: site.mono, fontSize:9, letterSpacing:'.24em', opacity:.55, textAlign:'center'}}>
                FIRST BOX SHIPS IN 2 DAYS · CANCEL ANY TIME
              </div>
            </div>

            {/* small reassurance card */}
            <div style={{marginTop:18, padding:'20px 22px', background: site.hanji, fontFamily: site.serif, fontStyle:'italic', fontSize:16, lineHeight:1.4}}>
              “Skip a month, change a formula, pause for travel — the apothecary follows you, not the other way around.”
              <div style={{fontFamily: site.mono, fontStyle:'normal', fontSize:9, letterSpacing:'.28em', opacity:.55, marginTop:10}}>OUR PHARMACIST</div>
            </div>
          </div>
        </div>
      </section>
    </div>
  );
}

Object.assign(window, { PageStack });
