// Modal overlays — collection story, lookbook lightbox, consultation form.

const { useState: useStateO, useEffect: useEffectO } = React;

// ───────────────────────────────────────────── COLLECTION STORY MODAL
function CollectionView({ collectionId, onClose }){
  const collection = window.PG_DATA.COLLECTIONS.find(c=>c.id===collectionId);
  useEffectO(()=>{
    if(!collection) return;
    document.body.style.overflow = 'hidden';
    const onKey = e=>{ if(e.key==='Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return ()=>{ document.body.style.overflow=''; window.removeEventListener('keydown', onKey); };
  },[collection, onClose]);
  if(!collection) return null;

  const enquireLink = `https://wa.me/971566854889?text=${encodeURIComponent(`Hi Pavit Gujral, I'd like to enquire about the ${collection.name} Collection.`)}`;

  return (
    <div className="modal-backdrop" style={{overflow:'auto', flexDirection:'column'}}>
      <button className="modal-close" onClick={onClose} aria-label="Close">✕</button>

      {/* Hero panel — black with epigraph + key piece */}
      <section style={{minHeight:'100vh', display:'grid', gridTemplateColumns:'1fr 1fr', background:'var(--noir)', position:'relative'}}>
        <div style={{padding:'120px 80px', display:'flex', flexDirection:'column', justifyContent:'center'}}>
          <div className="label" style={{color:'var(--rose)', marginBottom:24}}>Pavit Gujral · The Collection</div>
          <p className="display-italic" style={{fontSize:28, color:'var(--rose)', marginBottom:12, fontWeight:300}}>The</p>
          <h1 className="display" style={{fontSize:'clamp(80px, 11vw, 180px)', lineHeight:.9, color:'var(--paper)', letterSpacing:'-.02em', fontWeight:300, marginBottom:24, textTransform:'uppercase'}}>
            {collection.name}
          </h1>
          <p className="display-italic" style={{fontSize:22, color:'var(--bone)', lineHeight:1.4, fontWeight:300, marginBottom:6, opacity:.92, maxWidth:'42ch'}}>
            {collection.epigraph}
          </p>
          <p className="label" style={{color:'var(--rose)', fontSize:10.5}}>{collection.attribution}</p>

          <div style={{display:'flex', gap:16, marginTop:60}}>
            <a className="btn btn-solid" href={enquireLink} target="_blank" rel="noopener">Enquire about this collection <span className="arr">→</span></a>
          </div>
        </div>
        <div style={{position:'relative', background:'#0a0808'}}>
          <img src={collection.keyart} alt="" style={{width:'100%', height:'100%', objectFit:'cover', opacity:.9}}/>
          <div style={{position:'absolute', inset:0, background:'linear-gradient(90deg, var(--noir) 0%, transparent 30%)'}}></div>
        </div>
      </section>

      {/* Story panel */}
      <section style={{background:'var(--noir-2)', padding:'120px 80px', borderTop:'1px solid var(--line)'}}>
        <div style={{maxWidth:1200, margin:'0 auto', display:'grid', gridTemplateColumns:'1fr 2fr', gap:80, alignItems:'start'}}>
          <div className="label" style={{color:'var(--rose)'}}>The story · {collection.theme}</div>
          <div style={{display:'flex', flexDirection:'column', gap:24}}>
            {collection.story.map((p,i)=>(
              <p key={i} className="display" style={{fontSize: i===0?30:22, lineHeight:1.45, color: i===0?'var(--paper)':'var(--bone)', fontWeight:300, letterSpacing:'-.005em'}}>
                {p}
              </p>
            ))}
          </div>
        </div>
      </section>

      {/* Pieces gallery */}
      <section style={{background:'var(--noir)', padding:'120px 80px 160px'}}>
        <div style={{maxWidth:1280, margin:'0 auto'}}>
          <div style={{display:'flex', justifyContent:'space-between', alignItems:'end', marginBottom:60}}>
            <h2 className="display" style={{fontSize:48, color:'var(--paper)', fontWeight:300}}>
              Pieces <span className="display-italic" style={{color:'var(--rose)'}}>in the collection</span>
            </h2>
            <span className="label" style={{color:'var(--muted)'}}>{collection.pieces.length} pieces · price on request</span>
          </div>

          <div style={{display:'grid', gridTemplateColumns:'repeat(auto-fit, minmax(360px, 1fr))', gap:32}}>
            {collection.pieces.map(p=>(
              <PieceCard key={p.id} piece={p}/>
            ))}
          </div>
        </div>
      </section>
    </div>
  );
}

function PieceCard({ piece }){
  const [hover, setHover] = useStateO(false);
  const link = `https://wa.me/971566854889?text=${encodeURIComponent(`Hi Pavit Gujral, I'd like to enquire about: ${piece.enquire}`)}`;
  return (
    <div
      onMouseEnter={()=>setHover(true)}
      onMouseLeave={()=>setHover(false)}
      style={{background:'#15110E', border:'1px solid var(--line)', overflow:'hidden', display:'flex', flexDirection:'column'}}>
      <div style={{position:'relative', aspectRatio:'4/5', background:'#1a1612', overflow:'hidden'}}>
        <img src={piece.img} alt={piece.name}
          style={{width:'100%', height:'100%', objectFit:'cover', transform:hover?'scale(1.04)':'scale(1)', transition:'transform 1s cubic-bezier(.2,.7,.2,1)', filter:'contrast(1.04)'}}/>
        {piece.badge && (
          <div style={{position:'absolute', top:18, left:18, background:'rgba(217,166,166,.95)', color:'var(--noir)', padding:'7px 12px', fontSize:9.5, letterSpacing:'.2em', textTransform:'uppercase', fontWeight:500}}>
            ★ {piece.badge}
          </div>
        )}
      </div>
      <div style={{padding:'28px 28px 32px', display:'flex', flexDirection:'column', gap:14}}>
        <h3 className="display" style={{fontSize:28, color:'var(--paper)', fontWeight:300, letterSpacing:'-.005em'}}>{piece.name}</h3>
        <p style={{fontSize:12.5, color:'var(--muted)', lineHeight:1.6, fontFamily:'var(--body)'}}>{piece.materials}</p>
        <p style={{fontSize:13.5, color:'var(--bone)', lineHeight:1.6, opacity:.85, fontStyle:'italic'}}>{piece.inspiration}</p>
        <a href={link} target="_blank" rel="noopener" style={{
          marginTop:10, display:'inline-flex', alignItems:'center', gap:10,
          fontSize:11, letterSpacing:'.22em', textTransform:'uppercase', color:'var(--rose)',
          paddingTop:14, borderTop:'1px solid var(--line)'
        }}>
          Enquire · Price on request <span style={{transform:hover?'translateX(4px)':'translateX(0)', transition:'transform .25s'}}>→</span>
        </a>
      </div>
    </div>
  );
}

// ───────────────────────────────────────────── LOOKBOOK LIGHTBOX
function Lightbox({ index, onClose, onNext, onPrev }){
  const items = window.PG_DATA.LOOKBOOK;
  useEffectO(()=>{
    document.body.style.overflow = 'hidden';
    const onKey = e=>{
      if(e.key==='Escape') onClose();
      if(e.key==='ArrowRight') onNext();
      if(e.key==='ArrowLeft') onPrev();
    };
    window.addEventListener('keydown', onKey);
    return ()=>{ document.body.style.overflow=''; window.removeEventListener('keydown', onKey); };
  },[onClose, onNext, onPrev]);
  if(index==null) return null;
  const item = items[index];
  return (
    <div className="modal-backdrop" style={{padding:'80px 0', alignItems:'center', justifyContent:'center'}}>
      <button className="modal-close" onClick={onClose}>✕</button>
      <button onClick={onPrev} aria-label="Previous" style={{position:'fixed', left:24, top:'50%', transform:'translateY(-50%)', width:54, height:54, borderRadius:'50%', background:'rgba(250,246,239,.06)', color:'var(--paper)', border:'1px solid var(--line-2)', zIndex:110, fontSize:20}}>‹</button>
      <button onClick={onNext} aria-label="Next" style={{position:'fixed', right:24, top:'50%', transform:'translateY(-50%)', width:54, height:54, borderRadius:'50%', background:'rgba(250,246,239,.06)', color:'var(--paper)', border:'1px solid var(--line-2)', zIndex:110, fontSize:20}}>›</button>
      <div style={{display:'flex', flexDirection:'column', alignItems:'center', gap:18, maxHeight:'90vh', maxWidth:'92vw'}}>
        <img src={item.src} alt={item.label} style={{maxWidth:'90vw', maxHeight:'80vh', objectFit:'contain', boxShadow:'0 30px 100px rgba(0,0,0,.7)'}}/>
        <div style={{display:'flex', alignItems:'center', gap:20, color:'var(--paper)'}}>
          <span className="label" style={{color:'var(--rose)', fontSize:10}}>{item.label}</span>
          <span style={{fontSize:11, color:'var(--muted)', letterSpacing:'.2em', textTransform:'uppercase'}}>{index+1} / {items.length}</span>
        </div>
      </div>
    </div>
  );
}

// ───────────────────────────────────────────── CONSULTATION FORM MODAL
function ConsultationForm({ open, onClose, initialCollection='' }){
  const [data, setData] = useStateO({
    name:'', email:'', phone:'', occasion:'Bespoke / customised design',
    collection: initialCollection, message:''
  });
  const [sent, setSent] = useStateO(false);
  useEffectO(()=>{
    if(open){
      document.body.style.overflow='hidden';
      setSent(false);
      setData(d=>({...d, collection: initialCollection}));
    } else {
      document.body.style.overflow='';
    }
    const onKey = e=>{ if(e.key==='Escape' && open) onClose(); };
    window.addEventListener('keydown', onKey);
    return ()=>window.removeEventListener('keydown', onKey);
  },[open, onClose, initialCollection]);
  if(!open) return null;

  const set = (k,v)=>setData(d=>({...d, [k]:v}));

  const handoff = ()=>{
    const lines = [
      `Hi Pavit Gujral, I'd like to book a consultation.`,
      data.name && `Name: ${data.name}`,
      data.email && `Email: ${data.email}`,
      data.phone && `Phone: ${data.phone}`,
      `Occasion: ${data.occasion}`,
      data.collection && `Collection of interest: ${data.collection}`,
      data.message && `Message: ${data.message}`
    ].filter(Boolean).join('\n');
    const url = `https://wa.me/971566854889?text=${encodeURIComponent(lines)}`;
    window.open(url, '_blank');
    setSent(true);
  };

  const COLLECTIONS = window.PG_DATA.COLLECTIONS;

  return (
    <div className="modal-backdrop" style={{padding:0, alignItems:'stretch'}}>
      <div style={{display:'grid', gridTemplateColumns:'1fr 1.2fr', width:'100%', minHeight:'100vh', overflow:'auto'}}>

        {/* Left — context panel */}
        <div style={{background:'var(--noir)', padding:'120px 80px', position:'relative', display:'flex', flexDirection:'column', justifyContent:'space-between'}}>
          <button className="modal-close" onClick={onClose} style={{top:24, left:24, right:'auto'}}>✕</button>
          <div>
            <div className="label" style={{color:'var(--rose)', marginBottom:24, marginTop:40}}>Book a Consultation</div>
            <h2 className="display" style={{fontSize:'clamp(40px, 5vw, 64px)', lineHeight:1.02, color:'var(--paper)', maxWidth:'12ch', fontWeight:300}}>
              The first <span className="display-italic" style={{color:'var(--rose)'}}>conversation</span> is yours.
            </h2>
            <p style={{marginTop:32, fontSize:15, color:'var(--bone)', lineHeight:1.7, maxWidth:380, opacity:.85}}>
              Share the brief — an occasion, an inherited stone, a collection that caught the eye — and we will be in touch within the working day. The studio is by appointment.
            </p>
          </div>
          <div style={{marginTop:60, paddingTop:30, borderTop:'1px solid var(--line-2)'}}>
            <div className="label" style={{color:'var(--rose)', marginBottom:14}}>Direct</div>
            <a href={window.PG_DATA.CONTACT.whatsappLink} target="_blank" rel="noopener" style={{fontSize:14, color:'var(--paper)', display:'block', marginBottom:6}}>WhatsApp · {window.PG_DATA.CONTACT.whatsapp}</a>
            <a href={`mailto:${window.PG_DATA.CONTACT.email}`} style={{fontSize:14, color:'var(--paper)', display:'block'}}>{window.PG_DATA.CONTACT.email}</a>
          </div>
        </div>

        {/* Right — form */}
        <div style={{background:'var(--paper)', color:'var(--ink)', padding:'120px 80px'}}>
          {!sent ? (
            <form style={{display:'flex', flexDirection:'column', gap:32, maxWidth:560}} onSubmit={e=>{e.preventDefault(); handoff();}}>
              <div className="label" style={{color:'var(--rose-deep)'}}>Tell us about your piece</div>

              <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:32}}>
                <div className="field">
                  <label>Your name</label>
                  <input required value={data.name} onChange={e=>set('name', e.target.value)} placeholder="—"/>
                </div>
                <div className="field">
                  <label>Email</label>
                  <input required type="email" value={data.email} onChange={e=>set('email', e.target.value)} placeholder="—"/>
                </div>
              </div>

              <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:32}}>
                <div className="field">
                  <label>Phone / WhatsApp</label>
                  <input type="tel" value={data.phone} onChange={e=>set('phone', e.target.value)} placeholder="+971 …"/>
                </div>
                <div className="field">
                  <label>Occasion</label>
                  <select value={data.occasion} onChange={e=>set('occasion', e.target.value)}>
                    <option>Bespoke / customised design</option>
                    <option>Bridal</option>
                    <option>Anniversary / milestone</option>
                    <option>Heirloom reset</option>
                    <option>Investment / collector piece</option>
                    <option>Gifting</option>
                    <option>Press / editorial</option>
                  </select>
                </div>
              </div>

              <div className="field">
                <label>Collection of interest</label>
                <select value={data.collection} onChange={e=>set('collection', e.target.value)}>
                  <option value="">— No preference yet</option>
                  {COLLECTIONS.map(c=>(<option key={c.id} value={c.name}>The {c.name} Collection</option>))}
                </select>
              </div>

              <div className="field">
                <label>Tell us more</label>
                <textarea value={data.message} onChange={e=>set('message', e.target.value)} placeholder="The story, the occasion, the inherited stone…"/>
              </div>

              <div style={{paddingTop:8}}>
                <button className="btn btn-ink" type="submit" style={{padding:'20px 32px'}}>
                  Send via WhatsApp <span className="arr">→</span>
                </button>
                <p style={{fontSize:11, color:'var(--muted-2)', marginTop:16, letterSpacing:'.04em'}}>
                  Submitting will open WhatsApp with your brief pre-filled. We respond within the working day.
                </p>
              </div>
            </form>
          ) : (
            <div style={{maxWidth:520, paddingTop:40}}>
              <div className="label" style={{color:'var(--rose-deep)', marginBottom:24}}>Brief sent</div>
              <h3 className="display" style={{fontSize:'clamp(36px, 4vw, 56px)', lineHeight:1.05, fontWeight:300}}>
                Thank you, {data.name || 'beautifully said'}.
              </h3>
              <p style={{marginTop:24, fontSize:16, lineHeight:1.7, color:'#3a342d'}}>
                Your message has been handed off to WhatsApp. Pavit's atelier responds within the working day — usually faster. While you wait, a few stones to look at:
              </p>
              <div style={{display:'flex', gap:12, marginTop:32, flexWrap:'wrap'}}>
                <button className="btn btn-ink" onClick={onClose}>Continue browsing</button>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { CollectionView, Lightbox, ConsultationForm });
