/* global React, Spark, openLead, useBus, WA, TEL, TEL_HUMAN, useCart, fmtKzt, getSource, PriceTag, AddToCartBtn */
const { useState: useStateM, useEffect: useEffectM } = React;

function LeadFormFields({ onDone, quiz }) {
  const [f, setF] = useStateM({ name: "", company: "", phone: "" });
  const [err, setErr] = useStateM({});
  const [sent, setSent] = useStateM(false);
  const [failed, setFailed] = useStateM(false);
  const [busy, setBusy] = useStateM(false);
  const cart = useCart();
  const hasOrder = cart.list.length > 0;
  const upd = (k) => (e) => { setF((s) => ({ ...s, [k]: e.target.value })); if (err[k]) setErr((s) => ({ ...s, [k]: null })); };
  const submit = async (e) => {
    e.preventDefault();
    if (busy) return;  // защита от двойной отправки — иначе в Битриксе задвоятся лиды
    const er = {};
    if (!f.name.trim()) er.name = "Укажите имя";
    if (!f.company.trim()) er.company = "Укажите компанию";
    if ((f.phone.match(/\d/g) || []).length < 7) er.phone = "Укажите корректный телефон";
    setErr(er);
    if (Object.keys(er).length > 0) return;
    const order = cart.list.map((i) => ({ name: i.name, kz: i.kz, qty: i.qty, price: i.price }));
    const wasOrder = order.length > 0;
    setFailed(false);
    setBusy(true);
    let ok = false;
    try {
      const r = await fetch("/send.php", {
        method: "POST",
        headers: { "Content-Type": "application/json", Accept: "application/json" },
        body: JSON.stringify({ name: f.name, company: f.company, phone: f.phone, source: getSource(),
          ...(wasOrder ? { items: order, total: cart.total } : {}), ...(quiz ? { quiz } : {}) })
      });
      // важно: не только r.ok — send.php отвечает 200 лишь когда сработал хотя бы один канал
      const j = await r.json().catch(() => null);
      ok = r.ok && !!(j && j.success);
    } catch (_) {}
    if (!ok) {
      // запасной канал — на случай, если PHP или почта на сервере недоступны
      try {
        const orderText = wasOrder
          ? order.map((i) => `${i.name} ×${i.qty} = ${fmtKzt(i.price * i.qty)}`).join("\n") + `\nИтого: ${fmtKzt(cart.total)}`
          : "";
        const quizText = quiz ? `Кому: ${quiz.audience || "—"}; Бюджет: ${quiz.budget || "—"}; Логотип: ${quiz.logo || "—"}` : "";
        const rf = await fetch("https://formsubmit.co/ajax/info@mereketoy.kz", {
          method: "POST", headers: { "Content-Type": "application/json", Accept: "application/json" },
          body: JSON.stringify({ "Имя": f.name, "Компания": f.company, "Телефон": f.phone,
            ...(wasOrder ? { "Заказ": orderText, "Сумма": fmtKzt(cart.total) } : {}),
            ...(quiz ? { "Анкета": quizText } : {}),
            _subject: (wasOrder ? "Новый заказ с сайта Mereke — " : (quiz ? "Заявка-подбор с сайта Mereke — " : "Новая заявка с сайта Mereke — ")) + f.company, _captcha: "false", _template: "table" })
        });
        ok = rf.ok;
      } catch (_) {}
    }
    setBusy(false);
    if (!ok) { setFailed(true); return; }  // корзину не чистим — заявку можно переотправить
    if (wasOrder) cart.clear();
    setSent(true);
  };
  if (sent) {
    return React.createElement("div", { className: "lp-success" },
      React.createElement("div", { className: "ring" }, React.createElement(Spark, { style: { width: 26, height: 26 } })),
      React.createElement("h3", { style: { fontFamily: "var(--font-display)", fontWeight: 800, fontSize: "1.7rem", color: "#fff", margin: "0 0 10px" } }, "Заявка принята!"),
      React.createElement("p", { style: { color: "rgba(255,238,228,0.85)", margin: 0, fontSize: 16 } },
        f.name + ", спасибо. Пришлём каталог и расчёт и перезвоним в течение часа в рабочее время."));
  }
  const field = (k, label, ph, type = "text", inputMode) =>
    React.createElement("div", { className: `lp-field ${err[k] ? "err" : ""}` },
      React.createElement("label", null, label),
      React.createElement("input", { value: f[k], onChange: upd(k), placeholder: ph, type, inputMode, "aria-label": label }),
      err[k] && React.createElement("span", { className: "msg" }, err[k]));
  return React.createElement("form", { className: "lp-form", onSubmit: submit, noValidate: true },
    hasOrder && React.createElement("div", { className: "lp-order-sum" },
      React.createElement("div", { className: "ttl" }, "Ваш заказ", React.createElement("span", null, cart.count + " шт")),
      cart.list.map((i) => React.createElement("div", { className: "row", key: i.key },
        React.createElement("span", { className: "n" }, i.name + " ×" + i.qty),
        React.createElement("span", { className: "p" }, fmtKzt(i.price * i.qty)))),
      React.createElement("div", { className: "tot" }, React.createElement("span", null, "Итого"), React.createElement("b", null, fmtKzt(cart.total)))),
    quiz && React.createElement("div", { className: "lp-order-sum" },
      React.createElement("div", { className: "ttl" }, "Ваш формат", React.createElement("span", null, "по квизу")),
      [["Кому", quiz.audience], ["Бюджет", quiz.budget], ["Логотип", quiz.logo]].map(([k, v]) =>
        React.createElement("div", { className: "row", key: k }, React.createElement("span", { className: "n" }, k), React.createElement("span", { className: "p" }, v || "—")))),
    field("name", "Ваше имя", "Айгерим"),
    field("company", "Компания", "Название компании"),
    field("phone", "Телефон", "+7 (___) ___-__-__", "tel", "tel"),
    failed && React.createElement("div", { role: "alert", style: { marginTop: 8, padding: "13px 15px", borderRadius: 10, background: "rgba(216,30,44,0.10)", border: "1px solid rgba(216,30,44,0.35)", fontSize: 14, lineHeight: 1.5 } },
      React.createElement("b", { style: { display: "block", color: "#D81E2C", marginBottom: 4 } }, "Заявка не отправилась"),
      React.createElement("span", { style: { color: "rgba(255,238,228,0.85)" } }, "Проверьте связь и попробуйте ещё раз — или свяжитесь с нами напрямую:"),
      React.createElement("div", { style: { display: "flex", flexWrap: "wrap", gap: 14, marginTop: 8 } },
        React.createElement("a", { href: "tel:" + TEL, style: { color: "var(--amber-400)", fontWeight: 700 } }, TEL_HUMAN),
        React.createElement("a", { href: WA, target: "_blank", rel: "noopener", style: { color: "var(--amber-400)", fontWeight: 700 } }, "WhatsApp"))),
    React.createElement("button", { type: "submit", disabled: busy, className: "lp-btn lp-btn-amber", style: { marginTop: 6, width: "100%", opacity: busy ? 0.6 : 1, cursor: busy ? "wait" : "pointer" } },
      busy ? "Отправляем…" : (hasOrder ? "Отправить заказ" : (quiz ? "Получить 3 варианта" : "Отправить заявку")), React.createElement(Spark, { style: { width: 15, height: 15 } })),
    React.createElement("a", { href: WA, target: "_blank", rel: "noopener", className: "lp-btn lp-btn-wa", style: { width: "100%" } }, "Написать в WhatsApp"),
    React.createElement("div", { className: "lp-form-note" }, React.createElement(Spark, { style: { width: 12, height: 12, color: "var(--amber-400)" } }), "Перезвоним в течение часа · каталог-PDF в подарок"));
}

