/* eslint-disable */
/* ============================================================
   PETICOTA — Designer (tasarla.html)
   Step 1: choose product
   Step 2: live customize with flash animation
============================================================ */
const { useState, useEffect, useRef, useMemo } = React;

const D_COPY = {
  tr: {
    nav: ["Ana Sayfa", "Ürünler", "Tasarla", "Hikaye", "İletişim"],
    eyebrow: "Nº 03 — Tasarımcı",
    headline: ["Kendi", { em: "edisyonunu" }, "tasarla."],
    sub: "Önce modeli seç. Sonra renk, beden, dikiş ve isim plakası ile kendine özgü kıl. Üretim İstanbul atölyesinde 7 — 10 iş günü içinde el yapımı.",
    choices: [
      { kind: "Tasma", num: "Nº 01", name: ["Boyun", { em: "Tasması" }], img: "https://peticota.com/wp-content/uploads/2025/12/2.png", meta: ["XS — XL", "Başlangıç ₺ 1.290"], cta: "Tasma tasarla" },
      { kind: "Kayış", num: "Nº 02", name: ["Gezdirme", { em: "Kayışı" }], img: "https://peticota.com/wp-content/uploads/2025/12/unnamed-4-2-e1767014417477.jpg", meta: ["120 — 200 cm", "Başlangıç ₺ 1.490"], cta: "Kayış tasarla" }
    ],
    back: "← Modeli değiştir",
    builderTitle: { collar: ["Boyun", { em: "Tasması" }], leash: ["Gezdirme", { em: "Kayışı" }] },
    labels: {
      size: "Beden",
      length: "Uzunluk",
      color: "Renk",
      finish: "Doku",
      stitch: "Dikiş",
      plate: "İsim plakası",
      platePh: "DOSTUN İSMİ",
      reflective: "Refleks şerit",
      qr: "Akıllı QR etiket",
      summary: "Özet",
      base: "Baz fiyat",
      addons: "Eklentiler",
      total: "Toplam",
      add: "Sepete ekle",
      production: "Üretim 7 — 10 iş günü",
      stamp: ["Peticota · Bespoke", "Edition Nº 04"]
    },
    sizes: { collar: ["XS", "S", "M", "L", "XL"], leash: ["120 cm", "150 cm", "180 cm", "200 cm"] },
    colors: [
      { c: "#0b0b08", n: "Kömür" },
      { c: "#e1261c", n: "Kızıl" },
      { c: "#c9a371", n: "Buğday" },
      { c: "#3c2a1f", n: "Maun" },
      { c: "#f1ecdf", n: "Krem" },
      { c: "#1a3528", n: "Orman" }
    ],
    finishes: ["Mat", "Yağlı", "Vintage"],
    stitches: ["Ton üstü ton", "Kontrast Krem", "Kontrast Kızıl"],
    addons: { reflective: { name: "Refleks şerit", desc: "Gece görünürlük", price: 120 }, qr: { name: "Akıllı QR etiket", desc: "Acil durumlarda yer bildirimi", price: 240 } }
  },
  en: {
    nav: ["Home", "Products", "Customize", "Story", "Contact"],
    eyebrow: "Nº 03 — Designer",
    headline: ["Design your", { em: "edition" }, "."],
    sub: "Pick the model first. Then color, size, stitching and ID plate make it yours. Hand-made in our Istanbul atelier in 7 — 10 working days.",
    choices: [
      { kind: "Collar", num: "Nº 01", name: ["The", { em: "Collar" }], img: "https://peticota.com/wp-content/uploads/2025/12/2.png", meta: ["XS — XL", "From ₺ 1.290"], cta: "Design the collar" },
      { kind: "Leash", num: "Nº 02", name: ["The", { em: "Leash" }], img: "https://peticota.com/wp-content/uploads/2025/12/unnamed-4-2-e1767014417477.jpg", meta: ["120 — 200 cm", "From ₺ 1.490"], cta: "Design the leash" }
    ],
    back: "← Change model",
    builderTitle: { collar: ["The", { em: "Collar" }], leash: ["The", { em: "Leash" }] },
    labels: {
      size: "Size",
      length: "Length",
      color: "Color",
      finish: "Finish",
      stitch: "Stitching",
      plate: "ID plate",
      platePh: "DOG NAME",
      reflective: "Reflective trim",
      qr: "Smart QR tag",
      summary: "Summary",
      base: "Base price",
      addons: "Add-ons",
      total: "Total",
      add: "Add to cart",
      production: "Production 7 — 10 working days",
      stamp: ["Peticota · Bespoke", "Edition Nº 04"]
    },
    sizes: { collar: ["XS", "S", "M", "L", "XL"], leash: ["120 cm", "150 cm", "180 cm", "200 cm"] },
    colors: [
      { c: "#0b0b08", n: "Charcoal" },
      { c: "#e1261c", n: "Red" },
      { c: "#c9a371", n: "Wheat" },
      { c: "#3c2a1f", n: "Mahogany" },
      { c: "#f1ecdf", n: "Cream" },
      { c: "#1a3528", n: "Forest" }
    ],
    finishes: ["Matte", "Oiled", "Vintage"],
    stitches: ["Tone-on-tone", "Cream contrast", "Red contrast"],
    addons: { reflective: { name: "Reflective trim", desc: "Night visibility", price: 120 }, qr: { name: "Smart QR tag", desc: "Find-me service", price: 240 } }
  }
};

