/* Checkout & order confirmation */

const UPI_APPS = [
  { id: 'gpay', name: 'GPay', color: '#1A73E8', letter: 'G' },
  { id: 'phonepe', name: 'PhonePe', color: '#5F259F', letter: 'P' },
  { id: 'paytm', name: 'Paytm', color: '#00BAF2', letter: 'P' },
  { id: 'bhim', name: 'BHIM', color: '#FF6E1E', letter: 'B' },
];

const Checkout = ({ open, onClose, items, subtotal, discount, freeShip, total, onPlaceOrder, promoApplied }) => {
  const [form, setForm] = React.useState({
    email: '', phone: '',
    firstName: '', lastName: '',
    address: '', address2: '', city: '', state: '', pincode: '',
    notes: '',
  });
  const [payment, setPayment] = React.useState('upi');
  const [upiApp, setUpiApp] = React.useState('gpay');
  const [upiId, setUpiId] = React.useState('');
  const [errors, setErrors] = React.useState({});
  const [submitting, setSubmitting] = React.useState(false);

  const setField = (k, v) => {
    setForm(f => ({ ...f, [k]: v }));
    if (errors[k]) setErrors(e => ({ ...e, [k]: null }));
  };

  const validate = () => {
    const e = {};
    if (!/^[\w.-]+@[\w-]+\.[a-z.]{2,}$/i.test(form.email)) e.email = 'Enter a valid email';
    if (!/^[6-9]\d{9}$/.test(form.phone.replace(/\D/g, ''))) e.phone = 'Enter a 10-digit mobile';
    if (!form.firstName.trim()) e.firstName = 'Required';
    if (!form.lastName.trim()) e.lastName = 'Required';
    if (!form.address.trim()) e.address = 'Required';
    if (!form.city.trim()) e.city = 'Required';
    if (!form.state.trim()) e.state = 'Required';
    if (!/^\d{6}$/.test(form.pincode)) e.pincode = '6-digit pincode';
    if (payment === 'upi' && upiId && !/^[\w.-]+@[\w-]+$/.test(upiId)) e.upiId = 'Format: name@bank';
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const handlePlace = () => {
    if (!validate()) {
      // scroll to first error
      const first = document.querySelector('.field.error');
      if (first) first.scrollIntoView({ behavior: 'smooth', block: 'center' });
      return;
    }
    setSubmitting(true);
    setTimeout(() => {
      onPlaceOrder({
        ...form,
        payment,
        upiApp,
        upiId,
        items,
        total,
        orderId: 'ORL' + Math.floor(100000 + Math.random() * 900000),
      });
      setSubmitting(false);
    }, 1100);
  };

  const STATES = ['Maharashtra', 'Karnataka', 'Tamil Nadu', 'Delhi', 'Telangana', 'Gujarat', 'West Bengal', 'Uttar Pradesh', 'Rajasthan', 'Kerala', 'Punjab', 'Haryana', 'Madhya Pradesh', 'Other'];

  return (
    <div className={`checkout-screen ${open ? 'open' : ''}`}>
      <div className="checkout-top">
        <button className="back" onClick={onClose}><Icon.ArrowLeft /> Back to cart</button>
        <BrandMark size={22} />
        <div className="secure-tag"><Icon.Shield size={14} /> Secure checkout</div>
      </div>

      <div className="checkout-grid">
        <div className="checkout-form">
          <h2 className="display">Almost yours.</h2>
          <p className="sub">Fill in your details — we'll ship from Delhi within 24 hours.</p>

          <div className="steps-progress">
            <div className="sp-step active"><div className="n">1</div> Contact & shipping</div>
            <div className="sp-line"></div>
            <div className="sp-step active"><div className="n">2</div> Payment</div>
            <div className="sp-line"></div>
            <div className="sp-step"><div className="n">3</div> Confirmation</div>
          </div>

          <div className="form-block">
            <h3><span className="n">1</span> Contact</h3>
            <div className="form-grid">
              <div className={`field full ${errors.email ? 'error' : ''}`}>
                <label>Email address</label>
                <input type="email" placeholder="you@example.com" value={form.email} onChange={e => setField('email', e.target.value)} />
                {errors.email && <span className="err-msg">{errors.email}</span>}
              </div>
              <div className={`field full ${errors.phone ? 'error' : ''}`}>
                <label>Mobile number</label>
                <input type="tel" placeholder="98765 43210" value={form.phone} onChange={e => setField('phone', e.target.value)} />
                {errors.phone && <span className="err-msg">{errors.phone}</span>}
              </div>
            </div>
          </div>

          <div className="form-block">
            <h3><span className="n">2</span> Shipping address</h3>
            <div className="form-grid">
              <div className={`field ${errors.firstName ? 'error' : ''}`}>
                <label>First name</label>
                <input value={form.firstName} onChange={e => setField('firstName', e.target.value)} />
                {errors.firstName && <span className="err-msg">{errors.firstName}</span>}
              </div>
              <div className={`field ${errors.lastName ? 'error' : ''}`}>
                <label>Last name</label>
                <input value={form.lastName} onChange={e => setField('lastName', e.target.value)} />
                {errors.lastName && <span className="err-msg">{errors.lastName}</span>}
              </div>
              <div className={`field full ${errors.address ? 'error' : ''}`}>
                <label>Address</label>
                <input placeholder="House / flat, street" value={form.address} onChange={e => setField('address', e.target.value)} />
                {errors.address && <span className="err-msg">{errors.address}</span>}
              </div>
              <div className="field full">
                <label>Apartment, landmark (optional)</label>
                <input value={form.address2} onChange={e => setField('address2', e.target.value)} />
              </div>
              <div className={`field ${errors.city ? 'error' : ''}`}>
                <label>City</label>
                <input value={form.city} onChange={e => setField('city', e.target.value)} />
                {errors.city && <span className="err-msg">{errors.city}</span>}
              </div>
              <div className={`field ${errors.state ? 'error' : ''}`}>
                <label>State</label>
                <select value={form.state} onChange={e => setField('state', e.target.value)}>
                  <option value="">Select state</option>
                  {STATES.map(s => <option key={s} value={s}>{s}</option>)}
                </select>
                {errors.state && <span className="err-msg">{errors.state}</span>}
              </div>
              <div className={`field full ${errors.pincode ? 'error' : ''}`}>
                <label>Pincode</label>
                <input placeholder="6-digit code" value={form.pincode} onChange={e => setField('pincode', e.target.value.replace(/\D/g, '').slice(0, 6))} />
                {errors.pincode && <span className="err-msg">{errors.pincode}</span>}
              </div>
            </div>
          </div>

          <div className="form-block">
            <h3><span className="n">3</span> Payment</h3>
            <div className="pay-options">
              <div className={`pay-option ${payment === 'upi' ? 'selected' : ''}`} onClick={() => setPayment('upi')}>
                <span className="radio"></span>
                <div className="info">
                  <b>UPI</b>
                  <span>GPay, PhonePe, Paytm, BHIM. Pay instantly.</span>
                </div>
                <div className="pay-logos">
                  <span className="pay-chip">UPI</span>
                </div>
              </div>
              {payment === 'upi' && (
                <div className="upi-detail">
                  <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--brown-700)', marginBottom: 10, letterSpacing: '0.16em', textTransform: 'uppercase' }}>Pay with</div>
                  <div className="upi-grid">
                    {UPI_APPS.map(app => (
                      <div key={app.id} className={`upi-app ${upiApp === app.id ? 'selected' : ''}`} onClick={() => setUpiApp(app.id)}>
                        <div className="upi-logo" style={{ background: app.color }}>{app.letter}</div>
                        <span>{app.name}</span>
                      </div>
                    ))}
                  </div>
                  <div className={`field ${errors.upiId ? 'error' : ''}`}>
                    <label>or enter UPI ID</label>
                    <input placeholder="yourname@okhdfcbank" value={upiId} onChange={e => { setUpiId(e.target.value); if (errors.upiId) setErrors(er => ({ ...er, upiId: null })); }} />
                    {errors.upiId && <span className="err-msg">{errors.upiId}</span>}
                  </div>
                </div>
              )}

              <div className={`pay-option ${payment === 'cod' ? 'selected' : ''}`} onClick={() => setPayment('cod')}>
                <span className="radio"></span>
                <div className="info">
                  <b>Cash on Delivery</b>
                  <span>Pay in cash when your order arrives. ₹49 handling fee.</span>
                </div>
                <Icon.Truck />
              </div>
            </div>
          </div>

          <div className="form-block">
            <h3><span className="n">4</span> Order notes <span style={{ fontFamily: 'var(--font-body)', fontSize: 12, color: 'var(--ink-500)', fontWeight: 500, letterSpacing: 0, textTransform: 'none' }}>(optional)</span></h3>
            <div className="field full">
              <textarea rows="3" placeholder="Anything we should know — gift wrap, building instructions, etc." value={form.notes} onChange={e => setField('notes', e.target.value)}></textarea>
            </div>
          </div>
        </div>

        <aside className="checkout-summary">
          <h3>Your order</h3>
          {items.map(item => (
            <div key={item.packId} className="ci-mini">
              <div className="ci-img">
                <span className="q-badge">{item.qty}</span>
                <img src="assets/product-bottle-box.jpeg" style={{ mixBlendMode: 'multiply' }} alt="" />
              </div>
              <div>
                <h5>{item.name}</h5>
                <span>200ml · sea buckthorn juice</span>
              </div>
              <b>₹{(item.price * item.qty).toLocaleString('en-IN')}</b>
            </div>
          ))}

          <div style={{ paddingTop: 18 }}>
            <div className="sumrow"><span>Subtotal</span><b>₹{subtotal.toLocaleString('en-IN')}</b></div>
            {discount > 0 && <div className="sumrow discount"><span>Discount (ORLINA10)</span><b>−₹{discount.toLocaleString('en-IN')}</b></div>}
            <div className="sumrow"><span>Shipping</span><b>{freeShip ? 'Free' : '₹49'}</b></div>
            {payment === 'cod' && <div className="sumrow"><span>COD handling</span><b>₹49</b></div>}
            <div className="sumrow"><span>GST (incl.)</span><b>included</b></div>
          </div>

          <div className="total">
            <span>Total</span>
            <b>₹{(total + (payment === 'cod' ? 49 : 0)).toLocaleString('en-IN')}</b>
          </div>

          <div className="perks">
            <div className="p"><Icon.Truck size={18} /> Ships within 24 hours from Delhi</div>
            <div className="p"><Icon.Shield size={18} /> 14-day money-back guarantee</div>
            <div className="p"><Icon.Refresh size={18} /> Easy returns · no questions</div>
          </div>

          <button className="btn btn-primary place-order" onClick={handlePlace} disabled={submitting}>
            {submitting ? 'Processing…' : <>Place order · ₹{(total + (payment === 'cod' ? 49 : 0)).toLocaleString('en-IN')} <Icon.Arrow /></>}
          </button>
          <p className="terms">
            By placing your order, you agree to Orlina's Terms of Service and Privacy Policy. Your payment is protected.
          </p>
        </aside>
      </div>
    </div>
  );
};

