/* Studio 76 — The Studio. Fully interactive centrepiece. */

function formatINR(n) {
  n = Math.round(n / 100) * 100;
  const s = String(n);
  const last3 = s.slice(-3);
  const rest = s.slice(0, -3);
  const grouped = rest.replace(/\B(?=(\d{2})+(?!\d))/g, ',');
  return '₹' + (rest ? grouped + ',' : '') + last3;
}

function quoteRange(base) {
  return [formatINR(base * 0.9), formatINR(base * 1.12)];
}

function Chip({ active, children, onClick }) {
  return (
    <button onClick={onClick}
      style={{
        fontFamily:'var(--font-body)', fontWeight:600, fontSize:15, cursor:'pointer',
        padding:'10px 18px', borderRadius:999,
        border: active ? '1.5px solid var(--gold-light)' : '1.5px solid rgba(255,255,255,.18)',
        background: active ? 'var(--gold-light)' : 'transparent',
        color: active ? 'var(--ink)' : 'var(--on-ink)',
        transition:'all .25s', whiteSpace:'nowrap',
      }}>
      {children}
    </button>
  );
}

function QuoteCard({ kind, sub, base, accent, dark }) {
  const [lo, hi] = quoteRange(base);
  return (
    <div className="shimmer" style={{
      flex:1, minWidth:0, borderRadius:16, padding:'22px 22px 24px',
      background: dark ? 'rgba(255,255,255,.04)' : 'var(--paper-card)',
      border: `1px solid ${dark ? 'rgba(232,201,122,.28)' : 'rgba(27,19,13,.1)'}`,
      color: dark ? 'var(--on-ink)' : 'var(--ink)', position:'relative',
    }}>
      <div style={{display:'flex', alignItems:'center', gap:9, marginBottom:4}}>
        <span style={{width:9,height:9,borderRadius:9,background:accent,display:'inline-block'}}></span>
        <span className="serif" style={{fontSize:26, fontStyle:'italic'}}>{kind}</span>
      </div>
      <p style={{margin:'0 0 16px', fontSize:13.5, opacity:.7, fontFamily:'var(--font-body)'}}>{sub}</p>
      <div style={{display:'flex', alignItems:'baseline', gap:8, flexWrap:'wrap'}}>
        <span style={{fontFamily:'var(--font-display)', fontWeight:800, fontSize:30, letterSpacing:'-.02em'}}>{lo}</span>
        <span style={{opacity:.55}}>–</span>
        <span style={{fontFamily:'var(--font-display)', fontWeight:800, fontSize:30, letterSpacing:'-.02em'}}>{hi}</span>
      </div>
      <p style={{margin:'8px 0 0', fontSize:12, opacity:.55, fontStyle:'italic', fontFamily:'var(--font-serif)'}}>indicative · final quote after your design review</p>
    </div>
  );
}

