// checkout.jsx — sepet sayfası, ödeme (checkout) formu ve sipariş sonucu sayfası
const { useState: useStateCo, useEffect: useEffectCo } = React;

function CartLineItem({ item, lang }) {
  const cart = useCart();
  const imgUrl = item.imagePath ? productImageUrl(item.imagePath) : null;
  return (
    <div className="flex flex-wrap sm:flex-nowrap items-center gap-4 rounded-[16px] bg-white p-4" style={{ boxShadow: "0 10px 30px -22px rgba(45,55,72,0.3)" }}>
      {imgUrl
        ? <img src={imgUrl} alt={item.label || item.name} className="rounded-[10px] object-cover shrink-0 w-16 h-16" />
        : <Placeholder label="" tone={item.tone} rounded="rounded-[10px]" className="shrink-0 w-16 h-16" />}
      <div className="flex-1 min-w-[140px]">
        <a href={`/urun/${item.slug}`} className="text-ink hover:text-ink/70 transition-colors" style={{ fontSize: 15.5, fontWeight: 600 }}>{item.name}</a>
        <div className="text-ink/50 mt-1" style={{ fontSize: 13 }}>{formatPriceTRY(item.priceKurus)} {lang === "tr" ? "/ adet" : "each"}</div>
      </div>
      <button onClick={() => cart.removeItem(item.slug)} aria-label={lang === "tr" ? "Kaldır" : "Remove"}
        className="text-ink/40 hover:text-red-600 transition-colors shrink-0 order-1 sm:order-none">
        <Icon name="close" size={18} />
      </button>
      <div className="w-full sm:w-auto flex items-center justify-between sm:justify-end gap-4 order-2 sm:order-none">
        <Stepper qty={item.qty} setQty={(q) => cart.updateQty(item.slug, q)} label="" />
        <div className="text-ink text-right shrink-0" style={{ width: 84, fontSize: 15, fontWeight: 600 }}>
          {formatPriceTRY(item.priceKurus * item.qty)}
        </div>
      </div>
    </div>
  );
}

function CartPage({ lang, setLang }) {
  const c = window.CONTENT[lang];
  const cart = useCart();
  useEffectCo(() => { window.scrollTo(0, 0); }, []);

  return (
    <div style={{ backgroundColor: "#faf7f2" }}>
      <Nav c={c} lang={lang} setLang={setLang} />
      <main className="pt-[110px] lg:pt-[128px] pb-28">
        <section className="mx-auto max-w-[880px] px-6 lg:px-10">
          <nav className="flex items-center gap-2 text-ink/45" style={{ fontSize: 13 }}>
            <a href="/" className="hover:text-ink transition-colors">{c.pdp.home}</a>
            <span>/</span>
            <span className="text-ink/70">{lang === "tr" ? "Sepetim" : "Your Cart"}</span>
          </nav>
          <h1 className="font-serif text-ink mt-6 mb-10" style={{ fontSize: "clamp(28px,3.6vw,42px)", lineHeight: 1.12, letterSpacing: "-0.01em" }}>
            {lang === "tr" ? "Sepetim" : "Your Cart"}
          </h1>

          {cart.items.length === 0 ? (
            <div className="text-center py-20">
              <p className="text-ink/55" style={{ fontSize: 15.5 }}>{lang === "tr" ? "Sepetiniz şu anda boş." : "Your cart is currently empty."}</p>
              <a href="/urunler" className="mt-6 inline-flex items-center gap-2 rounded-full px-7 py-3.5 text-cream transition-all duration-300 hover:gap-3"
                style={{ backgroundColor: "#2d3748", fontSize: 14.5 }}>
                {lang === "tr" ? "Ürünleri Keşfet" : "Explore Products"}<Icon name="arrowRight" size={15} />
              </a>
            </div>
          ) : (
            <>
              <div className="space-y-4">
                {cart.items.map((item) => <CartLineItem key={item.slug} item={item} lang={lang} />)}
              </div>

              <div className="mt-8 pt-6 space-y-2" style={{ borderTop: "1px solid rgba(45,55,72,0.12)" }}>
                <div className="flex items-center justify-between text-ink/70" style={{ fontSize: 14.5 }}>
                  <span>{lang === "tr" ? "Ara Toplam" : "Subtotal"}</span>
                  <span>{formatPriceTRY(cart.totalKurus)}</span>
                </div>
                <div className="flex items-center justify-between text-ink/70" style={{ fontSize: 14.5 }}>
                  <span>{lang === "tr" ? "Kargo" : "Shipping"}</span>
                  <span>{cart.shippingKurus === 0
                    ? <span className="text-sage-deep" style={{ fontWeight: 600 }}>{lang === "tr" ? "Ücretsiz" : "Free"}</span>
                    : formatPriceTRY(cart.shippingKurus)}</span>
                </div>
                <div className="flex items-center justify-between pt-2">
                  <span className="text-ink" style={{ fontSize: 16, fontWeight: 600 }}>{lang === "tr" ? "Toplam" : "Total"}</span>
                  <span className="font-serif text-ink" style={{ fontSize: 26 }}>{formatPriceTRY(cart.grandTotalKurus)}</span>
                </div>
              </div>
              <p className="mt-2 text-ink/45" style={{ fontSize: 12.5 }}>
                {lang === "tr"
                  ? `${formatPriceTRY(FREE_SHIPPING_THRESHOLD_KURUS)} ve üzeri siparişlerde kargo ücretsizdir. Siparişiniz, ödeme onayının ardından 2 iş günü içinde kargoya verilir.`
                  : `Free shipping on orders over ${formatPriceTRY(FREE_SHIPPING_THRESHOLD_KURUS)}. Orders ship within 2 business days of payment confirmation.`}
              </p>

              <a href="/odeme" className="mt-7 flex items-center justify-center gap-2.5 rounded-full px-7 py-4 text-cream transition-all duration-300 hover:gap-3.5"
                style={{ backgroundColor: "#2d3748", fontSize: 15.5 }}>
                {lang === "tr" ? "Ödemeye Geç" : "Proceed to Checkout"}<Icon name="arrowRight" size={16} />
              </a>
            </>
          )}
        </section>
      </main>
      <Footer c={c} />
    </div>
  );
}