const renderParts = (parts, key = 0) => {
  if (typeof parts === "string") return parts;
  if (Array.isArray(parts))
    return parts.map((p, i) => (
      <React.Fragment key={`${key}-${i}`}>
        {renderParts(p, `${key}-${i}`)}{" "}
      </React.Fragment>
    ));
  if (parts && parts.em) return <em>{parts.em}</em>;
  return null;
};

/* ================================================
   Top nav (lighter than home)
================================================ */
const DNav = ({ lang, setLang }) => (
  <>
    <nav className="nav">
      <a className="logo" href="index.html">
        peticota<span className="dot"></span>
      </a>
      <ul className="nav-links">
        <li><a href="index.html">{lang === "en" ? "Home" : "Ana Sayfa"}</a></li>
        <li><a href="index.html#products">{lang === "en" ? "Products" : "Ürünler"}</a></li>
        <li><a href="tasarla.html" style={{ color: "var(--red)" }}>{lang === "en" ? "Customize" : "Tasarla"}</a></li>
        <li><a href="index.html#manifesto">{lang === "en" ? "Story" : "Hikaye"}</a></li>
      </ul>
      <div className="right">
        <div className="lang-toggle">
          <button className={lang === "tr" ? "active" : ""} onClick={() => setLang("tr")}>TR</button>
          <button className={lang === "en" ? "active" : ""} onClick={() => setLang("en")}>EN</button>
        </div>
        <ThemeToggle />
        <CartButton lang={lang} />
      </div>
    </nav>
    <div className="ticker">
      <div className="ticker-track">
        {[0, 1].map((d) => (
          <span key={d}>
            {(lang === "en"
              ? ["Bespoke", "Made by hand", "7 — 10 days", "Istanbul"]
              : ["Sana Özel", "El Yapımı", "7 — 10 İş Günü", "İstanbul"]
            ).map((x, i) => (
              <span key={i}>{x}</span>
            ))}
          </span>
        ))}
      </div>
    </div>
  </>
);

/* ================================================
   Step 1: Choose product
================================================ */
const Chooser = ({ t, lang, onPick }) => {
  return (
    <section className="chooser">
      <div className="chooser-head">
        <div>
          <span className="chooser-eyebrow">{t.eyebrow}</span>
          <h1 style={{ marginTop: 16 }}>{renderParts(t.headline)}</h1>
        </div>
        <p className="chooser-sub">{t.sub}</p>
      </div>
      <div className="chooser-cards">
        {t.choices.map((c, i) => {
          const k = i === 0 ? "collar" : "leash";
          return (
            <a
              key={i}
              className="choice"
              href={`?p=${k}`}
              onClick={(e) => { e.preventDefault(); onPick(k); }}
            >
              <span className="choice-num">{c.num}</span>
              <div className="choice-img" style={{ backgroundImage: `url('${c.img}')` }}></div>
              <div className="choice-text">
                <h2 className="choice-name">{renderParts(c.name)}</h2>
                <div className="choice-meta">
                  <span>{c.meta[0]} · {c.meta[1]}</span>
                  <span className="choice-go">{c.cta} <span>→</span></span>
                </div>
              </div>
            </a>
          );
        })}
      </div>
    </section>
  );
};

