/* Rocket Closet — Order Drawer + Menu + Tweaks + App Shell */
const { useState: useS2, useEffect: useE2, useMemo: useM2, useRef: useR2 } = React;
const { fmt, Icon, RcMark, TopBar, RcFooter, Cover, RC } = window.RcShared;
const { Home, Listing, Pdp } = window.RcViews;

// ------- Order drawer -------
const OrderDrawer = ({ open, onClose, items, onRemove }) => {
  const products = items.map(it => ({...it, p: window.RC_PRODUCTS.find(x=>x.id===it.id)})).filter(x=>x.p);
  const subtotal = products.reduce((s,x)=>s+x.p.now, 0);
  const wasTotal = products.reduce((s,x)=>s+x.p.was, 0);
  const saved = wasTotal - subtotal;

  const buildLines = () => products.map(x => {
    return `• ${x.p.id} — ${x.p.brand} ${x.p.name}\n  size ${x.size}${x.color?` · ${x.color}`:''} · ${fmt(x.p.now)} (was ${fmt(x.p.was)})`;
  }).join('\n\n');

  const textCheckout = () => {
    if (!products.length) return;
    const body = [
      `Rocket Closet Spring 2026 — Order (${products.length} items):`,
      ``,
      buildLines(),
      ``,
      `Subtotal: ${fmt(subtotal)} (saving ${fmt(saved)})`
    ].join('\n');
    window.location.href = `sms:${RC.tel}?&body=${encodeURIComponent(body)}`;
  };

  const whatsappCheckout = () => {
    if (!products.length) return;
    const body = [
      `Hello Rocket Closet Concierge,`,
      ``,
      `I'd like to order the following items from the Spring 2026 catalogue:`,
      ``,
      buildLines(),
      ``,
      `Subtotal: ${fmt(subtotal)}  (saving ${fmt(saved)} vs retail)`,
      ``,
      `Please confirm availability and send me a secure payment link.`,
      `— sent via rocketcloset.com`
    ].join('\n');
    const url = `https://wa.me/${RC.phone}?text=${encodeURIComponent(body)}`;
    window.open(url, '_blank');
  };
  const emailCheckout = () => {
    if (!products.length) return;
    const subject = `RC Spring 2026 — Order (${products.length} items)`;
    const body = [
      `Hello Rocket Closet Concierge,`,
      ``,
      `I'd like to order the following items from the Spring 2026 catalogue:`,
      ``,
      buildLines(),
      ``,
      `Subtotal: ${fmt(subtotal)}  (saving ${fmt(saved)} vs retail)`,
      ``,
      `Please confirm availability and send me a secure payment link.`,
      ``,
      `Thank you.`
    ].join('\n');
    window.location.href = `mailto:${RC.email}?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(body)}`;
  };

  const [copied, setCopied] = useS2(false);
  const copyCheckout = async () => {
    if (!products.length) return;
    const body = [
      `Hello Rocket Closet Concierge,`,
      ``,
      `I'd like to order the following items from the Spring 2026 catalogue:`,
      ``,
      buildLines(),
      ``,
      `Subtotal: ${fmt(subtotal)}  (saving ${fmt(saved)} vs retail)`,
      ``,
      `Please confirm availability and send me a secure payment link.`
    ].join('\n');
    try {
      await navigator.clipboard.writeText(body);
    } catch (_) {
      // Fallback — textarea + execCommand
      const ta = document.createElement('textarea');
      ta.value = body; ta.style.position='fixed'; ta.style.opacity='0';
      document.body.appendChild(ta); ta.select();
      try { document.execCommand('copy'); } catch(_){}
      document.body.removeChild(ta);
    }
    setCopied(true);
    setTimeout(()=>setCopied(false), 2200);
  };

  return (
    <>
      <div className={`drawer-scrim ${open?'on':''}`} onClick={onClose}/>
      <div className={`drawer ${open?'on':''}`}>
        <div className="drawer-head">
          <div>
            <span className="h">Order List</span>
            <span className="sub"> · {products.length}</span>
          </div>
          <button className="close" onClick={onClose}><Icon.close/></button>
        </div>

        <div className="drawer-body">
          {products.length === 0 ? (
            <div className="empty">
              <div className="k">Empty</div>
              <h3>Your list is empty</h3>
              <p>Tap any piece and add it to your Order List. When ready, check out by WhatsApp or email.</p>
            </div>
          ) : products.map((x,i) => (
            <div className="order-row" key={x.id+i}>
              <div className="thumb"><span>{x.p.brand}</span></div>
              <div>
                <div className="b">{x.p.brand}</div>
                <div className="n">{x.p.name}</div>
                <div className="m">{x.p.id} · {x.size}{x.color?` · ${x.color}`:''}</div>
              </div>
              <div>
                <div className="p">{fmt(x.p.now)}</div>
                <button className="rm" onClick={()=>onRemove(i)}>Remove</button>
              </div>
            </div>
          ))}
        </div>

        {products.length > 0 && (
          <div className="drawer-foot">
            <div className="sum-row"><span className="l">Retail</span><span style={{textDecoration:'line-through', color:'var(--muted)'}}>{fmt(wasTotal)}</span></div>
            <div className="sum-row"><span className="l">You save</span><span style={{color:'var(--accent)'}}>{fmt(saved)}</span></div>
            <div className="sum-row total"><span className="l" style={{fontFamily:'var(--serif)',letterSpacing:'.24em', fontSize:11}}>Subtotal</span><span>{fmt(subtotal)}</span></div>
            <div className="choose">
              <button className="wa" onClick={whatsappCheckout}><Icon.wa/> WhatsApp</button>
              <button className="em" onClick={textCheckout}><Icon.phone/> Text</button>
              <button className="em" onClick={emailCheckout}><Icon.mail/> Email</button>
              <button className="em" onClick={copyCheckout} style={{gridColumn:'1 / -1'}}>
                {copied ? '✓ Copied to clipboard' : 'Copy order'}
              </button>
            </div>
            <div className="note">
              <strong style={{color:'var(--ink)'}}>Concierge:</strong> WhatsApp {RC.phoneDisplay} · Text/call {RC.telDisplay}<br/>
              Replies within 24h with a secure payment link. RC Storage account required · from $500/yr.
            </div>
          </div>
        )}
      </div>
    </>
  );
};

