// ===== Shared page wrapper =====
// Hosts announcement, header, mega-nav, footer, cart drawer, product modal, toast.
// Pages render their content inside <PageWrapper>...</PageWrapper>.

const { useState: useWS, useEffect: useWE } = React;

const useCart = () => {
  const [cart, setCart] = useWS(() => {
    try { return JSON.parse(localStorage.getItem("store_cart")) || []; } catch { return []; }
  });
  useWE(() => { localStorage.setItem("store_cart", JSON.stringify(cart)); }, [cart]);
  return [cart, setCart];
};

const useFaves = () => {
  const [faves, setFaves] = useWS(() => {
    try { return new Set(JSON.parse(localStorage.getItem("store_faves")) || []); } catch { return new Set(); }
  });
  useWE(() => { localStorage.setItem("store_faves", JSON.stringify([...faves])); }, [faves]);
  return [faves, setFaves];
};

// ---------- Cart Drawer ----------
const CartDrawer = ({ open, onClose, items, onQty, onRemove, onCheckout }) => {
  const subtotal = items.reduce((s, it) => s + it.p.price * it.qty, 0);
  const shipping = subtotal > 50000 || items.length === 0 ? 0 : 1200;
  const total = subtotal + shipping;
  return (
    <>
      <div className={`drawer-overlay ${open ? "open" : ""}`} onClick={onClose}></div>
      <aside className={`drawer ${open ? "open" : ""}`}>
        <div className="drawer-head">
          <h3>
            <Icon name="cart" style={{ width: 20, height: 20 }} />
            Your cart
            <span className="count">{items.length} item{items.length === 1 ? "" : "s"}</span>
          </h3>
          <button className="drawer-close" onClick={onClose}><Icon name="close" /></button>
        </div>
        <div className="drawer-body">
          {items.length === 0 ? (
            <div className="cart-empty">
              <div className="ico"><Icon name="cart" style={{ width: 64, height: 64 }} /></div>
              <h4>Your cart is empty</h4>
              <p>Browse the deals — flash drops end tonight.</p>
            </div>
          ) : (
            items.map(it => (
              <div className="cart-row" key={it.p.id}>
                <div className="cart-thumb" style={it.p.img ? { backgroundImage: `url(${it.p.img})`, backgroundSize: "cover", backgroundPosition: "center" } : {}}></div>
                <div className="cart-info">
                  <div className="br">{it.p.brand}</div>
                  <div className="nm">{it.p.name}</div>
                  <div className="pr">{money(it.p.price * it.qty)} <span style={{ fontSize: 11, color: "var(--ink-mute)", fontFamily: "JetBrains Mono" }}>DZD</span></div>
                  <div className="qty-row">
                    <button className="qty-btn" onClick={() => onQty(it.p.id, it.qty - 1)}><Icon name="minus" style={{ width: 12, height: 12 }} /></button>
                    <span className="qty-val">{it.qty}</span>
                    <button className="qty-btn" onClick={() => onQty(it.p.id, it.qty + 1)}><Icon name="plus" style={{ width: 12, height: 12 }} /></button>
                  </div>
                </div>
                <button className="rm" onClick={() => onRemove(it.p.id)}><Icon name="close" /></button>
              </div>
            ))
          )}
        </div>
        {items.length > 0 && (
          <div className="drawer-foot">
            <div className="summary-row"><span>Subtotal</span><span>{money(subtotal)} DZD</span></div>
            <div className="summary-row"><span>Shipping</span><span>{shipping === 0 ? "Free" : `${money(shipping)} DZD`}</span></div>
            <div className="summary-row"><span>VAT (incl.)</span><span>{money(Math.round(total * 0.19))} DZD</span></div>
            <div className="summary-row total"><span>Total</span><span>{money(total)} DZD</span></div>
            <button className="checkout-btn" onClick={onCheckout}>
              Checkout securely <Icon name="arrow" />
            </button>
            <div style={{ textAlign: "center", marginTop: 10, fontSize: 11, color: "var(--ink-mute)" }}>
              Pay in 3 interest-free installments available at checkout
            </div>
          </div>
        )}
      </aside>
    </>
  );
};

