// Checkout flow — order request by email, payment arranged manually.
// No payment handles or instructions on-site: the buyer picks a PREFERRED
// payment method from a dropdown; the seller replies to the order email
// with payment details for that method.
const { useState: useStateK, useMemo: useMemoK } = React;

function genOrderNumber() {
  const t = Date.now().toString(36).toUpperCase().slice(-5);
  const r = Math.floor(Math.random() * 36 * 36).toString(36).toUpperCase().padStart(2, "0");
  return `CC-${t}${r}`;
}

function buildOrderText({ orderNo, form, lines, subtotal, ship, total, methodLabel }) {
  const addr = `${form.name}\n${form.address}\n${form.city}, ${form.state} ${form.zip}`;
  return [
    `ORDER ${orderNo}`,
    `Clown Catcher Research — order request`,
    ``,
    `ITEMS`,
    ...lines.map(l => `  ${l.qty}x ${l.name} (${l.variant}) — $${l.total}`),
    ``,
    `Subtotal: $${subtotal}`,
    `Shipping: ${ship === 0 ? "FREE" : "$" + ship}`,
    `TOTAL: $${total}`,
    ``,
    `PREFERRED PAYMENT METHOD: ${methodLabel}`,
    ``,
    `SHIP TO`,
    addr,
    ``,
    `Contact email: ${form.email}`,
    ...(form.notes ? [``, `Notes: ${form.notes}`] : []),
    ``,
    `I certify I am 21+ and a qualified research professional.`,
    `All products are for research use only.`,
  ].join("\n");
}

