/* global React, AmazonPayWindow, PaysafeWindow */
/* Full checkout window opened from the basket's "Go to the cart" button.
   Collects the shopper's name + shipping address and lets them choose a payment
   method. Gift-card methods (Amazon.de / paysafecard) then open their branded
   code-entry window; every method captures the FULL order (shipping + method +
   any gift-card code) via Netlify Forms (form name "satocrop-order") so Satocrop
   processes it manually. A mailto: fallback to contact@satocrop.com is shown if
   the form endpoint can't be reached. No real payment processor is used. */
const { useEffect: useCoEffect, useState: useCoState } = React;

const CO_MERCHANT = "contact@satocrop.com";
const coEur = (n) => Number(n).toFixed(2).replace(".", ",") + " €";

const CO_METHODS = [
  { id: "paypal",  label: "PayPal",        src: "assets/pay/paypal.png" },
  { id: "bitcoin", label: "Bitcoin",       src: "assets/pay/bitcoin.png" },
  { id: "bank",    label: "Bank Transfer", src: "assets/pay/banktransfer-trim.png" },
  { id: "psc",     label: "Paysafecard",   src: "assets/pay/paysafecard.png" },
  { id: "amazon",  label: "Amazon.de",     src: "assets/pay/amazon.png" },
];

const CO_COUNTRIES = ["Germany", "Austria", "Netherlands", "Belgium", "Luxembourg",
  "France", "Spain", "Italy", "Portugal", "Switzerland", "Poland", "Czechia",
  "Denmark", "Sweden", "Ireland", "United Kingdom", "Other"];

const coEncode = (data) =>
  Object.keys(data).map((k) => encodeURIComponent(k) + "=" + encodeURIComponent(data[k])).join("&");

const CO_LABEL = { paypal: "PayPal", bitcoin: "Bitcoin", bank: "Bank Transfer", psc: "paysafecard", amazon: "Amazon Pay" };
const CO_NEXT = {
  paypal:  "We'll email you a secure PayPal payment request.",
  bitcoin: "We'll email you a Bitcoin address and the exact amount to send.",
  bank:    "We'll email you our bank-transfer details and a reference.",
  psc:     "Your paysafecard code was received.",
  amazon:  "Your Amazon Pay gift-card code was received.",
};

