/* eslint-disable */
/* ============================================================
   PETICOTA — Cart (shared between index.html & tasarla.html)
   Uses localStorage, exposes useCart() + <CartDrawer/>
============================================================ */

const CART_KEY = "peticota.cart.v1";

/* ============================================================
   GOOGLE SHEETS BRIDGE
   ----------------------------------------------------------
   Apps Script Web App URL'sini buraya yapıştırın.
   Boş kalsa bile site çalışmaya devam eder; sadece Sheet'e
   yazılmaz. Kurulum talimatı için: apps-script.gs dosyası.
============================================================ */
const SHEETS_ENDPOINT = "https://script.google.com/macros/s/AKfycbxiTXKQvaLLTOGa10zN-zfskqlDugOrCyy_4Cw9afALEilAR6NBHrxdJRvwaUL_MshBVQ/exec";

/* ============================================================
   CLOUDFLARE TURNSTILE (CAPTCHA)
   Site key public — JS'de görünür olması normal/gerekli.
   Secret key sadece Apps Script tarafında.
============================================================ */
const TURNSTILE_SITE_KEY = "0x4AAAAAADSSg_EtwZNGsoqS";

function TurnstileWidget({ onToken, theme = "auto", size = "normal" }) {
  const ref = React.useRef(null);
  const idRef = React.useRef(null);
  React.useEffect(() => {
    let cancelled = false;
    const tryRender = () => {
      if (cancelled) return;
      if (!window.turnstile || !ref.current) {
        setTimeout(tryRender, 200);
        return;
      }
      if (idRef.current) return;
      try {
        idRef.current = window.turnstile.render(ref.current, {
          sitekey: TURNSTILE_SITE_KEY,
          theme,
          size,
          callback: (token) => onToken(token),
          "error-callback": () => onToken(""),
          "expired-callback": () => onToken(""),
          "timeout-callback": () => onToken("")
        });
      } catch (e) {
        console.error("Turnstile render failed:", e);
      }
    };
    tryRender();
    return () => {
      cancelled = true;
      if (idRef.current && window.turnstile) {
        try { window.turnstile.remove(idRef.current); } catch (e) {}
        idRef.current = null;
      }
    };
  }, []);
  return <div ref={ref} className="turnstile-widget"></div>;
}

async function pushToSheet(payload) {
  if (!SHEETS_ENDPOINT) {
    console.warn("[pushToSheet] SHEETS_ENDPOINT boş, atlanıyor");
    return { ok: false, skipped: true };
  }
  try {
    // Apps Script tarafı JSON.parse(e.postData.contents) ile okuyor →
    // gövdeyi düz JSON string olarak gönderiyoruz.
    // Content-Type: text/plain CORS-safelisted olduğu için preflight
    // tetiklenmez ve Apps Script /exec endpoint'i cevapla beraber
    // Access-Control-Allow-Origin: * gönderdiği için cevabı OKUYABİLİRİZ.
    // Eskisi gibi no-cors KULLANMIYORUZ — yoksa sunucu hatası geldiğinde
    // sessizce yutuluyordu.
    const res = await fetch(SHEETS_ENDPOINT, {
      method: "POST",
      headers: { "Content-Type": "text/plain;charset=utf-8" },
      body: JSON.stringify(payload),
      redirect: "follow"
    });
    const text = await res.text();
    let data = null;
    try { data = JSON.parse(text); } catch (_) {}
    if (!res.ok) {
      console.error("[pushToSheet] HTTP", res.status, text.slice(0, 500));
      return { ok: false, status: res.status, body: text };
    }
    if (data && data.ok === false) {
      console.error("[pushToSheet] sunucu hatası:", data);
      return { ok: false, server: data };
    }
    console.log("[pushToSheet] OK", data || text.slice(0, 200));
    return { ok: true, data };
  } catch (e) {
    console.error("[pushToSheet] network/CORS hatası:", e);
    return { ok: false, error: String(e) };
  }
}

// Konsoldan elle test etmek için:
//   pushToSheet({type:"whitelist", email:"deneme@x.com", lang:"tr", source:"console"})

Object.assign(window, { SHEETS_ENDPOINT, pushToSheet, TURNSTILE_SITE_KEY, TurnstileWidget });