// ---------- Product Modal ----------
const ProductModal = ({ p, onClose, onAdd }) => {
  const [qty, setQty] = useWS(1);
  const [thumb, setThumb] = useWS(0);
  useWE(() => { setQty(1); setThumb(0); }, [p?.id]);
  if (!p) return null;
  const discount = p.was ? Math.round((1 - p.price / p.was) * 100) : 0;
  return (
    <div className={`modal-overlay open`} onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <div className="modal-media">
          <div className="product-badges" style={{ position: "static", marginBottom: 4 }}>
            {p.badges.map((b, i) => {
              const cls = b.includes("%") ? "sale" : b === "NEW" ? "new" : "hot";
              return <span key={i} className={`badge ${cls}`}>{b}</span>;
            })}
          </div>
          <div className="modal-media-main">
            {p.img ? (
              <img src={p.img} alt={p.name} className="modal-img" />
            ) : (
              <PHLabel>{p.cat.toLowerCase()}.hero.render</PHLabel>
            )}
          </div>
          <div className="modal-thumbs">
            {[0,1,2,3].map(i => (
              <div key={i}
                className={`modal-thumb ${i === thumb ? "active" : ""}`}
                style={p.img ? { backgroundImage: `url(${p.img})`, backgroundSize: "cover", backgroundPosition: "center" } : {}}
                onClick={() => setThumb(i)}></div>
            ))}
          </div>
        </div>
        <div className="modal-body">
          <button className="modal-close" onClick={onClose}><Icon name="close" /></button>
          <div className="brand">{p.brand} · SKU APT-{1000 + p.id}</div>
          <h2>{p.name}</h2>
          <div className="modal-rate">
            <Stars value={p.rating} />
            <span>{p.rating.toFixed(1)} ({p.reviews} reviews)</span>
            <span className="dot"></span>
            <span className="in-stock">In stock — {p.stock} left</span>
          </div>
          <div className="modal-price">
            <span className="now">{money(p.price)} <span style={{ fontSize: 14, color: "var(--ink-mute)", fontWeight: 500 }}>DZD</span></span>
            {p.was && <span className="was">{money(p.was)} DZD</span>}
            {p.was && <span className="save-pill">-{discount}%</span>}
          </div>
          <div className="vat">VAT included · Ships in 24h from Algiers warehouse</div>

          <div className="modal-specs">
            {p.specs.map((s, i) => {
              const labels = ["Chipset", "Memory", "Speed", "Form factor"];
              return (
                <div className="modal-spec" key={i}>
                  <div className="k">{labels[i] || "Spec"}</div>
                  <div className="v">{s}</div>
                </div>
              );
            })}
            <div className="modal-spec">
              <div className="k">Warranty</div>
              <div className="v">2 years</div>
            </div>
            <div className="modal-spec">
              <div className="k">Ships from</div>
              <div className="v">Algiers, DZ</div>
            </div>
          </div>

          <div className="qty-pick">
            <label>Quantity</label>
            <div className="qty-stepper">
              <button onClick={() => setQty(Math.max(1, qty - 1))}>−</button>
              <span className="v">{qty}</span>
              <button onClick={() => setQty(qty + 1)}>+</button>
            </div>
          </div>

          <div className="modal-cta">
            <button className="btn btn-primary" onClick={() => { onAdd(p, qty); onClose(); }}>
              <Icon name="cart" /> Add to cart · {money(p.price * qty)} DZD
            </button>
            <a className="btn btn-ghost" href={`product.html?id=${p.id}`}>
              <Icon name="arrow" /> Full details
            </a>
          </div>

          <div className="modal-extras">
            <div><Icon name="truck" /> Free delivery on 50K+</div>
            <div><Icon name="shield" /> 2-year warranty</div>
            <div><Icon name="refresh" /> 14-day returns</div>
            <div><Icon name="check" /> Compatibility-verified</div>
          </div>
        </div>
      </div>
    </div>
  );
};

