/* Rass Jerseys - Cart drawer + WhatsApp order prompt */

function CartItem({ item, onUpdate, onRemove }) {
  const p = RassData.productById(item.productId);
  if (!p) return null;
  const t = RassData.teamById(p.team);
  const names = Array.isArray(item.customNames) ? item.customNames : [];
  const setQty = (qty) => { if (qty < 1) return; onUpdate(item.id, { qty, customNames: names.length > 0 ? RassData.resizeNames(names, qty) : [] }); };
  const setSize = (size) => onUpdate(item.id, { size });
  const setWantsName = (on) => onUpdate(item.id, { customNames: on ? RassData.resizeNames(names, item.qty) : [] });
  const setNameAt = (index, value) => {
    const copy = RassData.resizeNames(names, item.qty);
    copy[index] = value;
    onUpdate(item.id, { customNames: copy });
  };
  const hasCustomName = names.length > 0;
  const namingFee = RassData.namingFee(names);

  return (
    <div className="cart-item">
      <JerseyPlaceholder product={p} ratio="1/1" style={{ width: 72, height: 72, borderRadius: 10, flex: "none" }} />
      <div className="cart-item-body">
        <div className="cart-item-meta">
          <span className="cart-item-name">{t.name} <span className="muted">· {p.type}</span></span>
          <span className="price cart-item-price">{RassData.taka(p.price * item.qty + namingFee)}</span>
        </div>
        {hasCustomName && (
          <div style={{ fontSize: 11, color: "var(--muted)", marginTop: -6, marginBottom: 4 }}>
            +TK 100 × {names.length} naming fee included
          </div>
        )}

        <div className="cart-row-label">
          <span className="cart-label">Size</span>
          <div className="cart-size-row">
            {RassData.ALL_SIZES.map((s) => {
              const avail = Number(p.inventory[s] || 0) > 0;
              return (
                <button key={s} className="size-toggle"
                  style={{ width: 36, height: 36, fontSize: 11, borderRadius: 8 }}
                  data-active={item.size === s ? "1" : undefined}
                  disabled={!avail}
                  onClick={() => avail && setSize(s)}>{s}</button>
              );
            })}
          </div>
        </div>

        <div className="cart-row-label">
          <span className="cart-label">Name on jersey</span>
          <div className="name-choice" role="group" aria-label="Name on jersey">
            <button type="button" data-active={!hasCustomName ? "1" : undefined} onClick={() => setWantsName(false)}>No</button>
            <button type="button" data-active={hasCustomName ? "1" : undefined} onClick={() => setWantsName(true)}>Yes</button>
          </div>
          {hasCustomName && (
            <div className="name-input-list" style={{ marginTop: 6 }}>
              {RassData.resizeNames(names, item.qty).map((value, i) => (
                <div key={i} className="name-input-row">
                  {item.qty > 1 && <span className="name-input-label">Jersey {i + 1}</span>}
                  <input className="cart-name-input" placeholder="e.g. MESSI #10"
                    value={value} onChange={(e) => setNameAt(i, e.target.value)} maxLength={22} />
                </div>
              ))}
            </div>
          )}
        </div>

        <div className="cart-item-foot">
          <div className="cart-qty">
            <button className="qty-btn" onClick={() => setQty(item.qty - 1)} disabled={item.qty <= 1}>-</button>
            <span className="qty-val">{item.qty}</span>
            <button className="qty-btn" onClick={() => setQty(item.qty + 1)}>+</button>
          </div>
          <button className="cart-remove-btn" onClick={() => onRemove(item.id)}>
            <Icon name="trash" size={14} /> Remove
          </button>
        </div>
      </div>
    </div>
  );
}

