const { CountryFlag, Icon } = window.EdvinDesignSystem_ae67eb;
const LIGHT = { fontWeight: 300, letterSpacing: "0.01em" };

function H1({ children }) {
  return <h1 style={{ margin: "0 0 8px", fontSize: 32, lineHeight: 1.04, textTransform: "uppercase", color: "var(--edvin-green)", ...LIGHT }}>{children}</h1>;
}
function H2({ children }) {
  return <h2 style={{ margin: "0 0 14px", fontSize: 13, fontWeight: 700, textTransform: "uppercase", letterSpacing: ".08em", color: "var(--edvin-gray-900)" }}>{children}</h2>;
}

function Field({ label, value, onChange, placeholder, type = "text", multiline, rows = 3, autoComplete, name, inputMode, options }) {
  const shared = {
    width: "100%", padding: "13px 14px", borderRadius: 12, border: "none",
    background: "var(--edvin-gray-100)", outline: "none",
    fontFamily: "var(--font-core)", fontSize: 16, lineHeight: 1.4, color: "var(--edvin-black)",
  };
  return (
    <label style={{ display: "block" }}>
      <span style={{ display: "block", marginBottom: 6, fontSize: 13, color: "var(--edvin-gray-900)" }}>{label}</span>
      {options
        ? <div style={{ position: "relative" }}>
            <select name={name || autoComplete} autoComplete={autoComplete} value={value || ""} onChange={(e) => onChange(e.target.value)} style={{ ...shared, appearance: "none", WebkitAppearance: "none", paddingRight: 38, cursor: "pointer", color: value ? "var(--edvin-black)" : "var(--edvin-gray-900)" }}>
              <option value="">Bitte wählen</option>
              {options.map((o) => <option key={o} value={o}>{o}</option>)}
            </select>
            <span aria-hidden="true" style={{ position: "absolute", right: 14, top: "50%", transform: "translateY(-50%)", pointerEvents: "none", display: "grid", placeItems: "center" }}>
              <svg width="12" height="8" viewBox="0 0 12 8" fill="none"><path d="M1 1.5 6 6.5 11 1.5" stroke="var(--edvin-black)" strokeWidth="1.35" strokeLinecap="round" strokeLinejoin="round"/></svg>
            </span>
          </div>
        : multiline
        ? <textarea rows={rows} value={value || ""} placeholder={placeholder} onChange={(e) => onChange(e.target.value)} style={{ ...shared, resize: "vertical" }} />
        : <input type={type} name={name || autoComplete} autoComplete={autoComplete} inputMode={inputMode} value={value || ""} placeholder={placeholder} onChange={(e) => onChange(e.target.value)} style={shared} />}
    </label>
  );
}

function Choice({ checked, onChange, title, sub }) {
  return (
    <button type="button" onClick={onChange} style={{
      width: "100%", display: "flex", gap: 14, alignItems: "flex-start", textAlign: "left",
      padding: "16px 16px", borderRadius: 12, cursor: "pointer", border: "none",
      background: checked ? "var(--edvin-green-tint)" : "var(--edvin-gray-100)",
      boxShadow: checked ? "inset 0 0 0 1.5px var(--edvin-green)" : "none",
      fontFamily: "var(--font-core)", transition: "background var(--duration-fast) var(--ease-standard)",
    }}>
      <span style={{ flex: "0 0 auto", width: 22, height: 22, marginTop: 1, borderRadius: "50%", display: "grid", placeItems: "center", boxShadow: checked ? "none" : "inset 0 0 0 1.5px var(--edvin-gray-400)", background: checked ? "var(--edvin-green)" : "transparent", color: "#fff", fontSize: 13 }}>{checked ? "✓" : ""}</span>
      <span style={{ flex: 1 }}>
        <span style={{ display: "block", fontSize: 16, fontWeight: 400 }}>{title}</span>
        {sub && <span style={{ display: "block", marginTop: 3, fontSize: 14, color: "var(--edvin-gray-900)", lineHeight: 1.4 }}>{sub}</span>}
      </span>
    </button>
  );
}