const Toast = ({ msg, show }) => (
  <div className={`toast ${show ? "show" : ""}`}>
    <Icon name="check" /> {msg}
  </div>
);

// ---------- Algerian Checkout Modal ----------
const WILAYAS = [
  ["16","Alger",400], ["31","Oran",600], ["25","Constantine",600], ["19","Sétif",500],
  ["09","Blida",450], ["35","Boumerdès",450], ["06","Béjaïa",550], ["23","Annaba",650],
  ["15","Tizi Ouzou",500], ["05","Batna",650], ["02","Chlef",550], ["27","Mostaganem",650],
  ["13","Tlemcen",700], ["22","Sidi Bel Abbès",700], ["44","Aïn Defla",500], ["42","Tipaza",450],
  ["10","Bouira",500], ["26","Médéa",500], ["38","Tissemsilt",600], ["48","Relizane",600],
  ["29","Mascara",650], ["46","Aïn Témouchent",700], ["20","Saïda",700], ["14","Tiaret",650],
  ["17","Djelfa",750], ["28","M'Sila",700], ["34","Bordj Bou Arréridj",550], ["18","Jijel",600],
  ["21","Skikda",650], ["43","Mila",600], ["24","Guelma",700], ["36","El Tarf",750],
  ["41","Souk Ahras",700], ["04","Oum El Bouaghi",700], ["12","Tébessa",800], ["40","Khenchela",750],
  ["07","Biskra",800], ["39","El Oued",900], ["30","Ouargla",1000], ["32","El Bayadh",900],
  ["45","Naâma",900], ["08","Béchar",1100], ["37","Tindouf",1300], ["11","Tamanrasset",1500],
  ["33","Illizi",1500], ["47","Ghardaïa",1000], ["01","Adrar",1200], ["03","Laghouat",800],
];