/* ================================================
   Step 2: Builder
================================================ */
const Builder = ({ t, lang, productKey, onBack }) => {
  const basePrice = productKey === "collar" ? 1290 : 1490;
  const productImg = productKey === "collar"
    ? "https://peticota.com/wp-content/uploads/2025/12/2.png"
    : "https://peticota.com/wp-content/uploads/2025/12/unnamed-4-2-e1767014417477.jpg";

  const sizes = productKey === "collar" ? t.sizes.collar : t.sizes.leash;
  const sizeLabelKey = productKey === "collar" ? "size" : "length";

  const [size, setSize] = useState(productKey === "collar" ? "M" : "150 cm");
  const [colorIdx, setColorIdx] = useState(0);
  const [finish, setFinish] = useState(t.finishes[0]);
  const [stitch, setStitch] = useState(t.stitches[0]);
  const [plate, setPlate] = useState("");
  const [reflective, setReflective] = useState(false);
  const [qr, setQr] = useState(productKey === "collar");
  const [flash, setFlash] = useState(false);

  const color = t.colors[colorIdx];

  // flash when key options change
  const fireFlash = () => {
    setFlash(true);
    setTimeout(() => setFlash(false), 180);
  };
  useEffect(() => { fireFlash(); }, [colorIdx, finish, stitch, productKey]);

  const addonsTotal =
    (reflective ? t.addons.reflective.price : 0) +
    (qr ? t.addons.qr.price : 0);
  const total = basePrice + addonsTotal;

  const stageBg = useMemo(() => {
    // tint background subtly with selected color, kept dark for product visibility
    const c = color.c;
    return `linear-gradient(180deg, ${c}33 0%, #0b0b08 70%, #0b0b08 100%), radial-gradient(circle at 50% 60%, ${c}55 0%, #0b0b08 65%)`;
  }, [color]);

  const handleAdd = () => {
    if (typeof showCartToast !== "function") return;
    const item = {
      kind: productKey === "collar" ? (lang === "en" ? "Collar" : "Tasma") : (lang === "en" ? "Leash" : "Kayış"),
      name: productKey === "collar" ? (lang === "en" ? "The Collar" : "Boyun Tasması") : (lang === "en" ? "The Leash" : "Gezdirme Kayışı"),
      size,
      color: color.n,
      swatch: color.c,
      code: productKey === "collar" ? "C" : "L",
      plate: plate.trim().toUpperCase() || undefined,
      finish,
      stitch,
      reflective,
      qr,
      price: total,
      qty: 1
    };
    if (typeof useCart === "function") {
      // direct write to localStorage via custom event approach: we can't call hook here. Use the global helper.
      try {
        const raw = localStorage.getItem("peticota.cart.v1");
        const arr = raw ? JSON.parse(raw) : [];
        arr.push({ ...item, id: `it_${Date.now()}_${Math.random().toString(36).slice(2,6)}` });
        localStorage.setItem("peticota.cart.v1", JSON.stringify(arr));
        window.dispatchEvent(new CustomEvent("peticota:cart-changed"));
      } catch (e) {}
    }
    fireFlash();
    showCartToast(item.name, lang);
  };

  const T = t.labels;

  return (
    <section className="builder">
      <div className="preview">
        <div className="preview-stage" style={{ background: stageBg }}>
          <div className="preview-name-stamp">
            <span>{T.stamp[0]}</span>
            <span>{T.stamp[1]}</span>
          </div>
          <div
            className="preview-product"
            style={{ transform: `rotate(${(colorIdx % 2 === 0 ? 1 : -1) * 4}deg)` }}
          >
            <img src={productImg} alt={productKey} />
          </div>
          {plate.trim() ? (
            <div className="preview-plate">{plate.trim().toUpperCase().slice(0, 14)}</div>
          ) : null}
          <div className={`preview-flash ${flash ? "fire" : ""}`}></div>
        </div>
        <div className="preview-bottom-bar">
          <div className="preview-stat">{T[sizeLabelKey]}<b>{size}</b></div>
          <div className="preview-stat">{T.color}<b>{color.n}</b></div>
          <div className="preview-stat">{T.finish}<b>{finish}</b></div>
          <div className="preview-stat">{T.stitch}<b>{stitch}</b></div>
        </div>
      </div>

      <div className="options">
        <div className="options-header">
          <div>
            <span className="chooser-eyebrow">{t.eyebrow}</span>
            <h2 style={{ marginTop: 8 }}>{renderParts(t.builderTitle[productKey])}</h2>
          </div>
          <button className="options-back" onClick={onBack}>{t.back}</button>
        </div>

        {/* Size */}
        <div className="opt-group">
          <div className="opt-label"><span>{T[sizeLabelKey]}</span><span className="val">{size}</span></div>
          <div className="opt-row">
            {sizes.map((s) => (
              <button
                key={s}
                className={`opt-chip ${size === s ? "active" : ""}`}
                onClick={() => setSize(s)}
              >{s}</button>
            ))}
          </div>
        </div>

        {/* Color */}
        <div className="opt-group">
          <div className="opt-label"><span>{T.color}</span><span className="val">{color.n}</span></div>
          <div className="opt-swatches">
            {t.colors.map((c, i) => (
              <button
                key={i}
                className={`opt-swatch ${colorIdx === i ? "active" : ""}`}
                onClick={() => setColorIdx(i)}
              >
                <span className="dot" style={{ background: c.c }}></span>
                <span className="lbl">{c.n}</span>
              </button>
            ))}
          </div>
        </div>

        {/* Finish */}
        <div className="opt-group">
          <div className="opt-label"><span>{T.finish}</span><span className="val">{finish}</span></div>
          <div className="opt-row">
            {t.finishes.map((f) => (
              <button
                key={f}
                className={`opt-chip ${finish === f ? "active" : ""}`}
                onClick={() => setFinish(f)}
              >{f}</button>
            ))}
          </div>
        </div>

        {/* Stitch */}
        <div className="opt-group">
          <div className="opt-label"><span>{T.stitch}</span><span className="val">{stitch}</span></div>
          <div className="opt-row">
            {t.stitches.map((s) => (
              <button
                key={s}
                className={`opt-chip ${stitch === s ? "active" : ""}`}
                onClick={() => setStitch(s)}
              >{s}</button>
            ))}
          </div>
        </div>

        {/* Plate */}
        <div className="opt-group">
          <div className="opt-label"><span>{T.plate}</span><span className="val">{plate ? plate.toUpperCase().slice(0,14) : "—"}</span></div>
          <input
            className="opt-input"
            type="text"
            maxLength={14}
            value={plate}
            placeholder={T.platePh}
            onChange={(e) => setPlate(e.target.value)}
          />
        </div>

        {/* Add-ons */}
        <div className="opt-group">
          <div className="opt-label"><span>{T.addons}</span></div>
          <div
            className={`opt-toggle ${reflective ? "on" : ""}`}
            onClick={() => setReflective(!reflective)}
          >
            <div>
              <span className="lbl">{T.reflective}</span>
              <span className="delta">+₺ {t.addons.reflective.price}</span>
            </div>
            <span className="switch"></span>
          </div>
          <div
            className={`opt-toggle ${qr ? "on" : ""}`}
            onClick={() => setQr(!qr)}
          >
            <div>
              <span className="lbl">{T.qr}</span>
              <span className="delta">+₺ {t.addons.qr.price}</span>
            </div>
            <span className="switch"></span>
          </div>
        </div>

        {/* Summary */}
        <div className="summary">
          <div className="summary-row">
            <span>{T.base}</span>
            <span className="val">₺ {basePrice.toLocaleString("tr-TR")}</span>
          </div>
          {reflective ? (
            <div className="summary-row">
              <span>{T.reflective}</span>
              <span className="val">+ ₺ {t.addons.reflective.price}</span>
            </div>
          ) : null}
          {qr ? (
            <div className="summary-row">
              <span>{T.qr}</span>
              <span className="val">+ ₺ {t.addons.qr.price}</span>
            </div>
          ) : null}
          <div className="summary-total">
            <span className="label">{T.total}</span>
            <span className="price">
              ₺ {total.toLocaleString("tr-TR")}<em>.</em>
            </span>
          </div>
          <button className="btn btn-red" onClick={handleAdd}>
            {T.add} <span className="arr">→</span>
          </button>
          <span className="mono" style={{ color: "var(--muted)", textAlign: "center" }}>
            {T.production}
          </span>
        </div>
      </div>
    </section>
  );
};