function BigCheck({ checked, onChange, children }) {
  return (
    <button type="button" onClick={() => onChange(!checked)} style={{
      width: "100%", display: "flex", gap: 14, alignItems: "flex-start", textAlign: "left",
      padding: "14px 0", background: "none", border: "none", cursor: "pointer", fontFamily: "var(--font-core)",
    }}>
      <span style={{
        flex: "0 0 auto", width: 26, height: 26, borderRadius: 7, display: "grid", placeItems: "center",
        boxShadow: checked ? "none" : "inset 0 0 0 1.5px var(--edvin-gray-400)",
        background: checked ? "var(--edvin-green)" : "transparent", color: "#fff", fontSize: 15,
      }}>{checked ? "✓" : ""}</span>
      <span style={{ flex: 1, fontSize: 15, lineHeight: 1.45 }}>{children}</span>
    </button>
  );
}

function PrimaryButton({ children, onClick, disabled, tone = "red" }) {
  return (
    <button type="button" disabled={disabled} onClick={onClick} style={{
      width: "100%", height: 54, border: "none", borderRadius: 12, cursor: disabled ? "not-allowed" : "pointer",
      background: tone === "red" ? "var(--edvin-red)" : "var(--edvin-green)", color: "#fff",
      fontFamily: "var(--font-core)", fontWeight: 700, fontSize: 15, opacity: disabled ? 0.35 : 1,
      textTransform: "uppercase", letterSpacing: ".06em",
      transition: "opacity var(--duration-fast) var(--ease-standard)",
    }}>{children}</button>
  );
}

function Line({ label, value, bold, red }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", padding: "8px 0", fontSize: 16, fontWeight: bold ? 700 : 400, color: red ? "var(--edvin-red)" : "var(--edvin-black)" }}>
      <span>{label}</span><span>{value}</span>
    </div>
  );
}

function Totals({ sub, ship, total, saved }) {
  const chf = window.TDOF.chf;
  return (
    <div style={{ background: "var(--edvin-gray-100)", borderRadius: 14, padding: "14px 18px" }}>
      <Line label="Zwischensumme" value={chf(sub)} />
      <Line label="Versandkosten" value={ship === 0 ? "gratis" : chf(ship)} />
      <div style={{ height: "0.5px", background: "rgba(0,0,0,0.18)", margin: "6px 0" }} />
      <Line label="Gesamttotal" value={chf(total)} bold />
      <p style={{ margin: "10px 0 0", fontSize: 13, color: "var(--edvin-green)", fontWeight: 700 }}>Du sparst {chf(saved)} Festival-Rabatt.</p>
    </div>
  );
}

function useTotals(state) {
  const items = Object.keys(state.cart).filter((nr) => state.cart[nr] > 0).map((nr) => ({ w: window.TDOF.byNr[nr], n: state.cart[nr] }));
  const sub = items.reduce((s, i) => s + i.w.sale * i.n, 0);
  const saved = items.reduce((s, i) => s + (i.w.price - i.w.sale) * i.n, 0);
  const ship = state.fulfilment === "abholung" ? 0 : (sub >= window.TDOF.event.freeFrom || sub === 0 ? 0 : window.TDOF.event.shipping);
  return { items, sub, saved, ship, total: sub + ship };
}

function CartView({ state, actions, onCheckout, onBack }) {
  const wrap = window.TDOF_WRAP, chf = window.TDOF.chf;
  const { items, sub, saved, ship, total } = useTotals(state);
  const Stepper = window.TdofStepper;

  return (
    <div style={{ ...wrap, paddingTop: 28, paddingBottom: 36 }}>
      <H1>Dein Warenkorb</H1>
      {items.length === 0 && <p style={{ margin: "0 0 22px", fontSize: 15, color: "var(--edvin-gray-900)" }}>Noch nichts drin.</p>}
      {items.length === 0 && <PrimaryButton tone="green" onClick={onBack}>Zur Weinliste</PrimaryButton>}

      {items.map(({ w, n }, i) => (
        <div key={w.nr}>
          <div style={{ display: "flex", gap: 14, alignItems: "flex-start", padding: "18px 0" }}>
            <div style={{ flex: "0 0 54px", height: 96, borderRadius: 10, background: "var(--edvin-gray-100)" }} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ display: "flex", gap: 8, alignItems: "center", marginBottom: 6 }}>
                <span style={{ fontSize: 12, color: "var(--edvin-gray-900)" }}>{w.nr}</span>
                <CountryFlag country={w.land} width={18} shape="circle" />
              </div>
              <div style={{ fontSize: 16, lineHeight: 1.2, textTransform: "uppercase", fontWeight: 400, letterSpacing: "0.01em" }}>{w.name}</div>
              <div style={{ fontSize: 13, color: "var(--edvin-gray-900)", margin: "5px 0 12px" }}>{w.year ? w.year + " · " : ""}{(w.size || "75cl").replace("cl", " cl")} · {chf(w.sale)}/Fl.</div>
              <div style={{ display: "flex", alignItems: "center", gap: 16, flexWrap: "wrap" }}>
                <Stepper value={n} min={0} onChange={(v) => actions.setCart(w.nr, v)} />
                <button type="button" onClick={() => actions.setCart(w.nr, 0)} style={{ background: "none", border: "none", padding: "10px 4px", cursor: "pointer", fontFamily: "var(--font-core)", fontSize: 14, color: "var(--edvin-gray-900)" }}>Entfernen</button>
              </div>
            </div>
            <div style={{ fontWeight: 700, fontSize: 16, color: "var(--edvin-red)", whiteSpace: "nowrap" }}>{chf(w.sale * n)}</div>
          </div>
          {i < items.length - 1 && <span style={{ display: "block", height: "0.5px", background: "rgba(0,0,0,0.14)" }} />}
        </div>
      ))}

      {items.length > 0 && (
        <div style={{ marginTop: 26, display: "flex", flexDirection: "column", gap: 20 }}>
          <Totals sub={sub} ship={ship} total={total} saved={saved} />
          <PrimaryButton onClick={onCheckout}>Zur Bestellung</PrimaryButton>
        </div>
      )}
    </div>
  );
}

