/* ============================================================
   RUDRAA RATNA — Checkout, Custom Mix, Connect, Professional Help
   ============================================================ */

async function rrApiPost(action, payload){
  try{
    const res = await fetch("/rr-api.php?action=" + action, {
      method:"POST", headers:{ "Content-Type":"application/json" }, body:JSON.stringify(payload||{})
    });
    return await res.json();
  }catch(e){ return { ok:false, error:"Could not reach server" }; }
}

/* ---------------- Checkout ---------------- */
function CheckoutPage(){
  const { go } = useContext(Nav);
  const [items] = useState(()=>rrCartItems().map(it=>({ item:it, product:RR.byId(it.id) })).filter(x=>x.product && x.product.inStock!==false));
  const [f,setF] = useState({ name:'', phone:'', email:'', address:'', city:'', pincode:'', intention:'', coupon:'' });
  const [busy,setBusy] = useState(false);
  const [doneRef,setDoneRef] = useState(null);
  const set = (k,v)=>setF(s=>({ ...s, [k]:v }));
  const subtotal = items.reduce((s,x)=>s + x.product.price * Number(x.item.qty||1), 0);
  const couponValid = !!(f.coupon.trim() && RR.settings.offerCode && f.coupon.trim().toUpperCase()===RR.settings.offerCode.toUpperCase());
  const pct = Number(RR.settings.offerPercent)||0;
  const discount = (couponValid && pct>0) ? Math.round(subtotal*pct/100) : 0;
  const total = subtotal - discount;

  const submit = async (viaWa)=>{
    if(!f.name.trim() || !f.phone.trim()){ alert('Please enter your name and phone number.'); return; }
    if(!items.length){ alert('Your cart is empty.'); return; }
    setBusy(true);
    const payload = {
      name:f.name.trim(), phone:f.phone.trim(), email:f.email.trim(),
      address:f.address.trim(), city:f.city.trim(), pincode:f.pincode.trim(),
      intention:f.intention.trim(), coupon:couponValid?f.coupon.trim().toUpperCase():'',
      total:total, items:items.map(x=>({ id:x.product.id, name:x.product.name, qty:Number(x.item.qty||1), price:x.product.price }))
    };
    const r = await rrApiPost('order', payload);
    const ref = (r && r.ok) ? r.ref : '';
    setBusy(false);
    try{ localStorage.setItem('rr_cart_items','[]'); window.dispatchEvent(new CustomEvent('rr_cart_change')); }catch(e){}
    setDoneRef(ref || 'received');
    if(viaWa){
      const lines = items.map(x=>x.product.name + ' x ' + x.item.qty + ' - ' + RR.fmt(x.product.price*Number(x.item.qty||1))).join('\n');
      const msg = "Hi Rudraa Ratna, I placed an order:\n" + lines
        + (f.intention.trim()?("\nIntention: "+f.intention.trim()):'')
        + (couponValid?("\nCoupon: "+f.coupon.trim().toUpperCase()):'')
        + "\nTotal: " + RR.fmt(total) + (ref?("\nOrder ref: "+ref):'')
        + "\nName: " + f.name.trim() + "\nPhone: " + f.phone.trim();
      window.open(RR.wa(msg), '_blank', 'noopener');
    }
  };

  if(doneRef){
    return (
      <main className="pdp">
        <section className="section"><div className="wrap"><Reveal className="section-head center">
          <span className="cw__check"><Icon name="check" size={26}/></span>
          <h1 className="h1" style={{ marginTop:10 }}>Thank you{f.name?(', '+f.name.split(' ')[0]):''}!</h1>
          <p>Your order has been received{doneRef!=='received'?(' — reference '+doneRef):''}. Our team will contact you on WhatsApp to confirm availability, payment and delivery.</p>
          <div className="row gap4 wrapflex center mt6" style={{ justifyContent:'center' }}>
            <button className="btn btn-maroon btn-lg" onClick={()=>go('shop')}>Continue shopping <Icon name="arrow" size={17}/></button>
            <a className="btn btn-wa btn-lg" href={RR.wa("Hi Rudraa Ratna, I just placed an order. Please confirm.")} target="_blank" rel="noopener"><WaGlyph/> Message us</a>
          </div>
        </Reveal></div></section>
        <TrustDisclaimer/>
      </main>
    );
  }
  if(!items.length){
    return (
      <main className="pdp">
        <Breadcrumb items={[{label:'Home',page:'home'},{label:'Checkout'}]}/>
        <section className="section"><div className="wrap"><Reveal className="section-head center">
          <span className="eyebrow no-rule">Checkout</span>
          <h1 className="h1" style={{ marginTop:10 }}>Your cart is empty</h1>
          <p>Add a product, then come back to checkout — or message us on WhatsApp for guided buying.</p>
          <div className="center mt6"><button className="btn btn-maroon btn-lg" onClick={()=>go('shop')}>Browse products <Icon name="arrow" size={17}/></button></div>
        </Reveal></div></section>
      </main>
    );
  }
  return (
    <main>
      <Breadcrumb items={[{label:'Home',page:'home'},{label:'Shop',page:'shop'},{label:'Checkout'}]}/>
      <section className="section tight"><div className="wrap checkout">
        <Reveal className="section-head"><span className="eyebrow no-rule">Checkout</span><h1 className="h1" style={{marginTop:10}}>Confirm your order</h1></Reveal>
        <div className="checkout__grid mt8">
          <div className="checkout__form card">
            <h3 className="h3">Your details</h3>
            <div className="adm-grid2 mt4">
              <div className="field full"><label>Full name *</label><input className="input" value={f.name} onChange={e=>set('name',e.target.value)} placeholder="Your name"/></div>
              <div className="field"><label>Phone *</label><input className="input" value={f.phone} onChange={e=>set('phone',e.target.value)} placeholder="+91 …" inputMode="tel"/></div>
              <div className="field"><label>Email</label><input className="input" value={f.email} onChange={e=>set('email',e.target.value)} placeholder="you@email.com"/></div>
              <div className="field full"><label>Delivery address</label><textarea className="input" value={f.address} onChange={e=>set('address',e.target.value)} placeholder="House / street / area"/></div>
              <div className="field"><label>City</label><input className="input" value={f.city} onChange={e=>set('city',e.target.value)}/></div>
              <div className="field"><label>Pincode</label><input className="input" value={f.pincode} onChange={e=>set('pincode',e.target.value)} inputMode="numeric"/></div>
              <div className="field full"><label>Your purpose / intention <span className="hint">optional — what to energise it for</span></label><textarea className="input" value={f.intention} onChange={e=>set('intention',e.target.value)} placeholder="e.g. prosperity at work, calm, protection…"/></div>
            </div>
          </div>
          <div className="checkout__summary card">
            <h3 className="h3">Order summary</h3>
            <div className="checkout__items mt4">
              {items.map(x=>(
                <div className="checkout__item" key={x.product.id}>
                  <ProductVisual p={x.product} size={46}/>
                  <span><b>{x.product.name}</b><small>Qty {x.item.qty} · {RR.fmt(x.product.price)}</small></span>
                  <b>{RR.fmt(x.product.price*Number(x.item.qty||1))}</b>
                </div>
              ))}
            </div>
            <div className="quick-coupon mt4">
              <input value={f.coupon} onChange={e=>set('coupon',e.target.value)} placeholder="Coupon code"/>
              {f.coupon.trim() && <span className={couponValid?'quick-coupon__ok':'quick-coupon__no'}>{couponValid?('-'+pct+'%'):'invalid'}</span>}
            </div>
            <div className="checkout__totals mt4">
              <div><span>Subtotal</span><span>{RR.fmt(subtotal)}</span></div>
              {discount>0 && <div className="checkout__disc"><span>Discount ({pct}%)</span><span>-{RR.fmt(discount)}</span></div>}
              <div className="checkout__grand"><span>Total</span><b>{RR.fmt(total)}</b></div>
            </div>
            <button className="btn btn-maroon btn-block btn-lg mt4" disabled={busy} onClick={()=>submit(false)}>{busy?'Placing…':'Place order'}</button>
            <button className="btn btn-wa btn-block mt2" disabled={busy} onClick={()=>submit(true)}><WaGlyph/> Place &amp; confirm on WhatsApp</button>
            <p className="muted mt3" style={{fontSize:12.5}}>We confirm availability, payment and delivery on WhatsApp. Online payment will be enabled soon.</p>
          </div>
        </div>
      </div></section>
      <TrustDisclaimer/>
    </main>
  );
}