function CartDrawer({ cart, onUpdate, onRemove, onClose, onCheckout }) {
  const subtotal = cart.reduce((sum, item) => {
    const p = RassData.productById(item.productId);
    if (!p) return sum;
    const namingFee = RassData.namingFee(item.customNames);
    return sum + p.price * item.qty + namingFee;
  }, 0);
  const count = cart.reduce((sum, item) => sum + item.qty, 0);
  const deliveryCharge = 26;
  const total = subtotal + deliveryCharge;

  return (
    <div className="cart-overlay" onClick={onClose}>
      <div className="cart-drawer" onClick={(e) => e.stopPropagation()}>
        <div className="cart-head">
          <div>
            <h2 className="cart-title">Your Cart</h2>
            {cart.length > 0 && <span className="muted" style={{ fontSize: 13 }}>{count} item{count !== 1 ? "s" : ""}</span>}
          </div>
          <button className="icon-btn" onClick={onClose}><Icon name="close" size={18} /></button>
        </div>

        {cart.length === 0 ? (
          <div className="cart-empty">
            <div className="cart-empty-icon"><Icon name="bag" size={36} /></div>
            <p style={{ fontFamily: "var(--f-head)", fontWeight: 700, fontSize: 17, margin: "0 0 6px" }}>Your cart is empty</p>
            <p className="muted" style={{ fontSize: 14, margin: 0 }}>Add a jersey to get started.</p>
            <button className="btn btn-primary" style={{ marginTop: 20 }} onClick={onClose}>Browse Jerseys</button>
          </div>
        ) : (
          <React.Fragment>
            <div className="cart-items">
              {cart.map((item) => <CartItem key={item.id} item={item} onUpdate={onUpdate} onRemove={onRemove} />)}
            </div>
            <div className="cart-foot">
              <div className="cart-total-row" style={{ marginBottom: 4 }}>
                <span className="muted" style={{ fontSize: 13 }}>Subtotal</span>
                <span className="price" style={{ fontSize: 15 }}>{RassData.taka(subtotal)}</span>
              </div>
              <div className="cart-total-row" style={{ marginBottom: 10 }}>
                <span className="muted" style={{ fontSize: 13 }}>Delivery (flat TK 26)</span>
                <span className="price" style={{ fontSize: 15 }}>{RassData.taka(deliveryCharge)}</span>
              </div>
              <div className="cart-total-row">
                <span style={{ fontFamily: "var(--f-head)", fontWeight: 700 }}>Order total</span>
                <span className="price" style={{ fontSize: 24 }}>{RassData.taka(total)}</span>
              </div>
              <p className="muted" style={{ fontSize: 13, margin: "0 0 14px" }}>No payment gateway. We will prepare a WhatsApp order draft for you.</p>
              <button className="btn btn-wa btn-block cart-checkout-btn" onClick={onCheckout}>
                <WaIcon size={18} /> Review and Send Order
              </button>
            </div>
          </React.Fragment>
        )}
      </div>
    </div>
  );
}