const ORDER_TO = "f.perez@wka.ch";
const ORDER_ENDPOINT = "https://formsubmit.co/ajax/" + ORDER_TO;

function buildOrder(state, items, t) {
  const chf = window.TDOF.chf, f = state.form;
  const num = (n) => n.toFixed(2);
  const cl = (w) => (w.size || "75cl").replace("cl", " cl");
  const bottles = items.reduce((s, i) => s + i.n, 0);
  const now = new Date();
  const ref = "TDOF-" + now.toISOString().slice(2, 10).replace(/-/g, "") + "-" + String(1000 + Math.floor(Math.random() * 9000));
  const abholung = state.fulfilment === "abholung";
  const u = (i) => "\u200b".repeat(i + 1);

  const fields = {
    _subject: `TdOF Bestellung ${ref} \u2014 ${f.vorname || ""} ${f.nachname || ""} \u2014 ${chf(t.total)}`,
    _template: "table",
    _captcha: "false",
  };
  if (f.email) { fields._replyto = f.email; fields._cc = f.email; }

  fields["BESTELLUNG"] = "";
  items.forEach(({ w, n }, i) => {
    const k = u(i);
    fields["POSITION " + (i + 1) + k] = "";
    fields["Art.-Nr." + k] = String(w.art);
    fields["Weinname" + k] = w.name;
    fields["Produzent" + k] = w.producer || "\u2014";
    fields["Jahr" + k] = w.year || "\u2014";
    fields["Inhalt" + k] = cl(w);
    fields["Preis" + k] = num(w.sale);
    fields["Menge" + k] = String(n);
  });

  fields["TOTAL"] = "";
  fields["Positionen / Flaschen"] = `${items.length} / ${bottles}`;
  fields["Zwischensumme"] = chf(t.sub);
  fields["Festival-Rabatt"] = "\u2212 " + chf(t.saved);
  fields["Versandkosten"] = t.ship === 0 ? "gratis" : chf(t.ship);
  fields["GESAMTTOTAL"] = chf(t.total);

  fields["BESTELLER"] = "";
  fields["Anrede"] = f.anrede || "\u2014";
  fields["Vorname"] = f.vorname || "\u2014";
  fields["Nachname"] = f.nachname || "\u2014";
  fields["Firma"] = f.firma || "\u2014";
  fields["Strasse / Nr."] = abholung ? "\u2014 (Abholung)" : (f.strasse || "\u2014");
  fields["PLZ"] = abholung ? "\u2014 (Abholung)" : (f.plz || "\u2014");
  fields["Ort"] = abholung ? "\u2014 (Abholung)" : (f.ort || "\u2014");
  fields["Telefon"] = f.telefon || "\u2014";
  fields["E-Mail"] = f.email || "\u2014";
  fields["Bemerkungen"] = f.bemerkung || "\u2014";
  fields["Abwicklung"] = abholung ? "Abholung Weinladen Aarau, Rohrerstrasse 64" : "Lieferung";
  fields["Bestellnummer"] = ref;
  fields["Eingegangen"] = now.toLocaleString("de-CH", { dateStyle: "short", timeStyle: "short" });

  const tsv = [["Art.-Nr.", "Weinname", "Produzent", "Jahr", "Inhalt", "Preis", "Menge"].join("\t")];
  items.forEach(({ w, n }) => tsv.push([w.art, w.name, w.producer || "", w.year || "", cl(w), num(w.sale), n].join("\t")));

  const body = [
    tsv.join("\n"), "",
    `Gesamttotal\t${num(t.total)}`,
    `Zwischensumme\t${num(t.sub)}`,
    `Festival-Rabatt\t${num(t.saved)}`,
    `Versandkosten\t${num(t.ship)}`,
    "",
    `Anrede\t${f.anrede || ""}`,
    `Vorname\t${f.vorname || ""}`,
    `Nachname\t${f.nachname || ""}`,
    `Firma\t${f.firma || ""}`,
    `Strasse / Nr.\t${abholung ? "" : (f.strasse || "")}`,
    `PLZ\t${abholung ? "" : (f.plz || "")}`,
    `Ort\t${abholung ? "" : (f.ort || "")}`,
    `Telefon\t${f.telefon || ""}`,
    `E-Mail\t${f.email || ""}`,
    `Bemerkungen\t${f.bemerkung || ""}`,
    `Abwicklung\t${fields["Abwicklung"]}`,
    `Bestellnummer\t${ref}`,
    `Eingegangen\t${fields["Eingegangen"]}`,
  ].join("\n");

  return { fields, ref, mailto: `mailto:${ORDER_TO}?subject=${encodeURIComponent(fields._subject)}&body=${encodeURIComponent(body)}` };
}