// ------- Menu drawer -------
const MenuDrawer = ({ open, onClose, go }) => (
  <>
    <div className={`drawer-scrim ${open?'on':''}`} onClick={onClose}/>
    <div className={`drawer ${open?'on':''}`} style={{right:'auto', left:0, transform: open?'translateX(0)':'translateX(-100%)', borderLeft:0, borderRight:'1px solid var(--hairline)'}}>
      <div className="drawer-head">
        <div><span className="h">Catalogue</span><span className="sub"> · menu</span></div>
        <button className="close" onClick={onClose}><Icon.close/></button>
      </div>
      <div className="drawer-body" style={{padding:'14px 20px'}}>
        {[
          ['Home', {view:'home'}],
          ['Men', {view:'listing', gender:'men'}],
          ['Women', {view:'listing', gender:'women'}],
          ['Kids', {view:'listing', gender:'kids'}],
          ['Jackets', {view:'listing', gender:'men', cat:'jackets'}],
          ['Pants', {view:'listing', gender:'men', cat:'pants'}],
          ['Gear', {view:'listing', gender:'men', cat:'gear'}],
          ['Accessories', {view:'listing', gender:'men', cat:'accessories'}],
        ].map(([label, dest], i) => (
          <button key={i} onClick={()=>{ go(dest); onClose(); }} style={{display:'block', width:'100%', textAlign:'left', padding:'14px 0', borderBottom:'1px solid color-mix(in srgb, var(--ink) 10%, transparent)', fontFamily:'var(--serif)', fontSize:18, letterSpacing:'.02em'}}>
            {label}
          </button>
        ))}
        <div style={{marginTop:20, fontFamily:'var(--mono)', fontSize:10, letterSpacing:'.22em', color:'var(--muted)', textTransform:'uppercase'}}>Resorts</div>
        <div style={{display:'flex', flexWrap:'wrap', gap:6, marginTop:8, fontFamily:'var(--serif)', fontSize:11, letterSpacing:'.2em', textTransform:'uppercase', color:'var(--ink-soft)'}}>
          {['Vail','Aspen','Park City','Beaver Creek','Snowmass','Deer Valley'].map(r => <span key={r} style={{padding:'6px 10px', border:'1px solid color-mix(in srgb, var(--ink) 18%, transparent)'}}>{r}</span>)}
        </div>
        <div style={{marginTop:24, padding:14, background:'var(--ink)', color:'var(--paper)'}}>
          <div style={{fontFamily:'var(--serif)', letterSpacing:'.26em', fontSize:10, textTransform:'uppercase', color:'var(--bronze-soft)'}}>Concierge</div>
          <div style={{marginTop:8, display:'flex', flexDirection:'column', gap:6}}>
            <a href={`tel:${RC.tel}`} style={{color:'#fff', textDecoration:'none', display:'flex', alignItems:'center', gap:8, fontSize:13, letterSpacing:'.06em'}}>
              <Icon.phone/> <span>Text or call · {RC.telDisplay}</span>
            </a>
            <a href={`https://wa.me/${RC.phone}`} target="_blank" rel="noopener" style={{color:'#fff', textDecoration:'none', display:'flex', alignItems:'center', gap:8, fontSize:13, letterSpacing:'.06em'}}>
              <Icon.wa/> <span>WhatsApp · {RC.phoneDisplay}</span>
            </a>
            <a href={`mailto:${RC.email}`} style={{color:'#fff', textDecoration:'none', display:'flex', alignItems:'center', gap:8, fontSize:13, letterSpacing:'.04em'}}>
              <Icon.mail/> <span>{RC.email}</span>
            </a>
          </div>
          <div style={{fontFamily:'var(--mono)', fontSize:10, letterSpacing:'.2em', marginTop:10, opacity:.6, textTransform:'uppercase'}}>Replies within 24 hours</div>
        </div>
      </div>
    </div>
  </>
);