function CheckoutPage({ lang, setLang }) {
  const c = window.CONTENT[lang];
  const cart = useCart();
  const [form, setForm] = useStateCo({ name: "", email: "", phone: "", il: "", ilce: "", addressDetail: "" });
  const [paymentMethod, setPaymentMethod] = useStateCo("havale");
  const [acceptDistance, setAcceptDistance] = useStateCo(false);
  const [acceptPreinfo, setAcceptPreinfo] = useStateCo(false);
  const [busy, setBusy] = useStateCo(false);
  const [error, setError] = useStateCo("");
  const [submitted, setSubmitted] = useStateCo(false);

  useEffectCo(() => { window.scrollTo(0, 0); }, []);

  function set(field, value) { setForm((f) => ({ ...f, [field]: value })); }

  function setIl(il) {
    setForm((f) => ({ ...f, il, ilce: "" }));
  }

  const ilceler = (window.TR_LOCATIONS.find((x) => x.il === form.il) || {}).ilceler || [];

  async function submit(e) {
    e.preventDefault();
    setBusy(true);
    setError("");
    try {
      const fullAddress = `${form.addressDetail} — ${form.ilce}/${form.il}`;
      const { data, error: fnError } = await window.sb.functions.invoke("create-order", {
        body: {
          lang,
          payment_method: paymentMethod,
          agreements_accepted: acceptDistance && acceptPreinfo,
          customer: { name: form.name, email: form.email, phone: form.phone, address: fullAddress },
          items: cart.items.map((x) => ({ slug: x.slug, qty: x.qty })),
        },
      });
      if (fnError) throw fnError;
      if (!data || !data.orderId) throw new Error(lang === "tr" ? "Sipariş oluşturulamadı." : "Order could not be created.");
      setSubmitted(true);
      cart.clear();
      window.appNavigate(`/siparis-basarili/${data.orderId}?odeme=${paymentMethod}`);
    } catch (err) {
      setBusy(false);
      setError(err.message || String(err));
    }
  }

  const inputCls = "w-full rounded-[12px] px-4 py-3";
  const inputStyle = { border: "1px solid rgba(45,55,72,0.16)", fontSize: 14.5 };
  const label = (txt) => <label className="block text-ink/60 mb-1.5" style={{ fontSize: 13 }}>{txt}</label>;

  if (cart.items.length === 0 && !submitted) {
    return (
      <div style={{ backgroundColor: "#faf7f2" }}>
        <Nav c={c} lang={lang} setLang={setLang} />
        <div className="pt-[160px] pb-40 text-center">
          <p className="text-ink/55" style={{ fontSize: 15.5 }}>{lang === "tr" ? "Sepetiniz boş." : "Your cart is empty."}</p>
          <a href="/urunler" className="mt-6 inline-flex items-center gap-2 rounded-full px-7 py-3.5 text-cream" style={{ backgroundColor: "#2d3748", fontSize: 14.5 }}>
            {lang === "tr" ? "Ürünleri Keşfet" : "Explore Products"}
          </a>
        </div>
        <Footer c={c} />
      </div>
    );
  }

  return (
    <div style={{ backgroundColor: "#faf7f2" }}>
      <Nav c={c} lang={lang} setLang={setLang} />
      <main className="pt-[110px] lg:pt-[128px] pb-28">
        <section className="mx-auto max-w-[1080px] px-6 lg:px-10">
          <nav className="flex items-center gap-2 text-ink/45" style={{ fontSize: 13 }}>
            <a href="/" className="hover:text-ink transition-colors">{c.pdp.home}</a>
            <span>/</span>
            <a href="/sepet" className="hover:text-ink transition-colors">{lang === "tr" ? "Sepetim" : "Your Cart"}</a>
            <span>/</span>
            <span className="text-ink/70">{lang === "tr" ? "Ödeme" : "Checkout"}</span>
          </nav>
          <h1 className="font-serif text-ink mt-6 mb-10" style={{ fontSize: "clamp(28px,3.6vw,42px)", lineHeight: 1.12, letterSpacing: "-0.01em" }}>
            {lang === "tr" ? "Ödeme" : "Checkout"}
          </h1>

          <div className="grid lg:grid-cols-12 gap-10">
            <form onSubmit={submit} className="lg:col-span-7 space-y-4">
              <div>
                {label(lang === "tr" ? "Ad Soyad" : "Full name")}
                <input required className={inputCls} style={inputStyle} value={form.name} onChange={(e) => set("name", e.target.value)} />
              </div>
              <div className="grid sm:grid-cols-2 gap-4">
                <div>
                  {label("E-posta")}
                  <input required type="email" className={inputCls} style={inputStyle} value={form.email} onChange={(e) => set("email", e.target.value)} />
                </div>
                <div>
                  {label(lang === "tr" ? "Telefon" : "Phone")}
                  <input required type="tel" className={inputCls} style={inputStyle} value={form.phone} onChange={(e) => set("phone", e.target.value)} />
                </div>
              </div>
              <div className="grid sm:grid-cols-2 gap-4">
                <div>
                  {label("İl")}
                  <select required className={inputCls} style={inputStyle} value={form.il} onChange={(e) => setIl(e.target.value)}>
                    <option value="" disabled>{lang === "tr" ? "İl seçin" : "Select province"}</option>
                    {window.TR_LOCATIONS.map((x) => <option key={x.il} value={x.il}>{x.il}</option>)}
                  </select>
                </div>
                <div>
                  {label("İlçe")}
                  <select required disabled={!form.il} className={inputCls} style={inputStyle} value={form.ilce} onChange={(e) => set("ilce", e.target.value)}>
                    <option value="" disabled>{lang === "tr" ? "Önce il seçin" : "Select province first"}</option>
                    {ilceler.map((x) => <option key={x} value={x}>{x}</option>)}
                  </select>
                </div>
              </div>
              <div>
                {label(lang === "tr" ? "Mahalle, Sokak, Kapı No" : "Neighbourhood, street, building no")}
                <textarea required rows={3} className={inputCls} style={inputStyle} value={form.addressDetail} onChange={(e) => set("addressDetail", e.target.value)} />
              </div>

              {/* Ödeme yöntemi */}
              <div>
                {label(lang === "tr" ? "Ödeme Yöntemi" : "Payment method")}
                <div className="grid sm:grid-cols-2 gap-3">
                  <button type="button" onClick={() => setPaymentMethod("havale")}
                    className="rounded-[14px] p-4 text-left transition-all duration-200"
                    style={{
                      border: paymentMethod === "havale" ? "2px solid #2d3748" : "1px solid rgba(45,55,72,0.16)",
                      backgroundColor: paymentMethod === "havale" ? "rgba(155,170,144,0.10)" : "transparent",
                    }}>
                    <span className="flex items-center gap-2 text-ink" style={{ fontSize: 14.5, fontWeight: 600 }}>
                      <Icon name="check" size={16} className={paymentMethod === "havale" ? "text-sage-deep" : "opacity-0"} />
                      {lang === "tr" ? "Havale / EFT" : "Bank transfer"}
                    </span>
                    <span className="block text-ink/55 mt-1" style={{ fontSize: 12.5, lineHeight: 1.5 }}>
                      {lang === "tr"
                        ? "Sipariş sonrası hesap bilgileri iletilir; ödeme 3 iş günü içinde yapılmalıdır."
                        : "Bank details are shared after ordering; payment due within 3 business days."}
                    </span>
                  </button>
                  <div className="rounded-[14px] p-4 opacity-55 cursor-not-allowed select-none"
                    style={{ border: "1px dashed rgba(45,55,72,0.2)" }}
                    title={lang === "tr" ? "Çok yakında" : "Coming soon"}>
                    <span className="flex items-center gap-2 text-ink" style={{ fontSize: 14.5, fontWeight: 600 }}>
                      {lang === "tr" ? "Kredi / Banka Kartı" : "Credit / debit card"}
                      <span className="rounded-full px-2 py-0.5 text-cream" style={{ fontSize: 10.5, backgroundColor: "#a87d79" }}>
                        {lang === "tr" ? "yakında" : "soon"}
                      </span>
                    </span>
                    <span className="block text-ink/55 mt-1" style={{ fontSize: 12.5, lineHeight: 1.5 }}>
                      {lang === "tr" ? "iyzico güvenli ödeme altyapısıyla — çok yakında." : "Via iyzico secure checkout — coming very soon."}
                    </span>
                  </div>
                </div>
              </div>

              {/* Sözleşme onayları — işaretlenmeden sipariş verilemez */}
              <div className="space-y-2.5 rounded-[14px] p-4" style={{ border: "1px solid rgba(45,55,72,0.12)", backgroundColor: "rgba(250,247,242,0.6)" }}>
                <label className="flex items-start gap-3 cursor-pointer text-ink/70" style={{ fontSize: 13, lineHeight: 1.6 }}>
                  <input type="checkbox" required checked={acceptDistance} onChange={(e) => setAcceptDistance(e.target.checked)}
                    className="mt-0.5 shrink-0" style={{ width: 16, height: 16, accentColor: "#2d3748" }} />
                  <span>
                    {lang === "tr"
                      ? <><a href="/mesafeli-satis-sozlesmesi" target="_blank" rel="noopener" className="underline hover:text-ink transition-colors">Mesafeli Satış Sözleşmesi</a>'ni okudum ve kabul ediyorum.</>
                      : <>I have read and accept the <a href="/mesafeli-satis-sozlesmesi" target="_blank" rel="noopener" className="underline hover:text-ink transition-colors">Distance Sales Agreement</a>.</>}
                  </span>
                </label>
                <label className="flex items-start gap-3 cursor-pointer text-ink/70" style={{ fontSize: 13, lineHeight: 1.6 }}>
                  <input type="checkbox" required checked={acceptPreinfo} onChange={(e) => setAcceptPreinfo(e.target.checked)}
                    className="mt-0.5 shrink-0" style={{ width: 16, height: 16, accentColor: "#2d3748" }} />
                  <span>
                    {lang === "tr"
                      ? <><a href="/on-bilgilendirme-formu" target="_blank" rel="noopener" className="underline hover:text-ink transition-colors">Ön Bilgilendirme Formu</a>'nu okudum ve kabul ediyorum.</>
                      : <>I have read and accept the <a href="/on-bilgilendirme-formu" target="_blank" rel="noopener" className="underline hover:text-ink transition-colors">Pre-Contract Information</a>.</>}
                  </span>
                </label>
              </div>

              {error && <p className="text-red-600" style={{ fontSize: 13.5 }}>{error}</p>}

              <button type="submit" disabled={busy || !acceptDistance || !acceptPreinfo}
                className="w-full mt-2 flex items-center justify-center gap-2.5 rounded-full px-7 py-4 text-cream transition-all duration-300 disabled:opacity-50 disabled:cursor-not-allowed"
                style={{ backgroundColor: "#2d3748", fontSize: 15.5 }}>
                {busy ? (lang === "tr" ? "Sipariş oluşturuluyor…" : "Placing order…") : (lang === "tr" ? "Siparişi Tamamla" : "Place Order")}
              </button>
              {(!acceptDistance || !acceptPreinfo) && (
                <p className="text-ink/45 text-center" style={{ fontSize: 12.5 }}>
                  {lang === "tr"
                    ? "Siparişi tamamlamak için sözleşmeleri okuyup onaylamanız gerekir."
                    : "Please read and accept the agreements to place your order."}
                </p>
              )}
            </form>

            <div className="lg:col-span-5">
              <div className="rounded-[18px] bg-white p-6" style={{ boxShadow: "0 20px 50px -30px rgba(45,55,72,0.25)" }}>
                <h3 className="uppercase text-ink/45 mb-4" style={{ fontSize: 11, letterSpacing: "0.2em" }}>
                  {lang === "tr" ? "Sipariş Özeti" : "Order Summary"}
                </h3>
                <div className="space-y-3">
                  {cart.items.map((it) => (
                    <div key={it.slug} className="flex items-center justify-between" style={{ fontSize: 14 }}>
                      <span className="text-ink/75">{it.qty} × {it.name}</span>
                      <span className="text-ink">{formatPriceTRY(it.priceKurus * it.qty)}</span>
                    </div>
                  ))}
                </div>
                <div className="mt-4 pt-4 space-y-2" style={{ borderTop: "1px solid rgba(45,55,72,0.1)" }}>
                  <div className="flex items-center justify-between text-ink/70" style={{ fontSize: 13.5 }}>
                    <span>{lang === "tr" ? "Ara Toplam" : "Subtotal"}</span>
                    <span>{formatPriceTRY(cart.totalKurus)}</span>
                  </div>
                  <div className="flex items-center justify-between text-ink/70" style={{ fontSize: 13.5 }}>
                    <span>{lang === "tr" ? "Kargo" : "Shipping"}</span>
                    <span>{cart.shippingKurus === 0
                      ? <span className="text-sage-deep" style={{ fontWeight: 600 }}>{lang === "tr" ? "Ücretsiz" : "Free"}</span>
                      : formatPriceTRY(cart.shippingKurus)}</span>
                  </div>
                  <div className="flex items-center justify-between pt-1.5">
                    <span className="text-ink" style={{ fontWeight: 600 }}>{lang === "tr" ? "Toplam" : "Total"}</span>
                    <span className="font-serif text-ink" style={{ fontSize: 22 }}>{formatPriceTRY(cart.grandTotalKurus)}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </section>
      </main>
      <Footer c={c} />
    </div>
  );
}