function CheckoutView({ state, actions, onPlace, onBack }) {
  const wrap = window.TDOF_WRAP, chf = window.TDOF.chf;
  const { items, sub, saved, ship, total } = useTotals(state);
  const f = state.form;
  const set = (k) => (v) => actions.setForm({ ...f, [k]: v });
  const ready = f.vorname && f.nachname && f.email && state.agreed &&
    (state.fulfilment === "abholung" || (f.strasse && f.plz && f.ort));
  const [sending, setSending] = React.useState(false);
  const [fallback, setFallback] = React.useState("");

  const submit = async () => {
    setSending(true); setFallback("");
    const order = buildOrder(state, items, { sub, saved, ship, total });
    try {
      const r = await fetch(ORDER_ENDPOINT, {
        method: "POST",
        headers: { "Content-Type": "application/json", Accept: "application/json" },
        body: JSON.stringify(order.fields),
      });
      if (!r.ok) throw new Error("HTTP " + r.status);
      setSending(false);
      onPlace(order.ref);
    } catch (e) {
      setSending(false);
      setFallback(order.mailto);
    }
  };

  return (
    <div style={{ ...wrap, paddingTop: 22, paddingBottom: 44 }}>
      <button type="button" onClick={onBack} style={{ background: "none", border: "none", padding: "8px 0", cursor: "pointer", fontFamily: "var(--font-core)", fontSize: 15, color: "var(--edvin-green)", marginBottom: 8 }}>‹ Warenkorb</button>
      <H1>Bestellung abschliessen</H1>
      <p style={{ margin: "0 0 30px", fontSize: 15, lineHeight: 1.5, color: "var(--edvin-gray-900)" }}>
        {items.length} Position{items.length === 1 ? "" : "en"} · {chf(total)} — keine Zahlung nötig, die Rechnung folgt.
      </p>

      <section style={{ marginBottom: 32 }}>
        <H2>Lieferung oder Abholung</H2>
        <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
          <Choice checked={state.fulfilment === "lieferung"} onChange={() => actions.setFulfilment("lieferung")}
            title="Lieferung" sub="CHF 9.90 pauschal, ab CHF 180.– gratis" />
          <Choice checked={state.fulfilment === "abholung"} onChange={() => actions.setFulfilment("abholung")}
            title="Abholung Weinladen Aarau" sub="Rohrerstrasse 64 · bereit ab Mi, 10. Dezember" />
        </div>
      </section>

      <section style={{ marginBottom: 32 }}>
        <H2>Persönliche Angaben</H2>
        <form autoComplete="on" onSubmit={(e) => e.preventDefault()} style={{ display: "grid", gap: 12, gridTemplateColumns: "repeat(auto-fit,minmax(220px,1fr))" }}>
          <Field label="Anrede" autoComplete="honorific-prefix" options={["Frau", "Herr", "Keine Anrede"]} value={f.anrede} onChange={set("anrede")} />
          <Field label="Firma (optional)" autoComplete="organization" value={f.firma} onChange={set("firma")} />
          <Field label="Vorname" autoComplete="given-name" value={f.vorname} onChange={set("vorname")} />
          <Field label="Nachname" autoComplete="family-name" value={f.nachname} onChange={set("nachname")} />
          {state.fulfilment === "lieferung" && <Field label="Strasse / Nr." autoComplete="street-address" value={f.strasse} onChange={set("strasse")} />}
          {state.fulfilment === "lieferung" && <Field label="PLZ" autoComplete="postal-code" inputMode="numeric" value={f.plz} onChange={set("plz")} />}
          {state.fulfilment === "lieferung" && <Field label="Ort" autoComplete="address-level2" value={f.ort} onChange={set("ort")} />}
          <Field label="Telefon" type="tel" autoComplete="tel" inputMode="tel" value={f.telefon} onChange={set("telefon")} />
          <Field label="E-Mail" type="email" autoComplete="email" inputMode="email" value={f.email} onChange={set("email")} />
        </form>
        <div style={{ marginTop: 12 }}><Field label="Bemerkungen" multiline value={f.bemerkung} onChange={set("bemerkung")} /></div>
      </section>

      <section style={{ marginBottom: 10 }}><Totals sub={sub} ship={ship} total={total} saved={saved} /></section>

      <BigCheck checked={state.agreed} onChange={actions.setAgreed}>
        Ich bin mindestens 18 Jahre alt und akzeptiere die Konditionen.
      </BigCheck>
      <div style={{ marginTop: 12 }}><PrimaryButton disabled={!ready || sending} onClick={submit}>{sending ? "Wird übermittelt …" : "Bestellung übermitteln"}</PrimaryButton></div>
      {fallback && (
        <div style={{ marginTop: 16, padding: 16, borderRadius: 12, background: "var(--edvin-gray-100)" }}>
          <p style={{ margin: "0 0 12px", fontSize: 14, lineHeight: 1.5 }}>
            Der Versand hat nicht geklappt — keine Verbindung. Schick die Bestellung direkt per E-Mail, sie ist bereits ausgefüllt.
          </p>
          <a href={fallback} style={{
            display: "grid", placeItems: "center", height: 50, borderRadius: 12, textDecoration: "none",
            background: "var(--edvin-green)", color: "#fff", fontWeight: 700, fontSize: 15,
            textTransform: "uppercase", letterSpacing: ".06em",
          }}>E-Mail öffnen</a>
        </div>
      )}
      <p style={{ marginTop: 14, fontSize: 12, color: "var(--edvin-gray-900)", lineHeight: 1.55 }}>
        Nicht mit Monatsaktionen, anderen Rabatten oder Gutscheinen kumulierbar.
      </p>
    </div>
  );
}

