// Checkout page + order email
const { useState: useSC } = React;

// ============================================================================
// EMAIL NOTIFICATION SETUP (replace with your own)
// ----------------------------------------------------------------------------
// This uses Web3Forms (https://web3forms.com) — free, no-signup email forwarding.
// 1. Go to https://web3forms.com and enter your email to get an Access Key.
// 2. Paste your key below in WEB3FORMS_KEY.
// 3. Orders will arrive at the email you used to register the key.
// ============================================================================
window.TF_CONFIG = {
  WEB3FORMS_KEY: "8e43591b-5aa7-4b6a-9780-37aa6597844f",
  BRAND_EMAIL: "orders@twofragrances.com",
};

const PUNJAB_CITIES = [
  { name: "Lahore", fee: 200 },
  { name: "Faisalabad", fee: 400 },
  { name: "Rawalpindi", fee: 400 },
  { name: "Multan", fee: 400 },
  { name: "Gujranwala", fee: 400 },
  { name: "Sialkot", fee: 400 },
  { name: "Bahawalpur", fee: 400 },
];

function CheckoutPage({ cart, setCart, go }) {
  const [form, setForm] = useSC({
    name: "", phone: "", email: "", address: "", city: "Lahore", notes: "",
  });
  const [touched, setTouched] = useSC({});
  const [submitting, setSubmitting] = useSC(false);
  const [placed, setPlaced] = useSC(null); // order object once placed

  const city = PUNJAB_CITIES.find(c => c.name === form.city) || PUNJAB_CITIES[0];
  const subtotal = cart.reduce((s, i) => s + i.price * i.qty, 0);
  const shipping = cart.length === 0 ? 0 : city.fee;
  const total = subtotal + shipping;

  const errors = {
    name: form.name.trim().length < 2 ? "Please enter your full name" : "",
    phone: !/^[0-9+\-\s()]{10,}$/.test(form.phone.trim()) ? "Please enter a valid phone number" : "",
    email: !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email.trim()) ? "Please enter a valid email" : "",
    address: form.address.trim().length < 10 ? "Please enter a complete address" : "",
  };
  const isValid = !errors.name && !errors.phone && !errors.email && !errors.address;

  const showErr = (f) => touched[f] && errors[f];

  const update = (k) => (e) => setForm(f => ({ ...f, [k]: e.target.value }));
  const blur = (k) => () => setTouched(t => ({ ...t, [k]: true }));

  const placeOrder = async () => {
    setTouched({ name: true, phone: true, email: true, address: true });
    if (!isValid || cart.length === 0) return;
    setSubmitting(true);

    const orderId = "TF-" + Date.now().toString(36).toUpperCase();
    const itemLines = cart.map(i => `  • ${i.name} — ${i.size} × ${i.qty} = Rs ${(i.price * i.qty).toLocaleString("en-PK")}`).join("\n");
    const orderText = `
NEW ORDER — ${orderId}
=======================================

CUSTOMER
  Name:    ${form.name}
  Phone:   ${form.phone}
  Email:   ${form.email}
  City:    ${form.city}
  Address: ${form.address}
  Notes:   ${form.notes || "—"}

ITEMS
${itemLines}

Subtotal:      Rs ${subtotal.toLocaleString("en-PK")}
Shipping:      Rs ${shipping.toLocaleString("en-PK")} (${form.city})
TOTAL (COD):   Rs ${total.toLocaleString("en-PK")}

Payment: Cash on Delivery
Placed:  ${new Date().toLocaleString("en-PK")}
`.trim();

    const order = {
      id: orderId, form, cart: [...cart], subtotal, shipping, total,
      placedAt: new Date().toISOString(),
    };

    // Try to email via Web3Forms if key is set
    try {
      if (window.TF_CONFIG.WEB3FORMS_KEY && window.TF_CONFIG.WEB3FORMS_KEY.length > 10) {
        await fetch("https://api.web3forms.com/submit", {
          method: "POST",
          headers: { "Content-Type": "application/json", "Accept": "application/json" },
          body: JSON.stringify({
            access_key: window.TF_CONFIG.WEB3FORMS_KEY,
            subject: `New Two Fragrances order — ${orderId} — Rs ${total.toLocaleString("en-PK")}`,
            from_name: "Two Fragrances Website",
            replyto: form.email,
            message: orderText,
            customer_name: form.name,
            customer_phone: form.phone,
            customer_city: form.city,
            order_total: "Rs " + total.toLocaleString("en-PK"),
          }),
        });
      }
    } catch (err) {
      console.warn("Email send failed:", err);
    }

    // Log locally so the order is never lost
    const prev = JSON.parse(localStorage.getItem("tf_orders") || "[]");
    localStorage.setItem("tf_orders", JSON.stringify([order, ...prev]));

    setSubmitting(false);
    setPlaced(order);
    setCart([]);
    window.scrollTo({ top: 0 });
  };

  if (placed) {
    return (
      <div className="container" style={{ padding: "80px 0 160px", maxWidth: 720 }}>
        <div style={{ textAlign: "center", padding: "40px 0" }}>
          <div className="eyebrow" style={{ marginBottom: 20 }}>— Order Confirmed —</div>
          <h1 style={{ fontFamily: "Cormorant Garamond", fontSize: 72, fontWeight: 300, lineHeight: 1, marginBottom: 20 }}>
            Thank you, <em style={{ color: "var(--gold)", fontStyle: "italic" }}>{placed.form.name.split(" ")[0]}.</em>
          </h1>
          <p style={{ color: "var(--ink-soft)", maxWidth: 480, margin: "0 auto 32px", fontSize: 16, lineHeight: 1.7 }}>
            Your order has been placed. We'll call you on <strong style={{ color: "var(--ink)" }}>{placed.form.phone}</strong> within 24 hours to confirm, then dispatch to {placed.form.city}.
          </p>
          <div style={{ display: "inline-flex", flexDirection: "column", gap: 8, padding: "24px 40px", background: "var(--paper-2)", border: "1px solid var(--line)", marginBottom: 40 }}>
            <div className="eyebrow">Order Reference</div>
            <div style={{ fontFamily: "JetBrains Mono, monospace", fontSize: 22, letterSpacing: "0.08em" }}>{placed.id}</div>
          </div>
          <div style={{ borderTop: "1px solid var(--line)", borderBottom: "1px solid var(--line)", padding: "32px 0", marginBottom: 40, textAlign: "left" }}>
            {placed.cart.map(i => (
              <div key={i.id} style={{ display: "flex", justifyContent: "space-between", padding: "10px 0", fontSize: 14 }}>
                <span>{i.name} — <span style={{ color: "var(--muted)" }}>{i.size} × {i.qty}</span></span>
                <span style={{ fontFamily: "Cormorant Garamond", fontStyle: "italic", fontSize: 17 }}>Rs {(i.price * i.qty).toLocaleString("en-PK")}</span>
              </div>
            ))}
            <div style={{ display: "flex", justifyContent: "space-between", padding: "10px 0", fontSize: 14, color: "var(--ink-soft)" }}>
              <span>Shipping — {placed.form.city}</span>
              <span>Rs {placed.shipping.toLocaleString("en-PK")}</span>
            </div>
            <div style={{ display: "flex", justifyContent: "space-between", padding: "16px 0 0", borderTop: "1px solid var(--line)", marginTop: 12 }}>
              <span style={{ fontSize: 11, letterSpacing: "0.2em", textTransform: "uppercase", color: "var(--muted)", alignSelf: "center" }}>Total · Cash on Delivery</span>
              <span style={{ fontFamily: "Cormorant Garamond", fontStyle: "italic", fontSize: 32 }}>Rs {placed.total.toLocaleString("en-PK")}</span>
            </div>
          </div>
          <button className="btn" onClick={() => go("home")}>Continue shopping →</button>
        </div>
      </div>
    );
  }

  return (
    <>
      <div className="container">
        <div className="pdp-breadcrumb"><a onClick={() => go("home")}>Home</a> &nbsp;/&nbsp; Checkout</div>
      </div>
      <div className="container" style={{ paddingBottom: 120 }}>
        <div style={{ display: "grid", gridTemplateColumns: "1.3fr 1fr", gap: 80, alignItems: "start", marginTop: 32 }} className="checkout-grid">
          {/* LEFT — form */}
          <div>
            <div className="eyebrow" style={{ marginBottom: 16 }}>— Checkout · Cash on Delivery —</div>
            <h1 style={{ fontFamily: "Cormorant Garamond", fontSize: 72, fontWeight: 300, lineHeight: 0.95, letterSpacing: "-0.01em", marginBottom: 48 }}>
              Almost <em style={{ color: "var(--gold)", fontStyle: "italic" }}>yours.</em>
            </h1>

            {cart.length === 0 ? (
              <div style={{ padding: "60px 0", borderTop: "1px solid var(--line)", borderBottom: "1px solid var(--line)", textAlign: "center" }}>
                <div style={{ fontFamily: "Cormorant Garamond", fontStyle: "italic", fontSize: 28, marginBottom: 8 }}>Your cart is empty.</div>
                <p style={{ color: "var(--muted)", marginBottom: 24 }}>Add something to the cart before checking out.</p>
                <button className="btn" onClick={() => go("shop")}>Browse the range →</button>
              </div>
            ) : (
              <>
                <section style={{ borderTop: "1px solid var(--line)", paddingTop: 32, marginBottom: 40 }}>
                  <div style={{ fontSize: 11, letterSpacing: "0.2em", textTransform: "uppercase", color: "var(--muted)", marginBottom: 20 }}>01 · Contact</div>
                  <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 20 }}>
                    <Field label="Full name" value={form.name} onChange={update("name")} onBlur={blur("name")} error={showErr("name")} placeholder="e.g. Ayesha Khan" />
                    <Field label="Phone number" value={form.phone} onChange={update("phone")} onBlur={blur("phone")} error={showErr("phone")} placeholder="03xx xxxxxxx" type="tel" />
                    <Field label="Email" value={form.email} onChange={update("email")} onBlur={blur("email")} error={showErr("email")} placeholder="you@email.com" type="email" full />
                  </div>
                </section>

                <section style={{ borderTop: "1px solid var(--line)", paddingTop: 32, marginBottom: 40 }}>
                  <div style={{ fontSize: 11, letterSpacing: "0.2em", textTransform: "uppercase", color: "var(--muted)", marginBottom: 20 }}>02 · Delivery</div>
                  <div style={{ marginBottom: 20 }}>
                    <div style={{ fontSize: 11, letterSpacing: "0.16em", textTransform: "uppercase", color: "var(--ink-soft)", marginBottom: 12 }}>City</div>
                    <div style={{ position: "relative" }}>
                      <select
                        value={form.city}
                        onChange={(e) => setForm(f => ({ ...f, city: e.target.value }))}
                        style={{
                          width: "100%", padding: "14px 16px",
                          border: "1px solid var(--line)",
                          background: "var(--paper)",
                          fontFamily: "inherit", fontSize: 15, color: "var(--ink)",
                          outline: "none", appearance: "none",
                          WebkitAppearance: "none", MozAppearance: "none",
                          cursor: "pointer",
                          backgroundImage: "url(\"data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='12' height='8' viewBox='0 0 12 8'><path d='M1 1l5 5 5-5' stroke='%231A1814' stroke-width='1.2' fill='none'/></svg>\")",
                          backgroundRepeat: "no-repeat",
                          backgroundPosition: "right 16px center",
                          paddingRight: 44,
                        }}
                      >
                        {PUNJAB_CITIES.map(c => (
                          <option key={c.name} value={c.name}>{c.name}</option>
                        ))}
                      </select>
                    </div>
                  </div>
                  <Field label="Complete address" value={form.address} onChange={update("address")} onBlur={blur("address")} error={showErr("address")} placeholder="House, street, area, landmark…" full textarea />
                  <Field label="Order notes (optional)" value={form.notes} onChange={update("notes")} placeholder="Anything we should know?" full textarea short />
                </section>

                <section style={{ borderTop: "1px solid var(--line)", paddingTop: 32, marginBottom: 40 }}>
                  <div style={{ fontSize: 11, letterSpacing: "0.2em", textTransform: "uppercase", color: "var(--muted)", marginBottom: 20 }}>03 · Payment</div>
                  <div style={{ display: "flex", gap: 16, alignItems: "center", padding: "20px 24px", border: "1px solid var(--ink)", background: "var(--paper-2)" }}>
                    <div style={{ width: 14, height: 14, borderRadius: "50%", border: "4px solid var(--ink)" }} />
                    <div style={{ flex: 1 }}>
                      <div style={{ fontFamily: "Cormorant Garamond", fontSize: 22 }}>Cash on Delivery</div>
                      <div style={{ fontSize: 12, color: "var(--muted)", marginTop: 2 }}>Pay in cash when your order arrives at your door.</div>
                    </div>
                    <div style={{ fontFamily: "Cormorant Garamond", fontStyle: "italic", fontSize: 24 }}>Rs {total.toLocaleString("en-PK")}</div>
                  </div>
                </section>

                <button
                  className="btn"
                  style={{ width: "100%", padding: "22px 32px", fontSize: 12, opacity: submitting ? 0.6 : 1 }}
                  onClick={placeOrder}
                  disabled={submitting}
                >
                  {submitting ? "Placing order…" : `Place order · Rs ${total.toLocaleString("en-PK")}`}
                </button>
                <p style={{ textAlign: "center", fontSize: 11, color: "var(--muted)", marginTop: 16, letterSpacing: "0.1em" }}>
                  By placing this order you agree to pay in cash on delivery.
                </p>
              </>
            )}
          </div>

          {/* RIGHT — summary */}
          {cart.length > 0 && (
            <aside style={{ position: "sticky", top: 120, background: "var(--paper-2)", padding: 40, border: "1px solid var(--line)" }}>
              <div className="eyebrow" style={{ marginBottom: 16 }}>— Your Order —</div>
              <div style={{ fontFamily: "Cormorant Garamond", fontSize: 36, lineHeight: 1, marginBottom: 24, fontWeight: 300 }}>
                {cart.reduce((s, i) => s + i.qty, 0)} <em style={{ fontStyle: "italic", color: "var(--muted)" }}>items</em>
              </div>
              <div style={{ borderTop: "1px solid var(--line)" }}>
                {cart.map(i => (
                  <div key={i.id} style={{ display: "grid", gridTemplateColumns: "56px 1fr auto", gap: 14, padding: "16px 0", borderBottom: "1px solid var(--line)", alignItems: "center" }}>
                    <div style={{ background: "var(--paper)", height: 70, display: "flex", alignItems: "center", justifyContent: "center", padding: 6 }}>
                      <img src={i.image} alt={i.name} style={{ maxHeight: "100%", maxWidth: "100%", objectFit: "contain", mixBlendMode: "multiply" }} />
                    </div>
                    <div>
                      <div style={{ fontFamily: "Cormorant Garamond", fontSize: 18, lineHeight: 1.1 }}>{i.name}</div>
                      <div style={{ fontSize: 10, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--muted)", marginTop: 2 }}>{i.size} · Qty {i.qty}</div>
                    </div>
                    <div style={{ fontFamily: "Cormorant Garamond", fontStyle: "italic", fontSize: 18 }}>Rs {(i.price * i.qty).toLocaleString("en-PK")}</div>
                  </div>
                ))}
              </div>
              <div style={{ paddingTop: 20, fontSize: 14, display: "flex", flexDirection: "column", gap: 10 }}>
                <div style={{ display: "flex", justifyContent: "space-between" }}>
                  <span style={{ color: "var(--ink-soft)" }}>Subtotal</span>
                  <span>Rs {subtotal.toLocaleString("en-PK")}</span>
                </div>
                <div style={{ display: "flex", justifyContent: "space-between" }}>
                  <span style={{ color: "var(--ink-soft)" }}>Shipping — {form.city}</span>
                  <span>Rs {shipping.toLocaleString("en-PK")}</span>
                </div>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", paddingTop: 16, borderTop: "1px solid var(--line)", marginTop: 6 }}>
                  <span style={{ fontSize: 11, letterSpacing: "0.2em", textTransform: "uppercase", color: "var(--muted)" }}>Total</span>
                  <span style={{ fontFamily: "Cormorant Garamond", fontStyle: "italic", fontSize: 36 }}>Rs {total.toLocaleString("en-PK")}</span>
                </div>
              </div>
            </aside>
          )}
        </div>
      </div>
    </>
  );
}

function Field({ label, value, onChange, onBlur, error, placeholder, type = "text", full, textarea, short }) {
  const style = {
    width: "100%", padding: "14px 16px",
    border: "1px solid " + (error ? "#c0392b" : "var(--line)"),
    background: "var(--paper)",
    fontFamily: "inherit", fontSize: 15, color: "var(--ink)",
    outline: "none", transition: "border 0.2s",
  };
  return (
    <div style={{ gridColumn: full ? "1 / -1" : "auto" }}>
      <div style={{ fontSize: 11, letterSpacing: "0.16em", textTransform: "uppercase", color: "var(--ink-soft)", marginBottom: 8 }}>{label}</div>
      {textarea ? (
        <textarea value={value} onChange={onChange} onBlur={onBlur} placeholder={placeholder} rows={short ? 2 : 3} style={{ ...style, resize: "vertical", fontFamily: "inherit" }} />
      ) : (
        <input type={type} value={value} onChange={onChange} onBlur={onBlur} placeholder={placeholder} style={style} />
      )}
      {error && <div style={{ fontSize: 12, color: "#c0392b", marginTop: 6 }}>{error}</div>}
    </div>
  );
}

Object.assign(window, { CheckoutPage });