function OrderPromptModal({ cart, onClose }) {
  const [customerName, setCustomerName] = React.useState("");
  const [phone, setPhone] = React.useState("");
  const [city, setCity] = React.useState("");
  const [address, setAddress] = React.useState("");
  const [whatsappNumber, setWhatsappNumber] = React.useState(RassData.STORE.whatsappNumbers[0] || "");
  const [copied, setCopied] = React.useState(false);
  const [busy, setBusy] = React.useState(false);
  const [error, setError] = React.useState("");
  const [draft, setDraft] = React.useState(null);

  const submit = async () => {
    setBusy(true);
    setError("");
    const normalizedPhone = phone.replace(/[^\d]/g, "").replace(/^0+/, "");
    try {
      const result = await RassApi.createDraftOrder({
        customerName,
        phone: normalizedPhone ? "+880 " + normalizedPhone : "",
        city,
        address,
        whatsappNumber,
        items: cart.map((item) => ({
          productId: item.productId,
          size: item.size,
          qty: item.qty,
          customNames: item.customNames || [],
        })),
      });
      setDraft(result);
    } catch (err) {
      setError(err.message || "Could not prepare order.");
    } finally {
      setBusy(false);
    }
  };

  const copy = async () => {
    if (!draft) return;
    try {
      await navigator.clipboard.writeText(draft.messageText);
    } catch {
      const ta = document.createElement("textarea");
      ta.value = draft.messageText;
      document.body.appendChild(ta);
      ta.select();
      document.execCommand("copy");
      document.body.removeChild(ta);
    }
    setCopied(true);
    setTimeout(() => setCopied(false), 2600);
  };

  return (
    <div className="prompt-overlay" onClick={onClose}>
      <div className="prompt-modal" onClick={(e) => e.stopPropagation()}>
        <div className="prompt-head">
          <div>
            <h3 className="prompt-title">{draft ? "Send your draft to the seller" : "Checkout details"}</h3>
            <p className="prompt-sub muted">
              {draft ? "Last step! Copy your draft, then tap below to open the seller's WhatsApp chat and send it." : "Enter your delivery details and choose a sales number."}
            </p>
          </div>
          <button className="icon-btn" onClick={onClose}><Icon name="close" size={18} /></button>
        </div>

        <div className="prompt-body">
          {!draft ? (
            <div className="checkout-card">
              <div className="prompt-wa-hint">
                <WaIcon size={15} style={{ color: "var(--wa)" }} />
                <span>We will save a local draft order first, then send you to WhatsApp.</span>
              </div>
              <div className="checkout-grid">
                <label className="checkout-field">
                  <span>Name</span>
                <input value={customerName} onChange={(e) => setCustomerName(e.target.value)} placeholder="Your name" />
                </label>
                <label className="checkout-field">
                  <span>Phone</span>
                  <div className="phone-prefix-field">
                    <span>+880</span>
                    <input value={phone} onChange={(e) => setPhone(e.target.value)} placeholder="1XXXXXXXXX" inputMode="numeric" />
                  </div>
                </label>
                <label className="checkout-field">
                  <span>City</span>
                <input value={city} onChange={(e) => setCity(e.target.value)} placeholder="Dhaka" />
                </label>
                <label className="checkout-field checkout-field-wide">
                  <span>Delivery address</span>
                <textarea rows={3} value={address} onChange={(e) => setAddress(e.target.value)} placeholder="House, area, landmark" />
                </label>
                <label className="checkout-field checkout-field-wide">
                  <span>WhatsApp sales number</span>
                <select value={whatsappNumber} onChange={(e) => setWhatsappNumber(e.target.value)}>
                  {RassData.STORE.whatsappNumbers.map((number) => <option key={number} value={number}>{number}</option>)}
                </select>
                </label>
              </div>
              {error && <p className="auth-err" style={{ margin: 0 }}>{error}</p>}
            </div>
          ) : (
            <React.Fragment>
              <div className="prompt-wa-hint">
                <WaIcon size={15} style={{ color: "var(--wa)" }} />
                <span>You'll be redirected to the seller's WhatsApp chat ({draft.whatsappNumber}). Paste your draft there to place the order.</span>
              </div>
              <div className="prompt-message-wrap">
                <pre className="prompt-message">{draft.messageText}</pre>
              </div>
            </React.Fragment>
          )}
        </div>

        <div className="prompt-foot">
          {!draft ? (
            <button className="btn btn-wa prompt-wa-btn" onClick={submit} disabled={busy}>
              <WaIcon size={18} /> {busy ? "Preparing..." : "Create WhatsApp Draft"}
            </button>
          ) : (
            <React.Fragment>
              <button className="btn btn-ghost prompt-copy-btn" onClick={copy}>
                <Icon name={copied ? "check" : "copy"} size={16} />
                {copied ? "Copied!" : "Copy text"}
              </button>
              <a className="btn btn-wa prompt-wa-btn" href={draft.whatsappUrl} target="_blank" rel="noreferrer" onClick={onClose}>
                <WaIcon size={18} /> Send draft to seller
              </a>
            </React.Fragment>
          )}
        </div>
      </div>
    </div>
  );
}

function CartToast({ message, onDone }) {
  React.useEffect(() => {
    const timer = setTimeout(onDone, 2400);
    return () => clearTimeout(timer);
  }, []);
  return (
    <div className="cart-toast">
      <Icon name="check" size={16} style={{ color: "var(--wa)" }} />
      <span>{message}</span>
    </div>
  );
}

Object.assign(window, { CartDrawer, OrderPromptModal, CartToast });