/* ================================================
   APP
================================================ */
const D_TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "lang": "tr"
}/*EDITMODE-END*/;

const DApp = () => {
  const [tweaks, setTweak] = useTweaks(D_TWEAK_DEFAULTS);
  const lang = tweaks.lang;
  const setLang = (l) => setTweak("lang", l);
  const t = D_COPY[lang];

  // URL ?p=collar|leash
  const initialProduct = (() => {
    const p = new URLSearchParams(window.location.search).get("p");
    return p === "collar" || p === "leash" ? p : null;
  })();
  const [productKey, setProductKey] = useState(initialProduct);

  useEffect(() => {
    if (productKey) {
      const u = new URL(window.location);
      u.searchParams.set("p", productKey);
      window.history.replaceState({}, "", u);
    } else {
      const u = new URL(window.location);
      u.searchParams.delete("p");
      window.history.replaceState({}, "", u);
    }
  }, [productKey]);

  return (
    <>
      <DNav lang={lang} setLang={setLang} />
      <main className="designer-page">
        {productKey ? (
          <Builder t={t} lang={lang} productKey={productKey} onBack={() => setProductKey(null)} />
        ) : (
          <Chooser t={t} lang={lang} onPick={(k) => setProductKey(k)} />
        )}
      </main>
      <CartDrawer lang={lang} />
      <TweaksPanel title="Tweaks">
        <TweakSection title="Dil / Language">
          <TweakRadio
            value={tweaks.lang}
            onChange={(v) => setTweak("lang", v)}
            options={[
              { value: "tr", label: "Türkçe" },
              { value: "en", label: "English" }
            ]}
          />
        </TweakSection>
      </TweaksPanel>
    </>
  );
};

ReactDOM.createRoot(document.getElementById("root")).render(<DApp />);