function useEsc(open, close) {
  useEffectM(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === "Escape") close(); };
    document.addEventListener("keydown", onKey);
    const prev = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => { document.removeEventListener("keydown", onKey); document.body.style.overflow = prev; };
  }, [open, close]);
}

function useModalAnim(open) {
  const [shown, setShown] = useStateM(false);
  const [locked, setLocked] = useStateM(false);
  useEffectM(() => {
    if (!open) { setShown(false); setLocked(false); return; }
    const t1 = setTimeout(() => setShown(true), 20);
    const t2 = setTimeout(() => setLocked(true), 440);
    return () => { clearTimeout(t1); clearTimeout(t2); };
  }, [open]);
  const backStyle = locked ? { opacity: 1, transition: "none" } : undefined;
  const modalStyle = locked ? { opacity: 1, transform: "none", transition: "none" } : undefined;
  return { shown, backStyle, modalStyle };
}

function LeadModal() {
  const [open, setOpen] = useStateM(false);
  const [quiz, setQuiz] = useStateM(null);
  const cart = useCart();
  const hasOrder = cart.count > 0;
  const close = React.useCallback(() => setOpen(false), []);
  useBus("mereke:lead", React.useCallback((detail) => { setQuiz(detail && detail.quiz ? detail.quiz : null); setOpen(true); }, []));
  useEsc(open, close);
  const { shown, backStyle, modalStyle } = useModalAnim(open);
  const eyebrow = hasOrder ? "Оформление заказа" : (quiz ? "Подбор подарка" : "Заявка");
  const title = hasOrder ? "Оформить заказ" : (quiz ? "Получить 3 варианта" : "Получить каталог и расчёт");
  const desc = hasOrder ? "Заполните контакты — перезвоним, подтвердим состав заказа и пришлём счёт."
    : (quiz ? "Оставьте контакты — пришлём 3 варианта комплектации под ваш формат и сроки производства."
      : "Оставьте контакты — подберём коллекцию под вашу команду и пришлём предложение в течение дня.");
  return React.createElement("div", { className: `lp-modal-back ${shown ? "open" : ""}`, style: backStyle, onClick: close, "aria-hidden": !open },
    React.createElement("div", { className: "lp-modal lp-glass", style: modalStyle, onClick: (e) => e.stopPropagation() },
      React.createElement("button", { className: "close", "aria-label": "Закрыть", onClick: close }, "×"),
      React.createElement("span", { style: { fontFamily: "var(--font-body)", fontWeight: 700, fontSize: 12, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--amber-400)" } }, eyebrow),
      React.createElement("h3", { style: { fontFamily: "var(--font-display)", fontWeight: 800, fontSize: "1.9rem", color: "#fff", margin: "10px 0 6px" } }, title),
      React.createElement("p", { style: { color: "rgba(255,238,228,0.82)", margin: "0 0 20px", fontSize: 15.5 } }, desc),
      open && React.createElement(LeadFormFields, { quiz }))
  );
}

function ProductModal() {
  const [p, setP] = useStateM(null);
  const close = React.useCallback(() => setP(null), []);
  useBus("mereke:product", React.useCallback((detail) => setP(detail), []));
  useEsc(!!p, close);
  const { shown, backStyle, modalStyle } = useModalAnim(!!p);
  return React.createElement("div", { className: `lp-modal-back ${shown ? "open" : ""}`, style: backStyle, onClick: close, "aria-hidden": !p },
    React.createElement("div", { className: "lp-modal lp-pmodal lp-glass", style: modalStyle, onClick: (e) => e.stopPropagation() },
      React.createElement("button", { className: "close", "aria-label": "Закрыть", onClick: close, style: { zIndex: 4 } }, "×"),
      p && React.createElement(React.Fragment, null,
        React.createElement("div", { className: "img" },
          React.createElement("div", { className: "lp-glow", style: { width: "70%", height: "60%", background: "radial-gradient(circle, rgba(242,161,78,0.4), rgba(242,161,78,0))", opacity: 0.7 } }),
          React.createElement("img", { src: "assets/products2026/" + p.img, alt: p.name })),
        React.createElement("div", { className: "body" },
          p.hit && React.createElement("span", { style: { alignSelf: "flex-start", display: "inline-flex", alignItems: "center", gap: 6, padding: "5px 12px", borderRadius: 999, background: "var(--amber-500)", color: "var(--ink-900)", fontFamily: "var(--font-body)", fontWeight: 700, fontSize: 11, letterSpacing: "0.04em", textTransform: "uppercase" } }, React.createElement(Spark, { style: { width: 11, height: 11 } }), "Хит сезона"),
          React.createElement("span", { className: "kz" }, p.kz),
          React.createElement("h3", null, p.name),
          React.createElement("p", null, p.desc),
          p.rrp && React.createElement("div", { style: { marginTop: 4 } }, React.createElement(PriceTag, { rrp: p.rrp, onRed: true })),
          React.createElement("div", { style: { marginTop: 8, display: "flex", flexWrap: "wrap", gap: 12, alignItems: "center" } },
            p.rrp && React.createElement(AddToCartBtn, { p, block: false }),
            React.createElement("button", { className: "lp-btn lp-btn-glass", onClick: () => { close(); openLead(); } }, "Оставить заявку", React.createElement(Spark, { style: { width: 14, height: 14 } }))),
          React.createElement("div", { style: { marginTop: 6, display: "flex", flexWrap: "wrap", gap: "8px 16px", color: "rgba(255,236,224,0.7)", fontSize: 13, fontFamily: "var(--font-body)" } },
            React.createElement("span", null, "✦ Выдувное стекло"),
            React.createElement("span", null, "✦ Ручная роспись"),
            React.createElement("span", null, "✦ Лимитированная серия")))))
  );
}

Object.assign(window, { LeadFormFields, LeadModal, ProductModal });