const CheckoutModal = ({ open, items, onClose, onConfirm }) => {
  const [step, setStep] = useWS(1);
  const [form, setForm] = useWS({
    name: "", phone: "", wilaya: "16", commune: "", address: "",
    delivery: "home", notes: "", payment: "cod",
  });
  const [submitting, setSubmitting] = useWS(false);
  const [orderId, setOrderId] = useWS(null);

  useWE(() => {
    if (open) { setStep(1); setOrderId(null); }
  }, [open]);

  const wilayaInfo = WILAYAS.find(w => w[0] === form.wilaya) || WILAYAS[0];
  const homeFee = wilayaInfo[2];
  const stopdeskFee = Math.round(homeFee * 0.6);
  const deliveryFee = form.delivery === "home" ? homeFee : stopdeskFee;
  const subtotal = items.reduce((s, it) => s + it.p.price * it.qty, 0);
  const total = subtotal + deliveryFee;

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

  const phoneOk = /^0(5|6|7)\d{8}$/.test(form.phone.replace(/\s/g, ""));
  const canContinue =
    (step === 1) ||
    (step === 2 && form.name.trim().length >= 3 && phoneOk && form.address.trim().length >= 5);

  const submit = () => {
    setSubmitting(true);
    setTimeout(() => {
      setSubmitting(false);
      const id = "APT-" + Math.floor(100000 + Math.random() * 900000);
      setOrderId(id);
      setStep(3);
      onConfirm && onConfirm();
    }, 1100);
  };

  if (!open) return null;
  return (
    <div className="modal-overlay open" onClick={onClose}>
      <div className="checkout-modal" onClick={(e) => e.stopPropagation()}>
        <header className="ck-head">
          <div>
            <div className="ck-eyebrow">Secure checkout · Paiement à la livraison</div>
            <h2>{step === 3 ? "Order confirmed" : "Finalize your order"}</h2>
          </div>
          <button className="modal-close" onClick={onClose}><Icon name="close" /></button>
        </header>

        {step !== 3 && (
          <div className="ck-stepbar">
            <div className={`ck-step ${step >= 1 ? "active" : ""}`}>
              <span className="n">1</span> Review
            </div>
            <div className="ck-step-bar"></div>
            <div className={`ck-step ${step >= 2 ? "active" : ""}`}>
              <span className="n">2</span> Delivery & contact
            </div>
            <div className="ck-step-bar"></div>
            <div className={`ck-step ${step >= 3 ? "active" : ""}`}>
              <span className="n">3</span> Confirmation
            </div>
          </div>
        )}

        <div className="ck-body">
          {step === 1 && (
            <div className="ck-pane">
              <h3>Order items ({items.reduce((s, i) => s + i.qty, 0)})</h3>
              <div className="ck-items">
                {items.map(it => (
                  <div className="ck-item" key={it.p.id}>
                    <div className="ck-item-thumb" style={it.p.img ? { backgroundImage: `url(${it.p.img})` } : {}}></div>
                    <div className="ck-item-info">
                      <div className="br">{it.p.brand}</div>
                      <div className="nm">{it.p.name}</div>
                      <div className="qty">Qty: {it.qty} × {money(it.p.price)} DZD</div>
                    </div>
                    <div className="ck-item-price">{money(it.p.price * it.qty)} DZD</div>
                  </div>
                ))}
              </div>
              <div className="ck-promo">
                <input placeholder="Promo code (e.g. WELCOME5)" />
                <button className="btn btn-ghost">Apply</button>
              </div>
            </div>
          )}

          {step === 2 && (
            <div className="ck-pane">
              <h3>Contact</h3>
              <div className="ck-grid">
                <label className="ck-field">
                  <span>Full name *</span>
                  <input value={form.name} onChange={(e) => set("name", e.target.value)} placeholder="Yacine Benkhelifa" />
                </label>
                <label className="ck-field">
                  <span>Phone (Algerian mobile) *</span>
                  <div className="phone-wrap">
                    <span className="phone-flag">🇩🇿 +213</span>
                    <input
                      value={form.phone}
                      onChange={(e) => set("phone", e.target.value)}
                      placeholder="0560 11 02 30"
                      inputMode="tel"
                      className={form.phone && !phoneOk ? "err" : ""}
                    />
                  </div>
                  {form.phone && !phoneOk && (
                    <span className="ck-err">Enter a valid mobile number (05/06/07…)</span>
                  )}
                </label>
              </div>

              <h3>Delivery</h3>
              <div className="ck-delivery">
                <label className={`ck-radio-card ${form.delivery === "home" ? "active" : ""}`}>
                  <input type="radio" name="delivery" checked={form.delivery === "home"} onChange={() => set("delivery", "home")} />
                  <div className="rc-head">
                    <div>
                      <div className="t">Home delivery</div>
                      <div className="s">Yalidine, Noest or our Express to your door</div>
                    </div>
                    <div className="rc-price">{money(homeFee)} DZD</div>
                  </div>
                </label>
                <label className={`ck-radio-card ${form.delivery === "stopdesk" ? "active" : ""}`}>
                  <input type="radio" name="delivery" checked={form.delivery === "stopdesk"} onChange={() => set("delivery", "stopdesk")} />
                  <div className="rc-head">
                    <div>
                      <div className="t">Stop-desk</div>
                      <div className="s">Pick up at the nearest Yalidine / Noest bureau</div>
                    </div>
                    <div className="rc-price">{money(stopdeskFee)} DZD</div>
                  </div>
                </label>
              </div>

              <div className="ck-grid">
                <label className="ck-field">
                  <span>Wilaya *</span>
                  <select value={form.wilaya} onChange={(e) => set("wilaya", e.target.value)}>
                    {WILAYAS.map(w => (
                      <option key={w[0]} value={w[0]}>{w[0]} — {w[1]}</option>
                    ))}
                  </select>
                </label>
                <label className="ck-field">
                  <span>Commune / Daïra</span>
                  <input value={form.commune} onChange={(e) => set("commune", e.target.value)} placeholder="Hydra, Bab El Oued, Belouizdad…" />
                </label>
              </div>

              <label className="ck-field">
                <span>{form.delivery === "home" ? "Detailed address *" : "Preferred bureau (optional)"}</span>
                <textarea
                  value={form.address}
                  onChange={(e) => set("address", e.target.value)}
                  rows="2"
                  placeholder={form.delivery === "home" ? "Rue, immeuble, étage, point de repère…" : "Bureau Yalidine de la cité…"}
                ></textarea>
              </label>

              <h3>Payment</h3>
              <div className="ck-delivery">
                <label className={`ck-radio-card ${form.payment === "cod" ? "active" : ""}`}>
                  <input type="radio" name="payment" checked={form.payment === "cod"} onChange={() => set("payment", "cod")} />
                  <div className="rc-head">
                    <div>
                      <div className="t">Cash on Delivery — Paiement à la livraison</div>
                      <div className="s">Pay the courier in cash when your order arrives</div>
                    </div>
                    <div style={{ display: "flex", gap: 6, alignItems: "center" }}>
                      <span className="pay-chip">CASH</span>
                    </div>
                  </div>
                </label>
                <label className={`ck-radio-card ${form.payment === "cib" ? "active" : ""}`}>
                  <input type="radio" name="payment" checked={form.payment === "cib"} onChange={() => set("payment", "cib")} />
                  <div className="rc-head">
                    <div>
                      <div className="t">Online card payment</div>
                      <div className="s">Pay now via CIB or Edahabia (secure SATIM gateway)</div>
                    </div>
                    <div style={{ display: "flex", gap: 6, alignItems: "center" }}>
                      <span className="pay-chip">CIB</span>
                      <span className="pay-chip">EDAHABIA</span>
                    </div>
                  </div>
                </label>
              </div>

              <label className="ck-field">
                <span>Notes (optional)</span>
                <textarea
                  value={form.notes}
                  onChange={(e) => set("notes", e.target.value)}
                  rows="2"
                  placeholder="Call before delivery, leave at reception, etc."
                ></textarea>
              </label>
            </div>
          )}

          {step === 3 && (
            <div className="ck-pane ck-confirm">
              <div className="confirm-tick"><Icon name="check" /></div>
              <h3>Thank you, {form.name.split(" ")[0]}!</h3>
              <p>
                Your order <strong>{orderId}</strong> has been placed.
                We'll call <strong>+213 {form.phone}</strong> within 2 hours to confirm,
                then dispatch to <strong>{wilayaInfo[1]}</strong> for delivery in <strong>2–4 working days</strong>.
              </p>
              <div className="confirm-card">
                <div className="confirm-row">
                  <span>Order total</span>
                  <strong>{money(total)} DZD</strong>
                </div>
                <div className="confirm-row">
                  <span>Payment</span>
                  <strong>{form.payment === "cod" ? "Cash on delivery" : "Online (CIB / Edahabia)"}</strong>
                </div>
                <div className="confirm-row">
                  <span>Delivery</span>
                  <strong>{form.delivery === "home" ? "Home delivery" : "Stop-desk pickup"}</strong>
                </div>
              </div>
              <div className="confirm-cta">
                <a className="btn btn-ghost" href="index.html">Back to shop</a>
                <button className="btn btn-primary" onClick={onClose}>Track my order</button>
              </div>
            </div>
          )}
        </div>

        {step !== 3 && (
          <footer className="ck-foot">
            <div className="ck-summary">
              <div className="row"><span>Subtotal</span><span>{money(subtotal)} DZD</span></div>
              <div className="row"><span>Delivery ({wilayaInfo[1]})</span><span>{money(deliveryFee)} DZD</span></div>
              <div className="row total"><span>Total to pay</span><span>{money(total)} DZD</span></div>
            </div>
            <div className="ck-actions">
              {step > 1 && (
                <button className="btn btn-ghost" onClick={() => setStep(step - 1)}>← Back</button>
              )}
              {step === 1 && (
                <button className="btn btn-primary" onClick={() => setStep(2)}>
                  Continue to delivery <Icon name="arrow" />
                </button>
              )}
              {step === 2 && (
                <button
                  className="btn btn-primary"
                  disabled={!canContinue || submitting}
                  onClick={submit}
                  style={!canContinue || submitting ? { opacity: 0.5, cursor: "not-allowed" } : {}}
                >
                  {submitting ? "Placing order…" : <>Confirm order · {money(total)} DZD</>}
                </button>
              )}
            </div>
          </footer>
        )}
      </div>
    </div>
  );
};