function Studio({ accent }) {
  const TABS = ['Upload', 'Paste a link', 'Describe it'];
  const [tab, setTab] = React.useState('Upload');
  const [img, setImg] = React.useState(null);     // dataURL
  const [url, setUrl] = React.useState('');
  const [desc, setDesc] = React.useState('');
  const [drag, setDrag] = React.useState(false);
  const [type, setType] = React.useState('Ring');
  const [gold, setGold] = React.useState('18k');
  const [presence, setPresence] = React.useState('Statement');
  const [reserving, setReserving] = React.useState(false);
  const [reserved, setReserved] = React.useState(false);
  const fileRef = React.useRef(null);

  const readFile = (file) => {
    if (!file || !file.type.startsWith('image/')) return;
    const r = new FileReader();
    r.onload = (e) => setImg(e.target.result);
    r.readAsDataURL(file);
  };
  const onDrop = (e) => { e.preventDefault(); setDrag(false); readFile(e.dataTransfer.files[0]); };

  const p = STUDIO_PRICING[type];
  const m = GOLD_MULT[gold] * PRESENCE_MULT[presence];
  const luxeBase = p.luxe * m;
  const deluxeBase = p.deluxe * m;

  const hasInput = (tab === 'Upload' && img) || (tab === 'Paste a link' && url.trim()) || (tab === 'Describe it' && desc.trim());

  const reset = () => { setReserved(false); setReserving(false); };

  return (
    <section id="studio" className="dark section-pad" style={{overflow:'hidden'}}>
      <div className="wrap">
        <div className="reveal" style={{maxWidth:760, marginBottom:'clamp(34px,5vw,58px)'}}>
          <Eyebrow dark>The Studio</Eyebrow>
          <h2 className="section-title" style={{marginTop:14}}>
            Start the piece you’ve been <span className="serif-italic" style={{color:'var(--gold-light)'}}>carrying around.</span>
          </h2>
          <p style={{maxWidth:560, marginTop:16, color:'var(--on-ink-soft)', fontSize:18}}>
            Bring the image you love. Shape it. See both ways to own it, side by side — then reserve a stylist to make it real.
          </p>
        </div>

        <div className="studio-grid reveal reveal-d1">
          {/* LEFT — input + config */}
          <div className="studio-panel">
            {/* tabs */}
            <div style={{display:'flex', gap:6, marginBottom:18, flexWrap:'wrap'}}>
              {TABS.map(t => (
                <button key={t} onClick={() => setTab(t)}
                  style={{
                    fontFamily:'var(--font-body)', fontWeight:600, fontSize:14, cursor:'pointer',
                    padding:'9px 16px', borderRadius:999, border:'none',
                    background: tab===t ? 'var(--gold-light)' : 'rgba(255,255,255,.06)',
                    color: tab===t ? 'var(--ink)' : 'var(--on-ink-soft)', transition:'.25s',
                  }}>{t}</button>
              ))}
            </div>

            {/* input area */}
            {tab === 'Upload' && (
              <div
                onDragOver={(e)=>{e.preventDefault();setDrag(true);}}
                onDragLeave={()=>setDrag(false)}
                onDrop={onDrop}
                onClick={()=>fileRef.current && fileRef.current.click()}
                style={{
                  border:`1.5px dashed ${drag ? 'var(--gold-light)':'rgba(255,255,255,.28)'}`,
                  borderRadius:14, padding: img ? 0 : '40px 24px', cursor:'pointer',
                  background: drag ? 'rgba(232,201,122,.08)' : 'rgba(255,255,255,.03)',
                  transition:'.25s', textAlign:'center', overflow:'hidden', position:'relative',
                  minHeight: 220, display:'flex', alignItems:'center', justifyContent:'center',
                }}>
                <input ref={fileRef} type="file" accept="image/*" hidden onChange={(e)=>readFile(e.target.files[0])} />
                {img ? (
                  <div style={{position:'relative', width:'100%'}}>
                    <img src={img} alt="Your inspiration" style={{width:'100%', maxHeight:340, objectFit:'cover', display:'block'}} />
                    <span style={{position:'absolute', top:12, left:12}} className="pill accent">Your pin → real</span>
                    <button onClick={(e)=>{e.stopPropagation(); setImg(null);}}
                      style={{position:'absolute', top:12, right:12, border:'none', background:'rgba(0,0,0,.55)', color:'#fff', borderRadius:999, width:30, height:30, cursor:'pointer', fontSize:15}}>✕</button>
                  </div>
                ) : (
                  <div>
                    <div style={{margin:'0 auto 14px', width:54, height:54, borderRadius:999, border:'1.5px solid rgba(255,255,255,.3)', display:'flex', alignItems:'center', justifyContent:'center'}}>
                      <svg viewBox="0 0 24 24" width="24" height="24" fill="none"><path d="M12 16V5m0 0L7.5 9.5M12 5l4.5 4.5M5 19h14" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/></svg>
                    </div>
                    <p style={{margin:'0 0 4px', fontWeight:600, fontSize:17}}>Drop your inspiration here</p>
                    <p style={{margin:0, fontSize:14, color:'var(--on-ink-soft)'}}>or <span style={{color:'var(--gold-light)', textDecoration:'underline'}}>browse</span> — a photo, costume piece, screenshot</p>
                  </div>
                )}
              </div>
            )}

            {tab === 'Paste a link' && (
              <div style={{padding:'8px 0 4px'}}>
                <label style={{fontSize:13, color:'var(--on-ink-soft)', display:'block', marginBottom:8}}>Pinterest pin or image URL</label>
                <input value={url} onChange={(e)=>setUrl(e.target.value)} placeholder="https://pin.it/…  or  image link"
                  style={{width:'100%', padding:'16px 18px', borderRadius:12, border:'1.5px solid rgba(255,255,255,.2)', background:'rgba(255,255,255,.04)', color:'var(--on-ink)', fontSize:16, fontFamily:'var(--font-body)'}} />
                <p style={{fontSize:13, color:'var(--on-ink-soft)', marginTop:12, minHeight:160, display:'flex', alignItems:'center', justifyContent:'center', textAlign:'center', border:'1.5px dashed rgba(255,255,255,.14)', borderRadius:12, padding:20}}>
                  {url.trim() ? '✓ Link received — we’ll pull the image in your design review.' : 'We accept Pinterest, Instagram saves, or any image URL.'}
                </p>
              </div>
            )}

            {tab === 'Describe it' && (
              <div style={{padding:'8px 0 4px'}}>
                <label style={{fontSize:13, color:'var(--on-ink-soft)', display:'block', marginBottom:8}}>Describe the piece you remember</label>
                <textarea value={desc} onChange={(e)=>setDesc(e.target.value)} rows={6}
                  placeholder="“A chunky gold serpent ring with a deep green stone for its head — I saw it years ago and never found it again…”"
                  style={{width:'100%', padding:'16px 18px', borderRadius:12, border:'1.5px solid rgba(255,255,255,.2)', background:'rgba(255,255,255,.04)', color:'var(--on-ink)', fontSize:16, fontFamily:'var(--font-body)', resize:'vertical', minHeight:170}} />
              </div>
            )}

            {/* configurator */}
            <div style={{marginTop:26, display:'flex', flexDirection:'column', gap:20}}>
              <div>
                <p className="label-mono" style={{color:'var(--gold-light)', marginBottom:10}}>Piece</p>
                <div style={{display:'flex', gap:8, flexWrap:'wrap'}}>
                  {STUDIO_TYPES.map(x => <Chip key={x} active={type===x} onClick={()=>setType(x)}>{x}</Chip>)}
                </div>
              </div>
              <div style={{display:'flex', gap:34, flexWrap:'wrap'}}>
                <div>
                  <p className="label-mono" style={{color:'var(--gold-light)', marginBottom:10}}>Gold</p>
                  <div style={{display:'flex', gap:8}}>
                    {STUDIO_GOLD.map(x => <Chip key={x} active={gold===x} onClick={()=>setGold(x)}>{x}</Chip>)}
                  </div>
                </div>
                <div>
                  <p className="label-mono" style={{color:'var(--gold-light)', marginBottom:10}}>Presence</p>
                  <div style={{display:'flex', gap:8, flexWrap:'wrap'}}>
                    {STUDIO_PRESENCE.map(x => <Chip key={x} active={presence===x} onClick={()=>setPresence(x)}>{x}</Chip>)}
                  </div>
                </div>
              </div>
            </div>
          </div>

          {/* RIGHT — live quotes + reserve */}
          <div className="studio-quotes">
            <div style={{display:'flex', alignItems:'baseline', justifyContent:'space-between', marginBottom:16}}>
              <span className="label-mono" style={{color:'var(--gold-light)'}}>Two ways to own it</span>
              <span style={{fontSize:13, color:'var(--on-ink-soft)'}}>{type} · {gold} · {presence}</span>
            </div>

            <div className="quote-row" style={{display:'flex', gap:14}}>
              <QuoteCard kind="Luxe" sub="Brilliant lab-grown stones in solid gold. Identical sparkle, kinder price." base={luxeBase} accent="var(--gold)" dark />
              <QuoteCard kind="Deluxe" sub="Certified natural stones in solid gold. Heirloom-grade, the genuine article." base={deluxeBase} accent="var(--emerald)" dark />
            </div>

            {!reserved ? (
              <div style={{marginTop:18}}>
                {!reserving ? (
                  <button className="btn btn-primary" style={{width:'100%', justifyContent:'center', opacity: hasInput?1:.6}}
                    onClick={()=> hasInput ? setReserving(true) : (setTab('Upload'))}>
                    {hasInput ? 'Reserve a design consultation' : 'Add your inspiration to reserve'} <ArrowR style={{width:18,height:18}}/>
                  </button>
                ) : (
                  <ReserveForm accent={accent} onDone={()=>setReserved(true)} onCancel={()=>setReserving(false)} />
                )}
                <p style={{margin:'14px 2px 0', fontSize:12.5, color:'var(--on-ink-soft)', textAlign:'center'}}>
                  Complimentary · no obligation · a stylist confirms the final quote.
                </p>
              </div>
            ) : (
              <div style={{marginTop:18, border:'1px solid rgba(232,201,122,.3)', borderRadius:14, padding:'26px 24px', textAlign:'center', background:'rgba(232,201,122,.05)'}}>
                <div style={{margin:'0 auto 12px', width:46,height:46,borderRadius:999, background:'var(--gold-light)', color:'var(--ink)', display:'flex',alignItems:'center',justifyContent:'center', fontSize:22}}>✓</div>
                <h3 className="serif" style={{fontSize:25, margin:'0 0 6px'}}>Your Studio 76 piece is reserved.</h3>
                <p style={{margin:'0 0 16px', color:'var(--on-ink-soft)', fontSize:15}}>A stylist will reach out within 48 hours to refine your {type.toLowerCase()} and confirm the quote.</p>
                <button className="link-arrow" onClick={reset} style={{color:'var(--gold-light)'}}>Start another piece <ArrowR style={{width:16,height:16}}/></button>
              </div>
            )}
          </div>
        </div>
      </div>
    </section>
  );
}