// ------- Tweaks panel -------
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "theme": "light",
  "density": "standard",
  "accent": "#E0672E"
}/*EDITMODE-END*/;

const TweaksPanel = ({ visible, values, onChange }) => {
  if (!visible) return null;
  return (
    <div className={`tweaks on`}>
      <div className="th">Tweaks</div>
      <div className="row">
        <span className="lab">Theme</span>
        <div className="seg">
          <button className={values.theme==='light'?'on':''} onClick={()=>onChange({theme:'light'})}>Paper</button>
          <button className={values.theme==='dark'?'on':''} onClick={()=>onChange({theme:'dark'})}>Midnight</button>
        </div>
      </div>
      <div className="row">
        <span className="lab">Density</span>
        <div className="seg-mini">
          <button className={values.density==='standard'?'on':''} onClick={()=>onChange({density:'standard'})}>Standard</button>
          <button className={values.density==='compact'?'on':''} onClick={()=>onChange({density:'compact'})}>Compact</button>
        </div>
      </div>
      <div className="row">
        <span className="lab">Orange</span>
        <input type="color" value={values.accent} onChange={e=>onChange({accent:e.target.value})}/>
      </div>
      <div className="row" style={{fontFamily:'var(--mono)', fontSize:9.5, letterSpacing:'.12em', color:'rgba(255,255,255,.5)', textTransform:'uppercase', lineHeight:1.5}}>
        Orange is punctuation — never paint. Used only for the CLOSET wordmark, slogan, CTAs &amp; discount badges.
      </div>
    </div>
  );
};