const Confirmation = ({ order, onContinue }) => {
  if (!order) return null;
  const eta = new Date(Date.now() + 4 * 24 * 60 * 60 * 1000);
  const etaStr = eta.toLocaleDateString('en-IN', { day: 'numeric', month: 'short' });
  return (
    <div className="checkout-screen open" style={{ background: 'var(--cream-50)' }}>
      <div className="checkout-top">
        <BrandMark size={22} />
        <div className="secure-tag" style={{ color: 'var(--leaf-600)' }}><Icon.Check size={14} /> Order confirmed</div>
      </div>
      <div className="confirm-screen">
        <div className="confirm-ic">
          <Icon.Check size={48} />
        </div>
        <h1 className="display">Thank you, <em>{order.firstName || 'friend'}.</em></h1>
        <p className="lead">
          Your order is in. We've sent a confirmation to <b>{order.email}</b> — your golden ritual will arrive in 2–5 days, dispatched from Delhi within 24 hours.
        </p>

        <div className="confirm-card">
          <div className="order-meta">
            <div className="m"><span>Order</span><b>#{order.orderId}</b></div>
            <div className="m"><span>Total paid</span><b>₹{(order.total + (order.payment === 'cod' ? 49 : 0)).toLocaleString('en-IN')}</b></div>
            <div className="m"><span>Arriving by</span><b>{etaStr}</b></div>
          </div>

          <div className="timeline">
            <div className="tl-step done"><div className="dot"><Icon.Check size={14} /></div>Placed</div>
            <div className="tl-step active"><div className="dot">2</div>Packed</div>
            <div className="tl-step"><div className="dot">3</div>Shipped</div>
            <div className="tl-step"><div className="dot">4</div>Delivered</div>
          </div>

          <div style={{ borderTop: '1px solid rgba(120,60,20,0.1)', paddingTop: 22, marginTop: 22 }}>
            <h4 style={{ fontFamily: 'var(--font-display)', fontSize: 18, fontWeight: 500, margin: '0 0 12px' }}>Shipping to</h4>
            <p style={{ margin: 0, color: 'var(--brown-700)', fontSize: 14, lineHeight: 1.6 }}>
              {order.firstName} {order.lastName}<br />
              {order.address}{order.address2 ? `, ${order.address2}` : ''}<br />
              {order.city}, {order.state} · {order.pincode}<br />
              <span style={{ color: 'var(--ink-500)' }}>{order.phone} · {order.email}</span>
            </p>
            <h4 style={{ fontFamily: 'var(--font-display)', fontSize: 18, fontWeight: 500, margin: '24px 0 12px' }}>Payment</h4>
            <p style={{ margin: 0, color: 'var(--brown-700)', fontSize: 14 }}>
              {order.payment === 'upi' ? `UPI · ${order.upiApp.toUpperCase()}${order.upiId ? ` · ${order.upiId}` : ''}` : 'Cash on Delivery'}
            </p>
          </div>
        </div>

        <div className="confirm-actions">
          <button className="btn btn-primary" onClick={onContinue}>Continue shopping <Icon.Arrow /></button>
          <button className="btn btn-ghost">Track order</button>
        </div>

        <p style={{ marginTop: 40, fontSize: 13, color: 'var(--brown-700)' }}>
          A small ritual, repeated daily, becomes a transformation. — Welcome to Orlina.
        </p>
      </div>
    </div>
  );
};

Object.assign(window, { Checkout, Confirmation });