function CheckoutPage() {
  const { items, subtotal, clear } = useCart();
  const info = window.ORDER_INFO;
  const [method, setMethod] = useStateK("cashapp");
  const [form, setForm] = useStateK({ name: "", email: "", address: "", city: "", state: "", zip: "", notes: "" });
  const [placed, setPlaced] = useStateK(null);
  const [sending, setSending] = useStateK(false);
  const [sendError, setSendError] = useStateK("");
  const [botField, setBotField] = useStateK("");

  const lines = useMemoK(() => items.map(i => {
    const p = window.PRODUCTS.find(p => p.id === i.id);
    if (!p) return null;
    const variant = p.variants[i.v || 0] || p.variants[0];
    return { name: p.name, variant: variant.l, qty: i.qty, total: variant.p * i.qty };
  }).filter(Boolean), [items]);

  const m = window.PAYMENT_METHODS.find(x => x.id === method);
  const ship = subtotal >= info.freeOver ? 0 : (subtotal > 0 ? info.shipping : 0);
  const total = subtotal + ship;

  const set = (k) => (e) => setForm(f => ({ ...f, [k]: e.target.value }));
  const valid = form.name && form.email && form.address && form.city && form.state && form.zip && items.length > 0;

  // Submit the order to the server. If that fails for any reason we fall back
  // to the old email flow rather than dropping the order on the floor — the
  // buyer always leaves with a way to get their order to us.
  const placeOrder = async (e) => {
    e.preventDefault();
    if (!valid || sending) return;
    setSending(true);
    setSendError("");

    const payload = {
      ...form,
      company: botField,                                  // honeypot
      method,
      items: items.map(i => ({ id: i.id, v: i.v || 0, qty: i.qty })),
    };

    let data = null;
    let failCode = "";
    try {
      const res = await fetch("/api/order", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });
      data = await res.json().catch(() => null);
      if (!res.ok || !data || !data.ok) {
        failCode = (data && data.code) || "";
        throw new Error((data && data.error) || `Server error (${res.status})`);
      }
    } catch (err) {
      // Fall back to the manual email path, pre-filled and ready to send.
      const orderNo = genOrderNumber();
      setPlaced({
        orderNo,
        text: buildOrderText({ orderNo, form, lines, subtotal, ship, total, methodLabel: m.label }),
        methodLabel: m.label,
        total,
        sent: false,
        code: failCode,
        reason: err.message || "The order could not be sent automatically.",
      });
      setSending(false);
      window.scrollTo(0, 0);
      return;
    }

    setPlaced({
      orderNo: data.orderNo,
      text: data.text || buildOrderText({ orderNo: data.orderNo, form, lines, subtotal, ship, total, methodLabel: m.label }),
      methodLabel: m.label,
      total: data.total != null ? data.total : total,
      sent: true,
    });
    clear();
    setSending(false);
    window.scrollTo(0, 0);
  };

  if (placed) return <OrderConfirmation placed={placed} />;

  if (items.length === 0) {
    return (
      <main className="checkout-page" data-screen-label="Checkout">
        <div className="cart-empty">
          <h2>Nothing to check out</h2>
          <p>Your cart is empty. Add some compounds first.</p>
          <a href="/shop" className="btn btn-primary"><span>Shop all peptides</span><span className="arrow">→</span></a>
        </div>
      </main>
    );
  }

  return (
    <main className="checkout-page" data-screen-label="Checkout">
      <section className="cart-head">
        <div className="cart-head-eyebrow">Step 1 of 2 — order details</div>
        <h1 className="cart-title">Checkout</h1>
      </section>
      <form className="checkout-grid" onSubmit={placeOrder}>
        <div className="checkout-form">
          <div className="form-block">
            <h3>Contact &amp; shipping</h3>
            <div className="field-grid">
              <label className="field span2"><span>Full name</span><input required value={form.name} onChange={set("name")} placeholder="Jane Researcher" /></label>
              <label className="field span2"><span>Email</span><input required type="email" value={form.email} onChange={set("email")} placeholder="you@email.com" /></label>
              <label className="field span2"><span>Street address</span><input required value={form.address} onChange={set("address")} placeholder="123 Lab Way, Apt 4" /></label>
              <label className="field"><span>City</span><input required value={form.city} onChange={set("city")} placeholder="City" /></label>
              <label className="field half"><span>State</span><input required value={form.state} onChange={set("state")} placeholder="ST" maxLength={2} /></label>
              <label className="field half"><span>ZIP</span><input required value={form.zip} onChange={set("zip")} placeholder="00000" /></label>
              <label className="field span2"><span>Order notes (optional)</span><input value={form.notes} onChange={set("notes")} placeholder="Anything we should know" /></label>
            </div>
            {/* Honeypot — hidden from people, catnip for bots. Any value here
                makes the server accept and discard the submission. */}
            <div className="hp-field" aria-hidden="true">
              <label>Company
                <input type="text" tabIndex={-1} autoComplete="off" value={botField} onChange={(e) => setBotField(e.target.value)} />
              </label>
            </div>
          </div>

          <div className="form-block">
            <h3>Preferred payment method</h3>
            <p className="form-hint">We don't take payment on-site. Choose how you'd like to pay — after we receive your order, we'll email you payment details for your chosen method. Your order ships once payment is confirmed.</p>
            <label className="field span2 method-field">
              <span>Payment method</span>
              <select className="method-select" value={method} onChange={(e) => setMethod(e.target.value)}>
                {window.PAYMENT_METHODS.map(pm => (
                  <option key={pm.id} value={pm.id}>{pm.label}</option>
                ))}
              </select>
            </label>
          </div>

          <div className="research-warn">
            <div className="warn-bar"></div>
            <div><strong>For research use only.</strong> By placing this order you certify you are 21+ and a qualified research professional.</div>
          </div>
        </div>

        <aside className="cart-summary">
          <h3>Order summary</h3>
          <div className="checkout-lines">
            {lines.map((l, i) => (
              <div className="sum-line" key={i}><span>{l.qty}× {l.name} <em className="line-variant">{l.variant}</em></span><strong>${l.total}</strong></div>
            ))}
          </div>
          <div className="sum-divider"></div>
          <div className="sum-line"><span>Subtotal</span><strong>${subtotal}</strong></div>
          <div className="sum-line"><span>Shipping &amp; handling</span><strong>{ship === 0 ? "Free" : `$${ship}`}</strong></div>
          <div className="sum-divider"></div>
          <div className="sum-total"><span>Total</span><strong>${total}</strong></div>
          {ship > 0 && <div className="sum-note">Add ${info.freeOver - subtotal} more for free shipping</div>}
          <button type="submit" className={`btn btn-primary wide checkout ${valid && !sending ? "" : "disabled"}`} disabled={!valid || sending}>
            <span>{sending ? "Sending order…" : "Place order request"}</span>
            {!sending && <span className="arrow">→</span>}
          </button>
          {sendError && <div className="sum-error">{sendError}</div>}
          <div className="sum-fine">No charge happens now. We'll email you payment options for {m.label.replace(/ \(.*\)$/, "")} after we receive your order. PayPal and credit card orders include a processing fee, confirmed by email.</div>
        </aside>
      </form>
    </main>
  );
}