/* ---------------- Create your own mix ---------------- */
function CustomMixPage(){
  const { go } = useContext(Nav);
  const [f,setF] = useState({ name:'', phone:'', email:'', intention:'', preferences:'', budget:'' });
  const [busy,setBusy] = useState(false);
  const [doneRef,setDoneRef] = useState(null);
  const set = (k,v)=>setF(s=>({ ...s, [k]:v }));
  const submit = async (viaWa)=>{
    if(!f.name.trim() || !f.phone.trim()){ alert('Please enter your name and phone number.'); return; }
    setBusy(true);
    const r = await rrApiPost('request', { name:f.name.trim(), phone:f.phone.trim(), email:f.email.trim(), intention:f.intention.trim(), preferences:f.preferences.trim(), budget:f.budget.trim() });
    const ref = (r && r.ok) ? r.ref : '';
    setBusy(false);
    setDoneRef(ref || 'received');
    if(viaWa){
      const msg = "Hi Rudraa Ratna, I'd like to create my own mix.\nName: " + f.name.trim()
        + "\nIntention: " + (f.intention.trim()||'-') + "\nPreferences: " + (f.preferences.trim()||'-')
        + "\nBudget: " + (f.budget.trim()||'-');
      window.open(RR.wa(msg), '_blank', 'noopener');
    }
  };
  if(doneRef){
    return (
      <main className="pdp"><section className="section"><div className="wrap"><Reveal className="section-head center">
        <span className="cw__check"><Icon name="check" size={26}/></span>
        <h1 className="h1" style={{ marginTop:10 }}>Request received{doneRef!=='received'?(' — '+doneRef):''}</h1>
        <p>Thank you! Our team will design your custom mix based on your intention and reach out, usually <b>within 3 working days</b>.</p>
        <div className="center mt6"><a className="btn btn-wa btn-lg" href={RR.wa("Hi Rudraa Ratna, I submitted a custom mix request.")} target="_blank" rel="noopener"><WaGlyph/> Continue on WhatsApp</a></div>
      </Reveal></div></section><TrustDisclaimer/></main>
    );
  }
  return (
    <main>
      <Breadcrumb items={[{label:'Home',page:'home'},{label:'Create your own mix'}]}/>
      <section className="section tight"><div className="wrap" style={{ maxWidth:760 }}>
        <Reveal className="section-head"><span className="eyebrow no-rule">Personalised</span><h1 className="h1" style={{marginTop:10}}>Create your own mix</h1>
          <p>Tell us your intention and preferences, and we'll hand-design a personalised crystal mix / bracelet for you, energised with sacred codes and mantras. We usually reply within <b>3 working days</b>.</p>
        </Reveal>
        <div className="card mt8">
          <div className="adm-grid2">
            <div className="field"><label>Full name *</label><input className="input" value={f.name} onChange={e=>set('name',e.target.value)}/></div>
            <div className="field"><label>Phone *</label><input className="input" value={f.phone} onChange={e=>set('phone',e.target.value)} inputMode="tel"/></div>
            <div className="field full"><label>Email</label><input className="input" value={f.email} onChange={e=>set('email',e.target.value)}/></div>
            <div className="field full"><label>Your intention / purpose</label><textarea className="input" value={f.intention} onChange={e=>set('intention',e.target.value)} placeholder="e.g. prosperity, calm, protection, focus…"/></div>
            <div className="field full"><label>Preferences <span className="hint">stones, colours, wrist size, style</span></label><textarea className="input" value={f.preferences} onChange={e=>set('preferences',e.target.value)} placeholder="e.g. amethyst + clear quartz, 8mm, soft tones"/></div>
            <div className="field"><label>Budget</label><input className="input" value={f.budget} onChange={e=>set('budget',e.target.value)} placeholder="e.g. ₹1,000–₹2,000"/></div>
          </div>
          <button className="btn btn-maroon btn-block btn-lg mt4" disabled={busy} onClick={()=>submit(false)}>{busy?'Submitting…':'Submit request'}</button>
          <button className="btn btn-wa btn-block mt2" disabled={busy} onClick={()=>submit(true)}><WaGlyph/> Submit &amp; chat on WhatsApp</button>
        </div>
      </div></section>
      <TrustDisclaimer/>
    </main>
  );
}