/* ============================================================
   THEME TOGGLE (light ↔ dark)
   Lives in the nav next to the lang toggle.
   Persists to localStorage.peticota.theme.
   System preference is the default — set by the inline init
   script in each HTML file, before paint.
============================================================ */
function ThemeToggle() {
  const [theme, setTheme] = React.useState(() => {
    if (typeof document !== "undefined") {
      return document.documentElement.getAttribute("data-theme") || "light";
    }
    return "light";
  });
  React.useEffect(() => {
    document.documentElement.setAttribute("data-theme", theme);
    try { localStorage.setItem("peticota.theme", theme); } catch (e) {}
  }, [theme]);
  const isDark = theme === "dark";
  const toggle = () => setTheme(isDark ? "light" : "dark");
  return (
    <button
      className="theme-toggle"
      onClick={toggle}
      aria-label={isDark ? "Aydınlık temaya geç" : "Karanlık temaya geç"}
      title={isDark ? "Aydınlık tema" : "Karanlık tema"}
    >
      {isDark ? (
        /* sun */
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="square" strokeLinejoin="miter" aria-hidden="true">
          <circle cx="12" cy="12" r="4"></circle>
          <path d="M12 2v2M12 20v2M4 12H2M22 12h-2M5 5l1.4 1.4M17.6 17.6L19 19M5 19l1.4-1.4M17.6 6.4L19 5"></path>
        </svg>
      ) : (
        /* moon */
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="square" strokeLinejoin="miter" aria-hidden="true">
          <path d="M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8z"></path>
        </svg>
      )}
    </button>
  );
}

Object.assign(window, { ThemeToggle });

const cartRead = () => {
  try {
    const raw = localStorage.getItem(CART_KEY);
    if (!raw) return [];
    const arr = JSON.parse(raw);
    return Array.isArray(arr) ? arr : [];
  } catch (e) { return []; }
};
const cartWrite = (arr) => {
  try { localStorage.setItem(CART_KEY, JSON.stringify(arr)); } catch (e) {}
  window.dispatchEvent(new CustomEvent("peticota:cart-changed"));
};

function useCart() {
  const [items, setItems] = React.useState(() => cartRead());
  React.useEffect(() => {
    const onChange = () => setItems(cartRead());
    window.addEventListener("peticota:cart-changed", onChange);
    window.addEventListener("storage", onChange);
    return () => {
      window.removeEventListener("peticota:cart-changed", onChange);
      window.removeEventListener("storage", onChange);
    };
  }, []);
  const add = (item) => {
    const cur = cartRead();
    cur.push({ ...item, id: item.id || `it_${Date.now()}_${Math.random().toString(36).slice(2,6)}` });
    cartWrite(cur);
  };
  const remove = (id) => cartWrite(cartRead().filter((x) => x.id !== id));
  const setQty = (id, q) =>
    cartWrite(
      cartRead().map((x) => (x.id === id ? { ...x, qty: Math.max(1, q) } : x))
    );
  const clear = () => cartWrite([]);
  const count = items.reduce((s, x) => s + (x.qty || 1), 0);
  const subtotal = items.reduce((s, x) => s + (x.price || 0) * (x.qty || 1), 0);
  return { items, add, remove, setQty, clear, count, subtotal };
}

/* ============================================================
   CART BUTTON & DRAWER
============================================================ */
function CartButton({ lang }) {
  const { count } = useCart();
  const open = () => window.dispatchEvent(new CustomEvent("peticota:cart-open"));
  const label = lang === "en" ? "Cart" : "Sepet";
  return (
    <button className="cart-btn" onClick={open}>
      {label} · {count}
    </button>
  );
}