window.CheckoutModal = CheckoutModal;

const PageWrapper = ({ children, query, setQuery }) => {
  const [cart, setCart] = useCart();
  const [faves, setFaves] = useFaves();
  const [drawer, setDrawer] = useWS(false);
  const [modal, setModal] = useWS(null);
  const [toast, setToast] = useWS({ msg: "", show: false });
  const [internalQ, setInternalQ] = useWS("");
  const [checkout, setCheckout] = useWS(null); // null or { items, source }
  const q = query ?? internalQ;
  const setQ = setQuery ?? setInternalQ;

  const showToast = (msg) => {
    setToast({ msg, show: true });
    setTimeout(() => setToast({ msg: "", show: false }), 2200);
  };
  const addToCart = (p, qty = 1) => {
    setCart(prev => {
      const found = prev.find(it => it.p.id === p.id);
      if (found) return prev.map(it => it.p.id === p.id ? { ...it, qty: it.qty + qty } : it);
      return [...prev, { p, qty }];
    });
    showToast(`${p.name.split(" ").slice(0, 4).join(" ")} added to cart`);
  };
  const setQty = (id, qty) => {
    if (qty < 1) return removeFromCart(id);
    setCart(prev => prev.map(it => it.p.id === id ? { ...it, qty } : it));
  };
  const removeFromCart = (id) => setCart(prev => prev.filter(it => it.p.id !== id));
  const toggleFav = (id) => setFaves(prev => {
    const next = new Set(prev);
    next.has(id) ? next.delete(id) : next.add(id);
    return next;
  });

  const openCheckout = (items, source = "buynow") => {
    if (!items || items.length === 0) return;
    setCheckout({ items, source });
    setDrawer(false);
    setModal(null);
  };
  const onCheckoutConfirm = () => {
    if (checkout?.source === "cart") setCart([]);
  };

  useWE(() => {
    const onKey = (e) => { if (e.key === "Escape") { setDrawer(false); setModal(null); setCheckout(null); } };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, []);

  const cartCount = cart.reduce((s, it) => s + it.qty, 0);
  const ctx = { addToCart, openModal: setModal, faves, toggleFav, openCheckout, cart };

  return (
    <div>
      <AnnounceBar />
      <Header
        cartCount={cartCount}
        onCartOpen={() => setDrawer(true)}
        query={q}
        setQuery={setQ}
      />
      <MegaNav />
      {typeof children === "function" ? children(ctx) : children}

      <CartDrawer
        open={drawer}
        onClose={() => setDrawer(false)}
        items={cart}
        onQty={setQty}
        onRemove={removeFromCart}
        onCheckout={() => openCheckout(cart, "cart")}
      />
      {modal && (
        <ProductModal
          p={modal}
          onClose={() => setModal(null)}
          onAdd={addToCart}
        />
      )}
      <CheckoutModal
        open={!!checkout}
        items={checkout?.items || []}
        onClose={() => setCheckout(null)}
        onConfirm={onCheckoutConfirm}
      />
      <Toast msg={toast.msg} show={toast.show} />
    </div>
  );
};

window.PageWrapper = PageWrapper;
window.CartDrawer = CartDrawer;
window.ProductModal = ProductModal;
window.Toast = Toast;