function ReserveForm({ onDone, onCancel }) {
  const [name, setName] = React.useState('');
  const [email, setEmail] = React.useState('');
  const ok = name.trim() && /\S+@\S+\.\S+/.test(email);
  const field = {
    width:'100%', padding:'14px 16px', borderRadius:11, marginBottom:10,
    border:'1.5px solid rgba(255,255,255,.2)', background:'rgba(255,255,255,.04)',
    color:'var(--on-ink)', fontSize:15.5, fontFamily:'var(--font-body)',
  };
  return (
    <div style={{border:'1px solid rgba(255,255,255,.14)', borderRadius:14, padding:'18px', background:'rgba(255,255,255,.03)'}}>
      <input style={field} placeholder="Your name" value={name} onChange={e=>setName(e.target.value)} />
      <input style={field} placeholder="Email" type="email" value={email} onChange={e=>setEmail(e.target.value)} />
      <div style={{display:'flex', gap:10, marginTop:4}}>
        <button className="btn btn-primary" style={{flex:1, justifyContent:'center', opacity:ok?1:.55}} onClick={()=> ok && onDone()}>Confirm reservation</button>
        <button className="btn btn-ghost" style={{borderColor:'rgba(255,255,255,.3)'}} onClick={onCancel}>Back</button>
      </div>
    </div>
  );
}

Object.assign(window, { Studio });