function CartDrawer({ lang = "tr" }) {
  const { items, remove, setQty, subtotal, clear } = useCart();
  const [open, setOpen] = React.useState(false);
  React.useEffect(() => {
    const onOpen = () => setOpen(true);
    window.addEventListener("peticota:cart-open", onOpen);
    return () => window.removeEventListener("peticota:cart-open", onOpen);
  }, []);
  React.useEffect(() => {
    document.body.style.overflow = open ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [open]);

  const T = lang === "en"
    ? { title: "Cart", empty: "Your cart is empty.", emptyCta: "Browse products",
        subtotal: "Subtotal", checkout: "Checkout", clear: "Clear", remove: "Remove",
        note: "Production: 7 — 10 working days · Free shipping within Türkiye" }
    : { title: "Sepet", empty: "Sepetin boş.", emptyCta: "Ürünleri keşfet",
        subtotal: "Ara toplam", checkout: "Siparişi tamamla", clear: "Temizle", remove: "Sil",
        note: "Üretim: 7 — 10 iş günü · Türkiye içi kargo ücretsiz" };

  return (
    <>
      <div className={`cart-overlay ${open ? "open" : ""}`} onClick={() => setOpen(false)}></div>
      <aside className={`cart-drawer ${open ? "open" : ""}`} aria-hidden={!open}>
        <header className="cart-head">
          <div>
            <span className="mono" style={{ color: "var(--muted)" }}>Nº 00 — {T.title}</span>
            <h3 className="display" style={{ fontSize: 56, marginTop: 6 }}>
              {T.title}<span style={{ color: "var(--red)" }}>.</span>
            </h3>
          </div>
          <button className="cart-close" aria-label="close" onClick={() => setOpen(false)}>×</button>
        </header>

        {items.length === 0 ? (
          <div className="cart-empty">
            <p className="serif" style={{ fontSize: 22, lineHeight: 1.4 }}>{T.empty}</p>
            <a className="btn btn-red" href="index.html#products" onClick={() => setOpen(false)}>
              {T.emptyCta} <span className="arr">→</span>
            </a>
          </div>
        ) : (
          <>
            <ul className="cart-list">
              {items.map((it) => (
                <li className="cart-item" key={it.id}>
                  <div className="cart-item-swatch" style={{ background: it.swatch || "#0b0b08" }}>
                    <span className="mono">{(it.code || "P")}</span>
                  </div>
                  <div className="cart-item-info">
                    <div className="mono" style={{ color: "var(--muted)" }}>{it.kind}</div>
                    <div className="display" style={{ fontSize: 26, lineHeight: 1 }}>{it.name}</div>
                    <div className="mono" style={{ fontSize: 10, marginTop: 6, lineHeight: 1.6 }}>
                      {it.size ? <>{lang==="en"?"Size":"Beden"}: <b>{it.size}</b> · </> : null}
                      {it.color ? <>{lang==="en"?"Color":"Renk"}: <b>{it.color}</b></> : null}
                      {it.plate ? <> · ID: <b>{it.plate}</b></> : null}
                    </div>
                    <div className="cart-item-row">
                      <div className="qty-ctrl">
                        <button onClick={() => {
                          if ((it.qty || 1) <= 1) remove(it.id);
                          else setQty(it.id, (it.qty || 1) - 1);
                        }}>−</button>
                        <span>{it.qty || 1}</span>
                        <button onClick={() => setQty(it.id, (it.qty||1) + 1)}>+</button>
                      </div>
                      <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
                        <span className="display" style={{ fontSize: 22 }}>
                          ₺ {((it.price||0)*(it.qty||1)).toLocaleString("tr-TR")}
                        </span>
                        <button className="cart-remove" aria-label={T.remove} title={T.remove} onClick={() => remove(it.id)}>
                          <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="square" strokeLinejoin="miter" aria-hidden="true">
                            <path d="M4 7h16"></path>
                            <path d="M9 7V4h6v3"></path>
                            <path d="M6 7l1 13h10l1-13"></path>
                            <path d="M10 11v6"></path>
                            <path d="M14 11v6"></path>
                          </svg>
                        </button>
                      </div>
                    </div>
                  </div>
                </li>
              ))}
            </ul>

            <footer className="cart-foot">
              <div className="cart-subtotal">
                <span className="mono">{T.subtotal}</span>
                <span className="display" style={{ fontSize: 48 }}>
                  ₺ {subtotal.toLocaleString("tr-TR")}
                </span>
              </div>
              <p className="mono" style={{ color: "var(--muted)", marginBottom: 14 }}>{T.note}</p>
              <button className="btn btn-red" style={{ width: "100%", justifyContent: "center" }}
                onClick={() => { window.location.href = "siparis.html"; }}>
                {T.checkout} <span className="arr">→</span>
              </button>
              <button className="cart-clear" onClick={clear}>{T.clear}</button>
            </footer>
          </>
        )}
      </aside>
    </>
  );
}

/* ============================================================
   Toast — used after add to cart
============================================================ */
function showCartToast(name, lang = "tr") {
  const wrap = document.createElement("div");
  wrap.className = "cart-toast";
  wrap.innerHTML = `
    <span class="mono">${lang === "en" ? "Added" : "Sepete eklendi"}</span>
    <span class="display">${name}</span>
    <button>${lang === "en" ? "View cart →" : "Sepete bak →"}</button>
  `;
  document.body.appendChild(wrap);
  requestAnimationFrame(() => wrap.classList.add("in"));
  const btn = wrap.querySelector("button");
  btn.onclick = () => { window.dispatchEvent(new CustomEvent("peticota:cart-open")); wrap.classList.remove("in"); setTimeout(() => wrap.remove(), 400); };
  setTimeout(() => { wrap.classList.remove("in"); setTimeout(() => wrap.remove(), 400); }, 3200);
}

Object.assign(window, { useCart, CartButton, CartDrawer, showCartToast });
