// Kotleto · validated local checkout flow

function CheckoutModal({ open, onClose, onSuccess }) {
  const { lang } = useLang();
  const cart = useCart();
  const deliveryConfig = useDeliveryConfig();
  const [step, setStep] = useState("details");
  const [form, setForm] = useState(() => ({
    name: LocalDB.get("user", {})?.name || "",
    phone: LocalDB.get("user", {})?.phone || "",
    address: LocalDB.get("user", {})?.address || "",
    note: "",
    payment: "card",
  }));
  const [otp, setOtp] = useState("");
  const [errors, setErrors] = useState({});
  const [submitting, setSubmitting] = useState(false);
  const submissionTimer = useRef(null);
  const submissionPending = useRef(false);
  const totals = getCartTotals(cart.subtotal, cart.promo, deliveryConfig);

  useEffect(() => {
    if (!open) return;
    const onKey = (event) => event.key === "Escape" && onClose();
    document.body.style.overflow = "hidden";
    window.addEventListener("keydown", onKey);
    return () => { document.body.style.overflow = ""; window.removeEventListener("keydown", onKey); };
  }, [open, onClose]);

  useEffect(() => {
    if (open) { setStep("details"); setOtp(""); setErrors({}); setSubmitting(false); submissionPending.current = false; }
    return () => { clearTimeout(submissionTimer.current); submissionPending.current = false; };
  }, [open]);

  if (!open) return null;

  const update = (key, value) => {
    setForm(current => ({ ...current, [key]: value }));
    setErrors(current => ({ ...current, [key]: "" }));
  };

  const validateDetails = () => {
    const next = {};
    if (cart.count === 0 || cart.subtotal < totals.minimumOrder) {
      notify(lang === "fa" ? "سبد خرید به حداقل مبلغ سفارش نرسیده است." : "Your cart has not reached the minimum order amount.", "error");
      return;
    }
    const phone = toEn(form.phone).replace(/\D/g, "");
    if (form.name.trim().length < 2) next.name = lang === "fa" ? "نام کامل را وارد کن" : "Enter your full name";
    if (!/^09\d{9}$/.test(phone)) next.phone = lang === "fa" ? "شماره باید ۱۱ رقمی و با ۰۹ شروع شود" : "Use an 11-digit mobile starting with 09";
    if (form.address.trim().length < 10) next.address = lang === "fa" ? "آدرس دقیق‌تری وارد کن" : "Enter a more complete address";
    setErrors(next);
    if (!Object.keys(next).length) {
      setForm(current => ({ ...current, phone }));
      setStep("otp");
    }
  };

  const confirm = () => {
    if (submissionPending.current || cart.count === 0) return;
    if (cart.subtotal < totals.minimumOrder) {
      notify(lang === "fa" ? "سبد خرید به حداقل مبلغ سفارش نرسیده است." : "Your cart has not reached the minimum order amount.", "error");
      setStep("details");
      return;
    }
    if (toEn(otp) !== "1234") {
      setErrors({ otp: lang === "fa" ? "کد آزمایشی ۱۲۳۴ است" : "Demo code is 1234" });
      return;
    }
    submissionPending.current = true;
    setSubmitting(true);
    LocalDB.set("user", { name: form.name.trim(), phone: form.phone, address: form.address.trim() });
    submissionTimer.current = setTimeout(() => {
      onSuccess({ ...form, ...totals });
      setSubmitting(false);
      submissionPending.current = false;
    }, 550);
  };

  return (
    <>
      <div onClick={onClose} style={{ position: "fixed", inset: 0, zIndex: 80, background: "rgba(26,20,16,.55)", backdropFilter: "blur(6px)" }} />
      <section className="modal-card" role="dialog" aria-modal="true" aria-labelledby="checkout-title" dir={lang === "fa" ? "rtl" : "ltr"} style={{
        position: "fixed", zIndex: 81, top: "50%", left: "50%", transform: "translate(-50%,-50%)",
        width: "min(560px,92vw)", maxHeight: "min(780px,92dvh)", overflowY: "auto",
        background: "var(--paper)", border: "1.5px solid var(--ink)", borderRadius: 28,
        boxShadow: "0 30px 80px rgba(0,0,0,.4)",
      }}>
        <header style={{ background: "var(--ink)", color: "var(--paper)", padding: "22px 26px", position: "relative" }}>
          <button onClick={onClose} aria-label={lang === "fa" ? "بستن" : "Close"} style={{ position: "absolute", top: 16, insetInlineEnd: 16, width: 44, height: 44, color: "var(--paper)", display: "grid", placeItems: "center" }}><Ico.X /></button>
          <div style={{ fontSize: 12, opacity: .6 }}>{lang === "fa" ? "تکمیل سفارش" : "Complete order"}</div>
          <h2 id="checkout-title" className="display" style={{ margin: "6px 0 0", fontSize: 28 }}>
            {step === "details" ? (lang === "fa" ? "کجا بیاریم؟" : "Where should we deliver?") : (lang === "fa" ? "تأیید شماره" : "Verify your number")}
          </h2>
        </header>

        <div className="mobile-compact" style={{ padding: 26 }}>
          <div style={{ display: "flex", justifyContent: "space-between", gap: 12, padding: "13px 15px", background: "var(--paper-2)", borderRadius: 14, marginBottom: 20 }}>
            <span>{lang === "fa" ? `${toFa(cart.count)} آیتم` : `${cart.count} items`}</span>
            <strong><Price value={totals.total} /></strong>
          </div>

          {step === "details" ? (
            <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
              <CheckoutField label={lang === "fa" ? "نام و نام خانوادگی" : "Full name"} error={errors.name}>
                <input autoFocus value={form.name} onChange={e => update("name", e.target.value)} autoComplete="name" style={checkoutInputStyle} />
              </CheckoutField>
              <CheckoutField label={lang === "fa" ? "شماره موبایل" : "Mobile number"} error={errors.phone}>
                <input value={form.phone} onChange={e => update("phone", e.target.value)} inputMode="numeric" autoComplete="tel" dir="ltr" placeholder="09123456789" style={checkoutInputStyle} />
              </CheckoutField>
              <CheckoutField label={lang === "fa" ? "آدرس تحویل" : "Delivery address"} error={errors.address}>
                <textarea value={form.address} onChange={e => update("address", e.target.value)} rows={3} autoComplete="street-address" style={{ ...checkoutInputStyle, resize: "vertical" }} />
              </CheckoutField>
              <CheckoutField label={lang === "fa" ? "توضیحات سفارش (اختیاری)" : "Order note (optional)"}>
                <input value={form.note} onChange={e => update("note", e.target.value)} placeholder={lang === "fa" ? "مثلاً بدون پیاز" : "e.g. no onions"} style={checkoutInputStyle} />
              </CheckoutField>
              <div role="radiogroup" aria-label={lang === "fa" ? "روش پرداخت" : "Payment method"} style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
                {[{ id: "card", fa: "کارت‌خوان", en: "Card on delivery" }, { id: "cash", fa: "نقدی", en: "Cash" }].map(item => (
                  <button key={item.id} role="radio" aria-checked={form.payment === item.id} onClick={() => update("payment", item.id)} style={{ padding: 12, borderRadius: 12, border: `1.5px solid ${form.payment === item.id ? "var(--brand)" : "var(--line)"}`, background: form.payment === item.id ? "rgba(217,70,30,.08)" : "transparent", fontWeight: 700 }}>{item[lang]}</button>
                ))}
              </div>
              <button className="btn btn-primary btn-lg" onClick={validateDetails}>{lang === "fa" ? "ادامه و تأیید" : "Continue & verify"} <Ico.Arrow /></button>
            </div>
          ) : (
            <div style={{ display: "flex", flexDirection: "column", gap: 16, textAlign: "center" }}>
              <p style={{ margin: 0, color: "var(--ink-3)" }}>{lang === "fa" ? <>کد ارسال‌شده به <b dir="ltr">{toFa(form.phone)}</b> را وارد کن.</> : <>Enter the code sent to <b>{form.phone}</b>.</>}</p>
              <div className="chip gold" style={{ alignSelf: "center" }}>{lang === "fa" ? "نسخه آزمایشی: کد ۱۲۳۴" : "Demo: use code 1234"}</div>
              <input autoFocus value={otp} onChange={e => { setOtp(toEn(e.target.value).replace(/\D/g, "").slice(0, 4)); setErrors({}); }} onKeyDown={e => e.key === "Enter" && confirm()} inputMode="numeric" maxLength={4} aria-label={lang === "fa" ? "کد تأیید" : "Verification code"} style={{ ...checkoutInputStyle, width: 180, alignSelf: "center", textAlign: "center", fontSize: 30, letterSpacing: ".35em" }} />
              {errors.otp && <div role="alert" style={{ color: "var(--brand-deep)", fontSize: 13, fontWeight: 700 }}>{errors.otp}</div>}
              <button className="btn btn-primary btn-lg" disabled={submitting || otp.length < 4} onClick={confirm}>{submitting ? (lang === "fa" ? "در حال ثبت…" : "Placing order…") : (lang === "fa" ? "ثبت نهایی سفارش" : "Place order")}</button>
              <button className="btn btn-ghost" disabled={submitting} onClick={() => setStep("details")}>{lang === "fa" ? "ویرایش اطلاعات" : "Edit details"}</button>
            </div>
          )}
        </div>
      </section>
    </>
  );
}

function CheckoutField({ label, error, children }) {
  return <label style={{ display: "flex", flexDirection: "column", gap: 6 }}>
    <span style={{ fontSize: 12, fontWeight: 700, color: "var(--ink-3)" }}>{label}</span>
    {children}
    {error && <span role="alert" style={{ color: "var(--brand-deep)", fontSize: 12, fontWeight: 700 }}>{error}</span>}
  </label>;
}

const checkoutInputStyle = { width: "100%", padding: "13px 15px", borderRadius: 13, border: "1.5px solid var(--ink)", background: "var(--paper)", fontSize: 15, outline: "none" };

window.CheckoutModal = CheckoutModal;