function OrderResultPage({ status, orderId, lang, setLang }) {
  const c = window.CONTENT[lang];
  useEffectCo(() => { window.scrollTo(0, 0); }, []);

  const success = status === "success";
  const isHavale = new URLSearchParams(window.location.search).get("odeme") === "havale";
  const waMsg = encodeURIComponent(
    lang === "tr"
      ? `Merhaba, ${orderId ? orderId.slice(0, 8) : ""} numaralı siparişim için havale bilgilerini alabilir miyim?`
      : `Hello, could I get the bank transfer details for my order ${orderId ? orderId.slice(0, 8) : ""}?`
  );
  return (
    <div style={{ backgroundColor: "#faf7f2" }}>
      <Nav c={c} lang={lang} setLang={setLang} />
      <main className="pt-[130px] lg:pt-[150px] pb-32">
        <section className="mx-auto max-w-[600px] px-6 lg:px-10 text-center">
          <span className="inline-flex items-center justify-center rounded-full mx-auto"
            style={{ width: 64, height: 64, backgroundColor: success ? "rgba(155,170,144,0.18)" : "rgba(194,64,64,0.12)" }}>
            <Icon name={success ? "check" : "close"} size={28} className={success ? "text-sage-deep" : ""} style={!success ? { color: "#b23c3c" } : undefined} />
          </span>
          <h1 className="font-serif text-ink mt-6" style={{ fontSize: "clamp(26px,3.4vw,38px)", lineHeight: 1.15 }}>
            {success
              ? (lang === "tr" ? "Siparişiniz alındı!" : "Your order has been received!")
              : (lang === "tr" ? "Sipariş tamamlanamadı" : "Order could not be completed")}
          </h1>
          <p className="text-ink/60 mt-4" style={{ fontSize: 15.5, lineHeight: 1.7 }}>
            {success
              ? (lang === "tr"
                  ? "Siparişiniz kaydedildi, en kısa sürede sizinle iletişime geçeceğiz."
                  : "Your order has been recorded — we'll be in touch with you shortly.")
              : (lang === "tr"
                  ? "Bir sorun oluştu. Lütfen tekrar deneyin ya da bizimle WhatsApp üzerinden iletişime geçin."
                  : "Something went wrong. Please try again or reach us on WhatsApp.")}
          </p>
          {success && orderId && (
            <p className="text-ink/40 mt-3" style={{ fontSize: 12.5 }}>{lang === "tr" ? "Sipariş no" : "Order ID"}: {orderId}</p>
          )}
          {success && isHavale && (
            <div className="mt-7 rounded-[16px] p-5 text-left" style={{ backgroundColor: "rgba(155,170,144,0.13)" }}>
              <h3 className="text-ink" style={{ fontSize: 14.5, fontWeight: 600 }}>
                {lang === "tr" ? "Havale / EFT ile ödeme" : "Paying by bank transfer"}
              </h3>
              <p className="text-ink/65 mt-2" style={{ fontSize: 13.5, lineHeight: 1.7 }}>
                {lang === "tr"
                  ? "Hesap bilgilerimiz (IBAN), sipariş numaranızla birlikte WhatsApp veya telefon üzerinden size iletilecektir. Ödemenizin açıklama kısmına sipariş numaranızı yazmanız yeterli. Ödeme onaylandıktan sonra siparişiniz 2 iş günü içinde kargoya verilir."
                  : "Our bank details (IBAN) will be sent to you via WhatsApp or phone together with your order number. Simply include the order number in the payment note. Once payment is confirmed, your order ships within 2 business days."}
              </p>
              <a href={`https://wa.me/905416067890?text=${waMsg}`} target="_blank" rel="noopener noreferrer"
                className="mt-4 inline-flex items-center gap-2 rounded-full px-5 py-2.5 text-cream transition-all duration-300 hover:gap-3"
                style={{ backgroundColor: "#25D366", fontSize: 13.5, fontWeight: 500 }}>
                {lang === "tr" ? "WhatsApp'tan hesap bilgisi iste" : "Request bank details on WhatsApp"}
              </a>
            </div>
          )}
          {success && !isHavale && (
            <p className="text-ink/50 mt-4" style={{ fontSize: 13.5 }}>
              {lang === "tr" ? "Siparişiniz, ödeme onayının ardından 2 iş günü içinde kargoya verilir." : "Your order ships within 2 business days of payment confirmation."}
            </p>
          )}
          <a href="/urunler" className="mt-8 inline-flex items-center gap-2 rounded-full px-7 py-3.5 text-cream transition-all duration-300 hover:gap-3"
            style={{ backgroundColor: "#2d3748", fontSize: 14.5 }}>
            {lang === "tr" ? "Alışverişe Devam Et" : "Continue Shopping"}<Icon name="arrowRight" size={15} />
          </a>
        </section>
      </main>
      <Footer c={c} />
    </div>
  );
}

Object.assign(window, { CartPage, CheckoutPage, OrderResultPage });