// ------- App -------
const App = () => {
  const [route, setRoute] = useS2(()=>{
    try { return JSON.parse(localStorage.getItem('rc_route')) || {view:'cover'}; } catch(e){ return {view:'cover'};}
  });
  const [cart, setCart] = useS2(()=>{ try { return JSON.parse(localStorage.getItem('rc_cart'))||[]; } catch(e){ return [];}});
  const [favs, setFavs] = useS2(()=>{ try { return new Set(JSON.parse(localStorage.getItem('rc_favs'))||[]); } catch(e){ return new Set();}});
  const [cartOpen, setCartOpen] = useS2(false);
  const [menuOpen, setMenuOpen] = useS2(false);
  const [tweaksVisible, setTweaksVisible] = useS2(false);
  const [tweaks, setTweaks] = useS2(TWEAK_DEFAULTS);

  useE2(()=>{ localStorage.setItem('rc_route', JSON.stringify(route)); window.scrollTo({top:0,behavior:'instant'});},[route]);
  useE2(()=>{ localStorage.setItem('rc_cart', JSON.stringify(cart));}, [cart]);
  useE2(()=>{ localStorage.setItem('rc_favs', JSON.stringify(Array.from(favs)));}, [favs]);

  // apply tweaks to DOM
  useE2(()=>{
    const root = document.documentElement;
    document.body.classList.toggle('theme-dark', tweaks.theme==='dark');
    root.style.setProperty('--orange', tweaks.accent);
    document.body.classList.toggle('density-compact', tweaks.density==='compact');
  }, [tweaks]);

  // tweaks toolbar handshake
  useE2(()=>{
    const handler = (e) => {
      if (!e.data || typeof e.data !== 'object') return;
      if (e.data.type === '__activate_edit_mode') setTweaksVisible(true);
      if (e.data.type === '__deactivate_edit_mode') setTweaksVisible(false);
    };
    window.addEventListener('message', handler);
    window.parent.postMessage({type:'__edit_mode_available'}, '*');
    return ()=> window.removeEventListener('message', handler);
  },[]);

  const addToCart = (item) => {
    setCart(c => [...c.filter(x=>!(x.id===item.id && x.size===item.size && x.color===item.color)), item]);
    setTimeout(()=>setCartOpen(true), 180);
  };
  const removeFromCart = (idx) => setCart(c => c.filter((_,i)=>i!==idx));
  const toggleFav = (id) => setFavs(f => {
    const n = new Set(f); n.has(id) ? n.delete(id) : n.add(id); return n;
  });

  const go = (r) => { setRoute(r); setMenuOpen(false); };
  const inCart = route.view === 'pdp' ? cart.some(x=>x.id===route.id) : false;

  const current = route.view;

  return (
    <div className={`rc-stage ${current==='cover'?'hide-on-cover':''}`}>
      {current !== 'cover' && (
        <TopBar onMenu={()=>setMenuOpen(true)} onCart={()=>setCartOpen(true)} cartCount={cart.length}
          section={current==='listing' ? (route.gender==='men'?'MEN':route.gender==='women'?'WOMEN':'KIDS') : current==='pdp' ? 'DETAIL' : ''}
        />
      )}
      <div className="scroll-area">
        {current==='cover' && <Cover onEnter={()=>go({view:'home'})} />}
        {current==='home' && <Home go={go} openCart={()=>setCartOpen(true)} cartCount={cart.length} favs={favs} onFav={toggleFav}/>}
        {current==='listing' && <Listing gender={route.gender} initialCat={route.cat} go={go} onFav={toggleFav} favs={favs}/>}
        {current==='pdp' && <Pdp id={route.id} from={route.from} go={go} onAdd={addToCart} inCart={inCart} onFav={toggleFav} favs={favs}/>}
      </div>
      {current !== 'cover' && <RcFooter/>}

      <OrderDrawer open={cartOpen} onClose={()=>setCartOpen(false)} items={cart} onRemove={removeFromCart}/>
      <MenuDrawer open={menuOpen} onClose={()=>setMenuOpen(false)} go={go}/>
      <TweaksPanel visible={tweaksVisible} values={tweaks} onChange={(patch)=>{
        const next = {...tweaks, ...patch};
        setTweaks(next);
        window.parent.postMessage({type:'__edit_mode_set_keys', edits: patch}, '*');
      }}/>
    </div>
  );
};

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