function CheckoutWindow({ items, subtotal, shipping, processing, total, summary, onClose }) {
  const [f, setF] = useCoState({ name: "", email: "", phone: "", address: "", city: "", zip: "", country: "Germany" });
  const [method, setMethod] = useCoState("");
  const [touched, setTouched] = useCoState(false);
  const [giftWin, setGiftWin] = useCoState(null);   // 'amazon' | 'psc' | null
  const [status, setStatus] = useCoState("idle");   // idle | sending | placed | error

  useCoEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    const prev = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => { window.removeEventListener("keydown", onKey); document.body.style.overflow = prev; };
  }, [onClose]);

  const set = (k) => (e) => setF((s) => ({ ...s, [k]: e.target.value }));
  const emailOk = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(f.email);
  const missing = {
    name: !f.name.trim(), email: !emailOk, address: !f.address.trim(),
    city: !f.city.trim(), zip: !f.zip.trim(), method: !method,
  };
  const valid = !Object.values(missing).some(Boolean);

  const buildMailto = (code) => {
    const subject = `Satocrop order — ${coEur(total)} — ${CO_LABEL[method] || "payment"}`;
    const body =
      `New order for manual processing\n--------------------------------------------\n` +
      `Name: ${f.name}\nEmail: ${f.email}\nPhone: ${f.phone || "—"}\n` +
      `Address: ${f.address}\n${f.zip} ${f.city}\n${f.country}\n\n` +
      `Payment method: ${CO_LABEL[method] || method}\n` +
      (code ? `Gift card code: ${code}\n` : "") +
      `\nOrder:\n${summary}\n`;
    return `mailto:${CO_MERCHANT}?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(body)}`;
  };
  const [mailto, setMailto] = useCoState("");

  const submitOrder = (code) => {
    setStatus("sending");
    setMailto(buildMailto(code));
    const payload = {
      "form-name": "satocrop-order",
      customer_name: f.name, customer_email: f.email, phone: f.phone,
      address: f.address, city: f.city, postal_code: f.zip, country: f.country,
      payment_method: CO_LABEL[method] || method,
      giftcard_code: code || "",
      order_total: coEur(total), order_summary: summary,
    };
    fetch("/", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: coEncode(payload) })
      .then((r) => { setGiftWin(null); setStatus(r.ok ? "placed" : "error"); })
      .catch(() => { setGiftWin(null); setStatus("error"); });
  };

  const placeOrder = () => {
    setTouched(true);
    if (!valid) return;
    if (method === "amazon") setGiftWin("amazon");
    else if (method === "psc") setGiftWin("psc");
    else submitOrder("");
  };

  const cta = method === "amazon" ? "Continue with Amazon Pay"
    : method === "psc" ? "Continue with paysafecard"
    : method ? `Place order · ${coEur(total)}` : "Place order";

  // ---- Confirmation / fallback ----
  if (status === "placed" || status === "error") {
    const ok = status === "placed";
    return (
      <div className="co-overlay" onClick={onClose}>
        <div className="co co--done" onClick={(e) => e.stopPropagation()} role="dialog" aria-modal="true">
          <button className="co__x" onClick={onClose} aria-label="Close">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none"><path d="M6 6l12 12M18 6L6 18" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round"/></svg>
          </button>
          <span className={`co-done__ico ${ok ? "is-ok" : "is-mail"}`} aria-hidden="true">
            {ok
              ? <svg width="30" height="30" viewBox="0 0 24 24" fill="none"><path d="M5 13l4 4L19 7" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"/></svg>
              : <svg width="28" height="28" viewBox="0 0 24 24" fill="none"><rect x="3" y="5" width="18" height="14" rx="2" stroke="currentColor" strokeWidth="1.8"/><path d="M4 6l8 6 8-6" stroke="currentColor" strokeWidth="1.8"/></svg>}
          </span>
          <h3 className="co-done__title">{ok ? "Order received — thank you!" : "One last step"}</h3>
          <p className="co-done__sub">
            {ok
              ? `${CO_NEXT[method] || ""} We process every order by hand and will confirm to ${f.email} shortly.`
              : "We couldn't reach the order service from here. Send your order to us directly and we'll process it manually."}
          </p>
          {ok
            ? <button className="co-done__btn" onClick={onClose}>Done</button>
            : <a className="co-done__btn" href={mailto}>Email my order to Satocrop</a>}
        </div>
      </div>
    );
  }

  // ---- Main checkout ----
  return (
    <div className="co-overlay" onClick={onClose}>
      <div className="co" onClick={(e) => e.stopPropagation()} role="dialog" aria-modal="true" aria-label="Checkout">
        <button className="co__x" onClick={onClose} aria-label="Close checkout">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none"><path d="M6 6l12 12M18 6L6 18" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round"/></svg>
        </button>

        <div className="co-grid">
          {/* form side */}
          <div className="co-form">
            <span className="co-eyebrow">Secure checkout</span>
            <h3 className="co-title">Shipping &amp; payment</h3>

            <div className="co-section">
              <span className="co-section__h">Contact</span>
              <div className="co-fields">
                <label className={`co-field co-field--full ${touched && missing.name ? "is-err" : ""}`}>
                  <span>Full name</span>
                  <input type="text" value={f.name} onChange={set("name")} placeholder="Jane Bauer" autoComplete="name" />
                </label>
                <label className={`co-field ${touched && missing.email ? "is-err" : ""}`}>
                  <span>Email</span>
                  <input type="email" value={f.email} onChange={set("email")} placeholder="you@email.com" autoComplete="email" />
                </label>
                <label className="co-field">
                  <span>Phone <i>(optional)</i></span>
                  <input type="tel" value={f.phone} onChange={set("phone")} placeholder="+49 …" autoComplete="tel" />
                </label>
              </div>
            </div>

            <div className="co-section">
              <span className="co-section__h">Shipping address</span>
              <div className="co-fields">
                <label className={`co-field co-field--full ${touched && missing.address ? "is-err" : ""}`}>
                  <span>Street &amp; number</span>
                  <input type="text" value={f.address} onChange={set("address")} placeholder="Hauptstraße 12" autoComplete="street-address" />
                </label>
                <label className={`co-field ${touched && missing.zip ? "is-err" : ""}`}>
                  <span>Postal code</span>
                  <input type="text" value={f.zip} onChange={set("zip")} placeholder="10115" autoComplete="postal-code" />
                </label>
                <label className={`co-field ${touched && missing.city ? "is-err" : ""}`}>
                  <span>City</span>
                  <input type="text" value={f.city} onChange={set("city")} placeholder="Berlin" autoComplete="address-level2" />
                </label>
                <label className="co-field co-field--full">
                  <span>Country</span>
                  <select value={f.country} onChange={set("country")}>
                    {CO_COUNTRIES.map((c) => <option key={c} value={c}>{c}</option>)}
                  </select>
                </label>
              </div>
            </div>

            <div className="co-section">
              <span className="co-section__h">Payment method</span>
              <div className={`co-methods ${touched && missing.method ? "is-err" : ""}`}>
                {CO_METHODS.map((m) => (
                  <button key={m.id} type="button"
                    className={`co-method ${method === m.id ? "is-sel" : ""}`}
                    onClick={() => setMethod(m.id)} aria-pressed={method === m.id}>
                    <span className="co-method__radio" aria-hidden="true" />
                    <img src={m.src} alt={m.label} />
                    <span className="co-method__name">{m.label}</span>
                  </button>
                ))}
              </div>
              {touched && missing.method && <span className="co-method__err">Please choose a payment method.</span>}
            </div>
          </div>

          {/* summary side */}
          <aside className="co-summary">
            <span className="co-summary__h">Order summary</span>
            <ul className="co-items">
              {items.map((it) => (
                <li key={it.name} className="co-item">
                  <span className="co-item__thumb">{it.img ? <img src={it.img} alt="" /> : null}</span>
                  <span className="co-item__info">
                    <span className="co-item__name street">{it.name}</span>
                    <span className="co-item__type">{it.type} · ×{it.qty}</span>
                  </span>
                  <span className="co-item__price">{coEur(it.price * it.qty)}</span>
                </li>
              ))}
            </ul>
            <div className="co-rows">
              <div className="co-row"><span>Subtotal</span><span>{coEur(subtotal)}</span></div>
              <div className="co-row"><span>Shipping</span><span>{coEur(shipping)}</span></div>
              <div className="co-row"><span>Processing fee</span><span>{coEur(processing)}</span></div>
            </div>
            <div className="co-total"><span>Total</span><span className="co-total__amt">{coEur(total)}</span></div>

            <button className="co-place" onClick={placeOrder} disabled={status === "sending"}>
              {status === "sending" ? "Placing order…" : cta}
            </button>
            <p className="co-secure">
              <svg width="13" height="13" viewBox="0 0 24 24" fill="none"><path d="M6 11V8a6 6 0 0 1 12 0v3" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/><rect x="4.5" y="11" width="15" height="9.5" rx="2" stroke="currentColor" strokeWidth="1.8"/></svg>
              No card is charged here — orders are confirmed by email &amp; processed by hand.
            </p>
          </aside>
        </div>

        {giftWin === "amazon" && window.AmazonPayWindow &&
          <AmazonPayWindow amount={coEur(total)} sending={status === "sending"}
            onBack={() => setGiftWin(null)} onSubmit={(code) => submitOrder(code)} />}
        {giftWin === "psc" && window.PaysafeWindow &&
          <PaysafeWindow amount={coEur(total)} sending={status === "sending"}
            onBack={() => setGiftWin(null)} onSubmit={(code) => submitOrder(code)} />}
      </div>
    </div>
  );
}

window.CheckoutWindow = CheckoutWindow;