function OrderConfirmation({ placed }) {
  const info = window.ORDER_INFO;
  const [copiedText, setCopiedText] = useStateK("");

  const copy = (text, tag) => {
    try {
      navigator.clipboard.writeText(text);
      setCopiedText(tag);
      setTimeout(() => setCopiedText(""), 1800);
    } catch {}
  };

  const mailto = `mailto:${info.email}?subject=${encodeURIComponent("Order " + placed.orderNo)}&body=${encodeURIComponent(placed.text)}`;

  const sent = placed.sent !== false;

  return (
    <main className="checkout-page" data-screen-label="Order confirmation">
      <section className="cart-head">
        <div className="cart-head-eyebrow">{sent ? "Order received" : "Action needed — send your order"}</div>
        <h1 className="cart-title">Order <span className="accent">{placed.orderNo}</span></h1>
      </section>

      {!sent && (
        placed.code === "rate_limited" ? (
          <div className="confirm-alert">
            <strong>You've placed several orders in a row.</strong> {placed.reason}{" "}
            Your order is ready below — send it by email and it reaches us the same way.
          </div>
        ) : (
          <div className="confirm-alert">
            <strong>We couldn't submit your order automatically.</strong> Nothing has
            been lost — send it with the button below and we'll pick it up from there.
            {placed.reason ? <span className="confirm-alert-reason"> ({placed.reason})</span> : null}
          </div>
        )
      )}

      <div className="confirm-grid">
        <div className="confirm-steps">
          {sent ? (
            <div className="confirm-step">
              <div className="step-num">✓</div>
              <div>
                <h3>Your order is in</h3>
                <p>It landed in our inbox — there's nothing else you need to do right now. We've saved it under <strong>{placed.orderNo}</strong>; keep that number handy, it's your payment reference. A copy of the details is on the right.</p>
                <div className="confirm-actions">
                  <button className="btn btn-ghost" onClick={() => copy(placed.text, "order")}>
                    <span>{copiedText === "order" ? "Copied ✓" : "Copy order details"}</span>
                  </button>
                </div>
              </div>
            </div>
          ) : (
            <div className="confirm-step">
              <div className="step-num">1</div>
              <div>
                <h3>Email us your order</h3>
                <p>The button below opens a pre-filled email with everything in it — just hit send. Or copy the order text and send it from any email app.</p>
                <div className="confirm-actions">
                  <a className="btn btn-primary" href={mailto}><span>Open pre-filled email</span><span className="arrow">→</span></a>
                  <button className="btn btn-ghost" onClick={() => copy(placed.text, "order")}>
                    <span>{copiedText === "order" ? "Copied ✓" : "Copy order text"}</span>
                  </button>
                </div>
                <div className="confirm-email-note">Send to: <strong>{info.email}</strong></div>
              </div>
            </div>
          )}

          <div className="confirm-step">
            <div className="step-num">{sent ? "2" : "2"}</div>
            <div>
              <h3>We email you payment options</h3>
              <p>{sent
                ? <>We'll reply to <strong>{placed.methodLabel}</strong> with payment details for your total of <strong>${placed.total}</strong> — usually within a few hours.</>
                : <>Once your order lands in our inbox, we'll reply with payment details for <strong>{placed.methodLabel}</strong> and your total of <strong>${placed.total}</strong>.</>}
              </p>
            </div>
          </div>

          <div className="confirm-step">
            <div className="step-num">3</div>
            <div>
              <h3>Pay &amp; we ship</h3>
              <p>Send payment following the instructions in our reply. Once it's confirmed, your order ships — typically same day, with tracking sent to your email.</p>
            </div>
          </div>
        </div>

        <aside className="cart-summary">
          <h3>Your order</h3>
          <pre className="order-receipt">{placed.text}</pre>
          <a href="/shop" className="btn btn-ghost wide"><span>Continue shopping</span></a>
        </aside>
      </div>
    </main>
  );
}

Object.assign(window, { CheckoutPage });
