// Rezervačný formulár — nahradzuje checkout / košík v chovnom prototype.
(function () {
  if (typeof React === "undefined") return;
  var DS = window.VElaStvNajmanDesignSystem_bc3fc2;
  var Button = DS.Button;
  var Input = DS.Input;
  var Icon = window.VNIcon;

  function Err({ msg }) {
    if (!msg) return null;
    return (
      <span className="vn-field__error" style={{ display: "block", color: "var(--chyba)", fontSize: "var(--text-xs)", marginTop: 4 }}>
        {msg}
      </span>
    );
  }

  // Vlastný zaoblený dropdown (natívny <select> má hranatý OS-popup, ktorý sa nedá zaobliť cez CSS).
  function Select({ value, onChange, disabled, placeholder, options, ariaLabel }) {
    var _o = React.useState(false);
    var openState = _o[0];
    var setOpen = _o[1];
    var ref = React.useRef(null);
    var selected = null;
    for (var i = 0; i < options.length; i++) {
      if (options[i].value === value) { selected = options[i]; break; }
    }
    React.useEffect(function () {
      function onDoc(e) { if (ref.current && !ref.current.contains(e.target)) setOpen(false); }
      function onKey(e) { if (e.key === "Escape") setOpen(false); }
      document.addEventListener("mousedown", onDoc);
      document.addEventListener("keydown", onKey);
      return function () {
        document.removeEventListener("mousedown", onDoc);
        document.removeEventListener("keydown", onKey);
      };
    }, []);
    React.useEffect(function () { if (disabled) setOpen(false); }, [disabled]);
    function pick(opt) {
      if (opt.disabled) return;
      onChange(opt.value);
      setOpen(false);
    }
    return (
      <div className={"vn-select" + (disabled ? " is-disabled" : "") + (openState ? " is-open" : "")} ref={ref}>
        <button type="button" className="vn-select__btn" aria-haspopup="listbox" aria-expanded={openState}
          aria-label={ariaLabel} disabled={disabled}
          onClick={function () { if (!disabled) setOpen(function (v) { return !v; }); }}>
          <span className={"vn-select__value" + (selected ? "" : " is-placeholder")}>
            {selected ? selected.label : placeholder}
          </span>
          <Icon name="chevronDown" size={16} />
        </button>
        {openState && (
          <ul className="vn-select__menu" role="listbox">
            {options.map(function (opt) {
              return (
                <li key={opt.value || "__ph"} role="option" aria-selected={opt.value === value}
                  className={"vn-select__opt" + (opt.value === value ? " is-selected" : "") + (opt.disabled ? " is-disabled" : "")}
                  onClick={function () { pick(opt); }}>
                  {opt.label}
                </li>
              );
            })}
          </ul>
        )}
      </div>
    );
  }

  function Rezervace({ go, preset, presetQty }) {
    var initial = preset && typeof preset === "object" ? preset : null;
    var initTyp = initial && initial._typ ? initial._typ : initial && initial.cat === "oddelky" ? "oddelek" : "matka";
    var initSlug = initial && (initial._slug || initial.id) ? (initial._slug || initial.id) : "";

    var _s = React.useState({
      jmeno: "",
      email: "",
      telefon: "",
      typ: initTyp || "",
      polozkaSlug: initSlug,
      pocetKusu: String(presetQty || 1),
      preferovanyTermin: "",
      poznamka: "",
      gdprSouhlas: false,
    });
    var form = _s[0];
    var setForm = _s[1];
    var _e = React.useState({});
    var errors = _e[0];
    var setErrors = _e[1];
    var _st = React.useState("idle");
    var status = _st[0];
    var setStatus = _st[1];
    var _m = React.useState("");
    var successMsg = _m[0];
    var setSuccessMsg = _m[1];

    var shop = window.SHOP_DATA || {};
    var open = shop.rezervaceOtevrena !== false;

    function productsForTyp(typ) {
      return (shop.products || []).filter(function (p) {
        if (!typ) return false;
        return p._typ === typ && p.stock !== "out";
      });
    }

    function setField(key, value) {
      setForm(function (prev) {
        var next = Object.assign({}, prev, {});
        next[key] = value;
        if (key === "typ") next.polozkaSlug = "";
        return next;
      });
      setErrors(function (prev) {
        if (!prev[key]) return prev;
        var n = Object.assign({}, prev);
        delete n[key];
        return n;
      });
    }

    function onSubmit(e) {
      e.preventDefault();
      setErrors({});
      var parsed = window.__validateRezervace(form);
      if (!parsed.ok) {
        setErrors(parsed.errors);
        setStatus("error");
        return;
      }
      setStatus("loading");
      fetch("/api/cms/rezervace", {
        method: "POST",
        headers: { "Content-Type": "application/json", Accept: "application/json" },
        body: JSON.stringify(parsed.data),
      })
        .then(function (res) {
          return res.json().then(function (data) {
            return { res: res, data: data };
          });
        })
        .then(function (_ref) {
          var res = _ref.res;
          var data = _ref.data;
          if (!res.ok) {
            setErrors(data.errors || { form: data.error || "Rezervaci se nepodařilo odeslat." });
            setStatus("error");
            return;
          }
          setSuccessMsg(data.message || "Rezervace byla přijata. Ozveme se vám s potvrzením.");
          setStatus("success");
        })
        .catch(function () {
          setErrors({ form: "Nepodařilo se spojit se serverem. Zkuste to prosím později." });
          setStatus("error");
        });
    }

    if (!open) {
      return (
        <main className="kit">
          <div className="kit-shell" style={{ padding: "var(--section-y)" }}>
            <h1>Rezervace</h1>
            <p>Příjem rezervací je momentálně uzavřen.</p>
            <Button variant="secondary" onClick={function () { go("contact"); }}>Kontaktujte nás</Button>
          </div>
        </main>
      );
    }

    if (status === "success") {
      return (
        <main className="kit">
          <div className="kit-shell" style={{ maxWidth: 720, margin: "0 auto", padding: "var(--section-y)", textAlign: "center" }}>
            <div style={{ padding: 32, background: "var(--surface-card)", borderRadius: "var(--radius-lg)", border: "1px solid var(--border-soft)" }}>
              <Icon name="check" size={36} />
              <h1 style={{ marginTop: 16, marginBottom: 8 }}>Rezervace odeslána</h1>
              <p style={{ color: "var(--text-muted)", marginBottom: 24 }}>{successMsg}</p>
              <Button variant="primary" onClick={function () { go("category"); }}>Zpět na nabídku</Button>
            </div>
          </div>
        </main>
      );
    }

    var produkty = productsForTyp(form.typ);

    return (
      <main className="kit">
        <div className="kit-shell kit-cathead">
          <nav className="kit-breadcrumb">
            <a href="#" onClick={function (e) { e.preventDefault(); go("home"); }}>Domů</a>
            <Icon name="chevronRight" size={13} /> <span>Rezervace</span>
          </nav>
          <h1>Rezervace matky nebo oddělku</h1>
          <p>Vyplňte formulář pro předběžnou rezervaci. Ozveme se vám s potvrzením a dalšími informacemi k převzetí.</p>
        </div>
        <div className="kit-shell" style={{ maxWidth: 720, paddingBottom: "var(--section-y)" }}>
          <form className="kit-contact__form" onSubmit={onSubmit} noValidate aria-busy={status === "loading"}>
            {errors.form && (
              <p role="alert" style={{ color: "var(--chyba)", marginBottom: 16 }}>{errors.form}</p>
            )}
            <div className="kit-contact__row">
              <div className="vn-field">
                <Input label="Vaše jméno" value={form.jmeno} onChange={function (e) { setField("jmeno", e.target.value); }} disabled={status === "loading"} />
                <Err msg={errors.jmeno} />
              </div>
              <div className="vn-field">
                <Input label="E-mail" type="email" value={form.email} onChange={function (e) { setField("email", e.target.value); }} disabled={status === "loading"} />
                <Err msg={errors.email} />
              </div>
            </div>
            <div className="vn-field">
              <Input label="Telefon (nepovinné)" type="tel" value={form.telefon} onChange={function (e) { setField("telefon", e.target.value); }} placeholder="+420 …" disabled={status === "loading"} />
              <Err msg={errors.telefon} />
            </div>
            <div className="vn-field">
              <label className="vn-field__label" style={{ display: "block", marginBottom: 6 }}>Typ rezervace</label>
              <Select
                ariaLabel="Typ rezervace"
                value={form.typ}
                disabled={status === "loading"}
                placeholder="Vyberte…"
                onChange={function (v) { setField("typ", v); }}
                options={[
                  { value: "matka", label: "Chovná matka" },
                  { value: "oddelek", label: "Oddělek" },
                ]}
              />
              <Err msg={errors.typ} />
            </div>
            <div className="vn-field">
              <label className="vn-field__label" style={{ display: "block", marginBottom: 6 }}>Produkt</label>
              <Select
                ariaLabel="Produkt"
                value={form.polozkaSlug}
                disabled={!form.typ || status === "loading"}
                placeholder={form.typ ? "Vyberte…" : "Nejdříve vyberte typ"}
                onChange={function (v) { setField("polozkaSlug", v); }}
                options={produkty.map(function (p) { return { value: (p._slug || p.id), label: p.name }; })}
              />
              <Err msg={errors.polozkaSlug} />
            </div>
            <div className="vn-field">
              <Input label="Počet kusů" type="number" value={form.pocetKusu} onChange={function (e) { setField("pocetKusu", e.target.value); }} disabled={status === "loading"} />
              <Err msg={errors.pocetKusu} />
            </div>
            <div className="vn-field">
              <Input label="Preferovaný termín" value={form.preferovanyTermin} onChange={function (e) { setField("preferovanyTermin", e.target.value); }} placeholder="např. květen 2026, víkend …" disabled={status === "loading"} />
              <Err msg={errors.preferovanyTermin} />
            </div>
            <div className="vn-field">
              <label className="vn-field__label" style={{ display: "block", marginBottom: 6 }}>Poznámka</label>
              <textarea className="vn-input" rows={4} value={form.poznamka} onChange={function (e) { setField("poznamka", e.target.value); }} placeholder="Volitelná poznámka…" style={{ width: "100%", resize: "vertical", fontFamily: "var(--font-body)" }} disabled={status === "loading"} />
              <Err msg={errors.poznamka} />
            </div>
            <label style={{ display: "flex", gap: 10, alignItems: "flex-start", fontSize: "var(--text-sm)", cursor: "pointer" }}>
              <input type="checkbox" checked={form.gdprSouhlas} onChange={function (e) { setField("gdprSouhlas", e.target.checked); }} disabled={status === "loading"} style={{ marginTop: 3 }} />
              <span>Souhlasím se zpracováním osobních údajů za účelem vyřízení rezervace.</span>
            </label>
            <Err msg={errors.gdprSouhlas} />
            <div style={{ marginTop: 20 }}>
              <Button variant="primary" block size="lg" type="submit" disabled={status === "loading"} iconStart={status === "loading" ? undefined : <Icon name="check" size={18} />}>
                {status === "loading" ? "Odesílám…" : "Odeslat rezervaci"}
              </Button>
            </div>
          </form>
        </div>
      </main>
    );
  }

  window.VNRezervace = Rezervace;
})();