/* ---------------- Connect with us ---------------- */
function ConnectPage(){
  const ig = RR.settings.instagram || "https://www.instagram.com/rudraa_ratna";
  const fb = RR.settings.facebook || "";
  return (
    <main>
      <Breadcrumb items={[{label:'Home',page:'home'},{label:'Connect with us'}]}/>
      <section className="section tight"><div className="wrap" style={{ maxWidth:820 }}>
        <Reveal className="section-head center"><span className="eyebrow no-rule">Connect</span><h1 className="h1" style={{marginTop:10}}>Connect with Rudraa Ratna</h1><p>Follow us, message us, and stay updated on new arrivals, guidance and offers.</p></Reveal>
        <div className="connect-grid mt8">
          <a className="connect-card card" href={RR.wa("Hi Rudraa Ratna, I'd like to connect.")} target="_blank" rel="noopener"><span className="connect-card__ic" style={{ color:'var(--wa)' }}><WaGlyph size={26}/></span><b>WhatsApp</b><small>{RR.WA_DISPLAY}</small></a>
          <a className="connect-card card" href={ig} target="_blank" rel="noopener"><span className="connect-card__ic" style={{ color:'#C13584' }}><Icon name="instagram" size={26}/></span><b>Instagram</b><small>@rudraa_ratna</small></a>
          {fb && <a className="connect-card card" href={fb} target="_blank" rel="noopener"><span className="connect-card__ic" style={{ color:'#1877F2' }}><Icon name="facebook" size={26}/></span><b>Facebook</b><small>Rudraa Ratna</small></a>}
          {RR.settings.email && <a className="connect-card card" href={"mailto:"+RR.settings.email}><span className="connect-card__ic"><Icon name="mail" size={26}/></span><b>Email</b><small>{RR.settings.email}</small></a>}
        </div>
      </div></section>
      <ProfessionalHelp/>
      <TrustDisclaimer/>
    </main>
  );
}

/* ---------------- Professional help board ---------------- */
function ProfessionalHelp(){
  return (
    <section className="section tight" style={{ background:'var(--ivory-2)', borderBlock:'1px solid var(--line)' }}>
      <div className="wrap"><div className="help-board card">
        <div className="help-board__copy">
          <span className="eyebrow no-rule">Professional Help</span>
          <h2 className="h2">Need expert guidance?</h2>
          <p>Get founder-led, belief-based guidance on choosing the right crystal, Rudraksha or gemstone for your intention. We help with selection, suitability and care — never with guaranteed results.</p>
        </div>
        <div className="help-board__cta">
          <a className="btn btn-wa btn-lg" href={RR.wa("Hi Rudraa Ratna, I'd like professional guidance.")} target="_blank" rel="noopener"><WaGlyph/> Ask on WhatsApp</a>
          {RR.settings.email && <a className="btn btn-ghost btn-lg" href={"mailto:"+RR.settings.email}><Icon name="mail" size={17}/> {RR.settings.email}</a>}
        </div>
      </div></div>
    </section>
  );
}

Object.assign(window, { rrApiPost, CheckoutPage, CustomMixPage, ConnectPage, ProfessionalHelp });