function ConfirmView({ onBack, orderRef }) {
  const wrap = window.TDOF_WRAP;
  return (
    <div style={{ ...wrap, paddingTop: 72, paddingBottom: 90, textAlign: "center" }}>
      <div style={{ width: 68, height: 68, margin: "0 auto 24px", borderRadius: "50%", background: "var(--edvin-green)", color: "#fff", display: "grid", placeItems: "center", fontSize: 30 }}>✓</div>
      <h1 style={{ margin: "0 0 12px", fontSize: 30, textTransform: "uppercase", lineHeight: 1.05, ...LIGHT }}>Danke.<br />Bestellung erfasst.</h1>
      {orderRef && <p style={{ margin: "0 0 14px", fontSize: 13, letterSpacing: ".06em", color: "var(--edvin-green)", fontWeight: 700 }}>{orderRef}</p>}
      <p style={{ margin: "0 auto 30px", maxWidth: 420, fontSize: 15, lineHeight: 1.55, color: "var(--edvin-gray-900)" }}>
        Deine Bestellung ist bei uns eingegangen, eine Kopie liegt in deinem Postfach. Die Rechnung folgt mit der Lieferung. Merkliste und Notizen bleiben gespeichert.
      </p>
      <div style={{ maxWidth: 300, margin: "0 auto" }}><PrimaryButton tone="green" onClick={onBack}>Weiter degustieren</PrimaryButton></div>
    </div>
  );
}

Object.assign(window, {
  TdofCartView: CartView, TdofCheckoutView: CheckoutView, TdofConfirmView: ConfirmView,
  TdofField: Field, TdofPrimaryButton: PrimaryButton, TdofH1: H1, TdofH2: H2,
});
