/* global React, Icon, chf */
// ACN-Cars · Page: Booking (multi-step) + live calculator + smart hints

const DOW_LABELS_DE = ["Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag"];

// Findet das nächste Datum mit Wochentag = targetDow (0..6) ab Startdatum (inkl. heute)
function nextDateForDow(start, targetDow, hour) {
  const d = new Date(start.getTime());
  d.setHours(hour || 9, 0, 0, 0);
  // Wenn Startdatum bereits dieser Wochentag ist UND Zeit >= jetzt: nimm es. Sonst suche das nächste Vorkommen.
  let diff = (targetDow - d.getDay() + 7) % 7;
  if (diff === 0 && d.getTime() < start.getTime()) diff = 7;
  d.setDate(d.getDate() + diff);
  return d;
}
function toLocalIso(d) {
  const off = d.getTimezoneOffset();
  const local = new Date(d.getTime() - off * 60 * 1000);
  return local.toISOString().slice(0, 16);
}

function BookingPage({ vehicles, addons, locations, initialVehicleId, dealSeed, tierHours, contact, onComplete, onHome, onFleet }) {
  // v2.2.29 — Fallback wenn contact-prop fehlt (alte Aufrufe).
  contact = contact || (window.ACN_DATA && window.ACN_DATA.contact) || {};
  const boot = (window.ACN_DATA && window.ACN_DATA.boot) || {};
  const vatRate = (typeof boot.vatRate === "number" ? boot.vatRate : 8.1) / 100;
  const showLocations = !!boot.showLocations;
  const smartHints = boot.smartHints || {};

  // v2.2.4 — Aktive Wochenend-Aktion (über Aktions-CTA reingekommen)
  const weekendDeal = (dealSeed && dealSeed.isWeekend && dealSeed.weekend) ? dealSeed : null;
  const w = weekendDeal ? weekendDeal.weekend : null;
  const bonusEnabled = !!(w && w.bonusEnabled && w.bonusDay !== w.returnDay);

  // Default-Termine: morgen + 24h. Bei Aktion: nächster passender Wochentag/Stunde.
  // v2.2.6 — Tier-Hint aus VehicleCard: tierHours bestimmt initialReturn = pickup + tierHours
  const tomorrow = new Date(Date.now() + 24 * 3600 * 1000);
  const initialDurationH = (tierHours && tierHours > 0) ? tierHours : 24;
  const tPlusInitial = new Date(tomorrow.getTime() + initialDurationH * 3600 * 1000);

  let initialPickup = tomorrow;
  let initialReturn = tPlusInitial;
  if (weekendDeal && w) {
    const pStart = new Date(Date.now() + 24 * 3600 * 1000); // ab morgen
    const pickup = nextDateForDow(pStart, w.pickupDay, w.pickupHour || 9);
    const ret = nextDateForDow(pickup, w.returnDay, w.returnHour || 18);
    if (ret.getTime() <= pickup.getTime()) ret.setDate(ret.getDate() + 7);
    initialPickup = pickup;
    initialReturn = ret;
  }

  // Wenn ein Fahrzeug bereits vorausgewählt wurde (z.B. aus Fahrzeug-Karte heraus), Step 2 (Fahrzeug-Wahl) überspringen
  // → Nutzer startet trotzdem bei Step 1 (Daten), Stepper zeigt nur 3 Schritte (Daten → Extras → Bestätigung)
  const hasPreselected = !!initialVehicleId && vehicles.some(v => v.id === initialVehicleId);
  const [step, setStep] = React.useState(1);
  // v2.2.4 — Bonus-Tag-Toggle (verlängert die Aktion um den optionalen Bonus-Tag, z. B. Mo)
  const [useBonusDay, setUseBonusDay] = React.useState(false);
  const [data, setData] = React.useState({
    pickupLoc: locations[0],
    returnLoc: locations[0],
    pickupAt: toLocalIso(initialPickup),
    returnAt: toLocalIso(initialReturn),
    vehicleId: initialVehicleId || vehicles[0].id,
    addons: addons.filter(a => a.default || a.locked).map(a => a.id),
    extraKm: 0,
    name: "",
    email: "",
    phone: "",
    license: "",
    message: "",
    consent: false,
    website: "", // Honeypot
  });

  // v2.2.4 — Bonus-Tag An/Aus → returnAt entsprechend setzen
  React.useEffect(() => {
    if (!weekendDeal || !w || !bonusEnabled) return;
    const pickupDate = new Date(data.pickupAt);
    if (isNaN(pickupDate.getTime())) return;
    const targetDow = useBonusDay ? w.bonusDay : w.returnDay;
    const targetHour = useBonusDay ? (w.returnHour || 18) : (w.returnHour || 18);
    const newReturn = nextDateForDow(pickupDate, targetDow, targetHour);
    if (newReturn.getTime() <= pickupDate.getTime()) {
      newReturn.setDate(newReturn.getDate() + 7);
    }
    const newReturnIso = toLocalIso(newReturn);
    if (newReturnIso !== data.returnAt) {
      setData(d => ({ ...d, returnAt: newReturnIso }));
    }
    // eslint-disable-next-line
  }, [useBonusDay]);

  // Server-Quote (mit Smart-Rabatten) — wird bei jedem Datums/Fahrzeug/Addon-Wechsel neu geholt
  const [serverQuote, setServerQuote] = React.useState(null);
  const [quoting, setQuoting] = React.useState(false);

  React.useEffect(() => {
    if (!boot.apiBase) return;
    let cancelled = false;
    setQuoting(true);
    const controller = new AbortController();
    const t = setTimeout(() => {
      fetch(boot.apiBase + "/quote", {
        method: "POST",
        headers: { "Content-Type": "application/json", "X-WP-Nonce": boot.nonce },
        body: JSON.stringify({
          vehicle_id: data.vehicleId,
          pickup_at:  data.pickupAt,
          return_at:  data.returnAt,
          addons:     data.addons,
          extra_km:   parseInt(data.extraKm || 0, 10),
          // v2.2.37 — Aktion-Kontext mitsenden, damit Weekend-Pauschale auch
          // bei abweichenden Wochentagen greift (z. B. Fr→So obwohl Aktion
          // Fr→Mo konfiguriert ist).
          deal_id:    weekendDeal ? weekendDeal.id : "",
        }),
        signal: controller.signal,
      })
      .then(r => r.json())
      .then(j => { if (!cancelled) setServerQuote(j); })
      .catch(() => { /* silent */ })
      .finally(() => { if (!cancelled) setQuoting(false); });
    }, 250); // Debounce
    return () => { cancelled = true; clearTimeout(t); controller.abort(); };
  }, [data.vehicleId, data.pickupAt, data.returnAt, data.addons.join(","), data.extraKm, weekendDeal && weekendDeal.id, boot.apiBase]);

  const update = (k, v) => setData(d => ({ ...d, [k]: v }));
  const toggleAddon = (id) => {
    setData(d => {
      const a = addons.find(x => x.id === id);
      if (a && a.locked) return d; // locked Addons können nicht abgewählt werden
      const has = d.addons.includes(id);
      return { ...d, addons: has ? d.addons.filter(x => x !== id) : [...d.addons, id] };
    });
  };

  const vehicle = vehicles.find(v => v.id === data.vehicleId) || vehicles[0];
  const minHours = Math.max(1, parseInt(vehicle.minHours || (vehicle.minDays ? vehicle.minDays * 24 : 24), 10));
  const minDays  = Math.max(1, Math.ceil(minHours / 24));
  const rawHours = Math.round((new Date(data.returnAt) - new Date(data.pickupAt)) / (1000 * 60 * 60));
  const hours    = Math.max(1, rawHours);
  const days     = Math.max(1, Math.ceil(hours / 24));
  const tooShort = hours < minHours;

  // Lokale Berechnung als Fallback / Sofortige Anzeige
  // Auto-pick: günstigeres Modell aus (Stunden × Stundenpreis) vs (Tage × Tagespreis)
  const pricePerHour = vehicle.pricePerHour || 0;
  const baseDayTotal  = vehicle.pricePerDay * days;
  const baseHourTotal = pricePerHour > 0 ? pricePerHour * hours : 0;
  let priceMode = "day";
  let baseTotal = baseDayTotal;
  if (pricePerHour > 0 && baseHourTotal > 0 && baseHourTotal < baseDayTotal) {
    priceMode = "hour";
    baseTotal = baseHourTotal;
  }
  const addonTotal = data.addons.reduce((sum, id) => {
    const a = addons.find(x => x.id === id);
    if (!a) return sum;
    return sum + (a.per === "Tag" ? a.price * days : a.price);
  }, 0);

  // Server-Werte bevorzugen, wenn vorhanden
  const sq = serverQuote && !serverQuote.code ? serverQuote : null;
  const extraKmCost = sq ? (sq.extraKmCost || 0) : 0;
  const kmIncluded  = sq ? (sq.kmIncluded || 0) : 0;
  const extraKmPrice= sq ? (sq.extraKmPrice || 1.5) : (vehicle.kmExtraPrice || 1.5);
  const subtotal_pre   = sq ? (sq.baseTotal + sq.addonTotal + extraKmCost) : (baseTotal + addonTotal);
  const discountAmount = sq ? (sq.discountAmount || 0) : 0;
  const discountPct    = sq ? (sq.discountPct || 0)    : 0;
  const appliedDisc    = sq ? (sq.appliedDiscounts || []) : [];
  const hourTip        = sq ? (sq.hourTip || null) : null;
  const weekendApplied = sq ? !!sq.weekendApplied : false;
  const weekendLabel   = sq ? (sq.weekendLabel || "") : "";
  const weekendBonusUsed = sq ? !!sq.weekendBonusUsed : false;
  const weekendBonusSurcharge = sq ? (sq.weekendBonusSurcharge || 0) : 0;
  const afterHoursCost = sq ? (sq.afterHoursCost || 0) : 0;
  const afterHoursReasons = sq ? (sq.afterHoursReasons || []) : [];
  // Preise sind INKL. MwSt — Total = Brutto, MwSt wird daraus extrahiert.
  const total          = sq ? sq.total : (baseTotal + addonTotal);
  const subtotal       = sq ? sq.subtotal : Math.round(total / (1 + vatRate));
  const vat            = sq ? sq.vat   : (total - subtotal);
  const sqHours        = sq && typeof sq.hours === "number" ? sq.hours : hours;
  const sqMode         = sq && sq.priceMode ? sq.priceMode : priceMode;

  // v2.2.6 — Tier / Inquiry-Mode aus Server-Quote
  const isInquiry        = sq ? !!sq.isInquiry : false;
  const inquiryThresholdH= sq ? (sq.inquiryThresholdH || 168) : (vehicle.inquiryThresholdH || 168);
  const tierMatched      = sq ? !!sq.tierMatched : false;
  // Achtung: NICHT tierHours nennen — Kollision mit dem Prop weiter oben würde
  // einen SyntaxError („Identifier already declared") werfen und das ganze Bundle killen.
  const matchedTierHours = sq ? (sq.tierHours || null) : null;

  const summary = {
    vehicle, days, hours: sqHours, priceMode: sqMode,
    pricePerHour,
    baseTotal: sq ? sq.baseTotal : baseTotal,
    addonTotal: sq ? sq.addonTotal : addonTotal,
    extraKm: parseInt(data.extraKm || 0, 10),
    extraKmCost, kmIncluded, extraKmPrice,
    subtotal_pre, discountAmount, discountPct, appliedDisc, hourTip,
    weekendApplied, weekendLabel, weekendBonusUsed, weekendBonusSurcharge,
    afterHoursCost, afterHoursReasons,
    subtotal, vat, total, vatRate, minDays, minHours, tooShort, quoting,
    // v2.2.6
    isInquiry, inquiryThresholdH, tierMatched, tierHours: matchedTierHours,
  };

  // Stepper — Fahrzeug nur anzeigen wenn nicht vorausgewählt (oder wenn Nutzer dort schon war)
  const stepperItems = hasPreselected
    ? [
        { n: 1, l: "Daten" },
        { n: 3, l: "Extras" },
        { n: 4, l: "Bestätigung" },
      ]
    : [
        { n: 1, l: "Daten" },
        { n: 2, l: "Fahrzeug" },
        { n: 3, l: "Extras" },
        { n: 4, l: "Bestätigung" },
      ];

  return (
    <main className="section">
      <div className="container">
        {/* Back-Navigation oben — schnell zurück zur Startseite oder Flotte */}
        <div className="booking-back-bar">
          <button
            type="button"
            className="back-link"
            onClick={() => onHome && onHome()}
            aria-label="Zurück zur Startseite"
          >
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M19 12H5M12 19l-7-7 7-7"/></svg>
            <span>Zurück zur Startseite</span>
          </button>
          {onFleet && (
            <button
              type="button"
              className="back-link back-link-secondary"
              onClick={() => onFleet()}
              aria-label="Zurück zur Flotte"
            >
              <span>Andere Fahrzeuge ansehen</span>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M5 12h14M12 5l7 7-7 7"/></svg>
            </button>
          )}
        </div>

        {/* v2.2.3 — Buchungs-Hero: Auto-Bild + Marke/Modell + Specs + Trust-Badges */}
        {hasPreselected ? (
          <div className="booking-hero" style={{ backgroundImage: `linear-gradient(120deg, rgba(8,10,14,0.85) 0%, rgba(8,10,14,0.55) 55%, rgba(8,10,14,0.25) 100%), url(${vehicle.image})` }}>
            <div className="booking-hero-content">
              <div className="booking-hero-eyebrow">
                <span className="booking-hero-tag">Reservierung</span>
                {vehicle.dealPct > 0 && <span className="booking-hero-deal">−{vehicle.dealPct}% Deal</span>}
              </div>
              <div className="booking-hero-brand">{vehicle.brand}</div>
              <h1 className="booking-hero-title">{vehicle.model}</h1>
              {vehicle.tagline && <p className="booking-hero-sub">{vehicle.tagline}</p>}
              <div className="booking-hero-specs">
                <span className="booking-hero-spec">
                  <Icon.Bolt /> {vehicle.power} PS
                </span>
                <span className="booking-hero-spec">{vehicle.transmission}</span>
                <span className="booking-hero-spec">{vehicle.fuel}</span>
                <span className="booking-hero-spec">{vehicle.seats} Plätze</span>
                <span className="booking-hero-spec booking-hero-price">
                  ab CHF {chf(vehicle.pricePerDay)}/Tag
                </span>
              </div>
              <div className="booking-hero-trust">
                <div className="trust-badge">
                  <span className="trust-icon"><Icon.Clock /></span>
                  <div>
                    <strong>Sofort-Bestätigung</strong>
                    <span>innerhalb von 2 Std</span>
                  </div>
                </div>
                <div className="trust-badge">
                  <span className="trust-icon"><Icon.Shield /></span>
                  <div>
                    <strong>Vollkasko inkl.</strong>
                    <span>Versicherung enthalten</span>
                  </div>
                </div>
                <div className="trust-badge">
                  <span className="trust-icon"><Icon.Handshake /></span>
                  <div>
                    <strong>Persönliche Übergabe</strong>
                    <span>am Standort Neuhausen</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        ) : (
          <>
            <div className="eyebrow" style={{ marginBottom: 12 }}>Buchung</div>
            <h1 className="h-1" style={{ margin: 0, marginBottom: 32 }}>
              Reservierung in 4 Schritten.
            </h1>
          </>
        )}

        {/* v2.2.4 — Aktions-Banner (Weekend-Pauschale aus Aktions-CTA) */}
        {weekendDeal && w && (
          <div className="deal-active-banner">
            <div className="deal-active-banner-icon"><Icon.Sparkle /></div>
            <div className="deal-active-banner-body">
              <div className="deal-active-banner-title">
                Aktion aktiv: {weekendDeal.title}
              </div>
              <div className="deal-active-banner-sub">
                Diese Pauschale gilt für Abholung am <strong>{DOW_LABELS_DE[w.pickupDay] || "—"}</strong>
                {" "}({String(w.pickupHour || 9).padStart(2, "0")}:00 Uhr) und Rückgabe am
                {" "}<strong>{DOW_LABELS_DE[w.returnDay] || "—"}</strong>
                {" "}({String(w.returnHour || 18).padStart(2, "0")}:00 Uhr).
                {" "}Wir haben die Daten passend vorausgefüllt – Sie können sie aber jederzeit anpassen.
              </div>
              {bonusEnabled && (() => {
                // v2.2.5 — Saldo: After-Hours-Fee fällt durch späteren Werktag-Rückgabe weg
                // Saldo (negativ = Kunde spart). Wir zeigen ihn nur, wenn After-Hours aktiv ist
                // UND der Bonus-Tag wirklich innerhalb der Öffnungszeiten liegt.
                const ahEnabled = !!(boot.afterHours && boot.afterHours.enabled);
                const ahFee = ahEnabled ? (boot.afterHours.fee || 0) : 0;
                const surcharge = parseInt(w.bonusSurcharge || 0, 10);
                const showSaldo = ahFee > 0;
                const saved = ahFee;
                const net = saved - surcharge;
                return (
                  <>
                    <label className="deal-active-banner-toggle">
                      <input
                        type="checkbox"
                        checked={useBonusDay}
                        onChange={e => setUseBonusDay(e.target.checked)}
                      />
                      <span>
                        <strong>Bonus-Tag dazu:</strong> Rückgabe erst {DOW_LABELS_DE[w.bonusDay] || "—"}
                        {surcharge > 0
                          ? <> &nbsp;(+CHF {chf(surcharge)} Aufpreis)</>
                          : <> &nbsp;(ohne Aufpreis)</>}
                      </span>
                    </label>
                    {showSaldo && (
                      <div className="deal-active-banner-saldo">
                        {net > 0 ? (
                          <>
                            <Icon.Bolt />
                            <span>
                              <strong>Effektiv CHF {chf(net)} günstiger:</strong>
                              {" "}Sonntag-Rückgabe wäre After-Hours <strong>(+CHF {chf(saved)})</strong>
                              {surcharge > 0 ? <> – Bonus-Aufpreis CHF {chf(surcharge)}</> : null}
                              {" "}= Sie sparen CHF {chf(net)}.
                            </span>
                          </>
                        ) : net === 0 ? (
                          <>
                            <Icon.Info />
                            <span>
                              Bonus-Tag ist preisneutral: After-Hours fällt weg
                              {" "}(−CHF {chf(saved)}), Aufpreis CHF {chf(surcharge)} gleicht das aus.
                            </span>
                          </>
                        ) : (
                          <>
                            <Icon.Info />
                            <span>
                              Bonus-Tag kostet effektiv CHF {chf(-net)} mehr
                              {" "}(After-Hours wäre −CHF {chf(saved)}, Aufpreis +CHF {chf(surcharge)}).
                            </span>
                          </>
                        )}
                      </div>
                    )}
                  </>
                );
              })()}
            </div>
          </div>
        )}

        {/* Stepper */}
        <div className="stepper" style={{ marginBottom: 48, flexWrap: "wrap" }}>
          {stepperItems.map((s, i, arr) => (
            <React.Fragment key={s.n}>
              <button
                className="stepper-item"
                data-state={step === s.n ? "active" : step > s.n ? "done" : ""}
                onClick={() => s.n <= step && setStep(s.n)}
                style={{ background: "none", border: 0, padding: 0, cursor: s.n <= step ? "pointer" : "default" }}
              >
                <span className="stepper-num">{step > s.n ? <Icon.Check /> : (i + 1)}</span>
                {s.l}
              </button>
              {i < arr.length - 1 && <div className="stepper-line" />}
            </React.Fragment>
          ))}
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "1fr 380px", gap: 48, alignItems: "start" }} className="booking-grid">
          <div>
            {step === 1 && (
              <Step1
                data={data} update={update}
                locations={locations} showLocations={showLocations}
                summary={summary}
                onNext={() => setStep(hasPreselected ? 3 : 2)}
                weekendActive={!!weekendDeal}
              />
            )}
            {step === 2 && !hasPreselected && (
              <Step2
                data={data} update={update}
                vehicles={vehicles}
                onNext={() => setStep(3)} onBack={() => setStep(1)}
              />
            )}
            {step === 3 && (
              <Step3
                data={data} addons={addons} toggleAddon={toggleAddon}
                onNext={() => setStep(4)}
                onBack={() => setStep(hasPreselected ? 1 : 2)}
              />
            )}
            {step === 4 && (
              <Step4
                data={data} update={update} summary={summary} addons={addons}
                locations={locations} contact={contact}
                onConfirm={onComplete} onBack={() => setStep(3)}
              />
            )}
          </div>
          {/* Summary-Sidebar wird unten gerendert (wegen Reihenfolge im DOM/CSS) */}

          <Summary
            summary={summary} addons={addons} selectedAddons={data.addons}
            pickupLoc={data.pickupLoc} pickupAt={data.pickupAt} returnAt={data.returnAt}
          />
        </div>
      </div>
    </main>
  );
}

// v2.2.5 — Doppel-Slider für Mietdauer (Tage 0-30 + Stunden 0-23)
// onChangeHours(totalHours) — totalHours = days*24 + hours, mindestens 1
function DurationSlider({ hours, onChangeHours, maxDays }) {
  const safeMax = Math.max(1, parseInt(maxDays || 30, 10));
  const total = Math.max(1, parseInt(hours || 1, 10));
  const days = Math.floor(total / 24);
  const extraH = total - days * 24;
  const setDays = (d) => {
    const next = Math.max(0, Math.min(safeMax, parseInt(d, 10)));
    onChangeHours && onChangeHours(Math.max(1, next * 24 + extraH));
  };
  const setHours = (h) => {
    const next = Math.max(0, Math.min(23, parseInt(h, 10)));
    onChangeHours && onChangeHours(Math.max(1, days * 24 + next));
  };
  // Schöne Label-Anzeige
  const label = days > 0
    ? (extraH > 0 ? `${days} Tag${days === 1 ? "" : "e"} ${extraH} Std` : `${days} Tag${days === 1 ? "" : "e"}`)
    : `${extraH || 1} Std`;
  return (
    <div className="dur-slider">
      <div className="dur-slider-head">
        <div>
          <div className="eyebrow">Mietdauer</div>
          <div className="dur-slider-readout">{label}</div>
        </div>
        <div className="dur-slider-meta">
          <span>{days * 24 + extraH} Std</span>
        </div>
      </div>
      <div className="dur-slider-row">
        <div className="dur-slider-label">
          <span>Tage</span>
          <strong>{days}</strong>
          <span className="dur-slider-range">/ {safeMax}</span>
        </div>
        <input
          type="range"
          className="dur-slider-input"
          min="0"
          max={safeMax}
          step="1"
          value={days}
          onChange={(e) => setDays(e.target.value)}
          aria-label="Tage"
        />
      </div>
      <div className="dur-slider-row">
        <div className="dur-slider-label">
          <span>Stunden</span>
          <strong>{extraH}</strong>
          <span className="dur-slider-range">/ 23</span>
        </div>
        <input
          type="range"
          className="dur-slider-input"
          min="0"
          max="23"
          step="1"
          value={extraH}
          onChange={(e) => setHours(e.target.value)}
          aria-label="Zusätzliche Stunden"
        />
      </div>
    </div>
  );
}
window.DurationSlider = DurationSlider;

function Step1({ data, update, locations, showLocations, summary, onNext, weekendActive }) {
  // Mietdauer-Buckets für Schnellauswahl-Pills (kürzere Auswahl als Dropdown — die typischen Fälle)
  const buckets = [
    { hours: 3,   label: "3 Std" },
    { hours: 6,   label: "6 Std" },
    { hours: 24,  label: "1 Tag" },
    { hours: 48,  label: "2 Tage" },
    { hours: 168, label: "1 Woche" },
  ];
  // v2.2.20 — Mietdauer-Dropdown (statt Doppel-Slider). Optionen wie SC Sportcars:
  //   3H / 6H / 12H / 24H (1 Tag) / 48H (2 Tage) / 72H (3 Tage) / 96H (4 Tage) /
  //   120H (5 Tage) / Länger (Anfrage)
  const durationOptions = [
    { value: "3",      hours: 3,   label: "3 Stunden" },
    { value: "6",      hours: 6,   label: "6 Stunden" },
    { value: "12",     hours: 12,  label: "12 Stunden" },
    { value: "24",     hours: 24,  label: "24 Stunden (1 Tag)" },
    { value: "48",     hours: 48,  label: "48 Stunden (2 Tage)" },
    { value: "72",     hours: 72,  label: "72 Stunden (3 Tage)" },
    { value: "96",     hours: 96,  label: "96 Stunden (4 Tage)" },
    { value: "120",    hours: 120, label: "120 Stunden (5 Tage)" },
    { value: "longer", hours: 192, label: "Länger – auf Anfrage" },
  ];
  const currentHours = Math.max(1, Math.round((new Date(data.returnAt) - new Date(data.pickupAt)) / 3600000));
  const setHours = (h) => {
    const start = new Date(data.pickupAt);
    if (isNaN(start.getTime())) return;
    const end = new Date(start.getTime() + h * 3600 * 1000);
    const off = end.getTimezoneOffset();
    const local = new Date(end.getTime() - off * 60 * 1000);
    update("returnAt", local.toISOString().slice(0, 16));
  };
  const setBucket = (h) => setHours(h);
  // Aktuell gewählten Wert auf eine Dropdown-Option matchen, sonst "custom" (zeigt aktuellen Wert an)
  const matchedDuration = durationOptions.find(o => o.hours === currentHours);
  const durationSelectValue = matchedDuration
    ? matchedDuration.value
    : (currentHours > 120 ? "longer" : "custom");
  const handleDurationChange = (val) => {
    if (val === "custom") return;
    const opt = durationOptions.find(o => o.value === val);
    if (opt) setHours(opt.hours);
  };

  // v2.2.6 — Tier-Preise des aktuell gewählten Fahrzeugs
  const v = summary && summary.vehicle ? summary.vehicle : null;
  const tp = (v && v.tierPrices) ? v.tierPrices : {};
  const tierDefs = [
    { hours: 3,   label: "3 Std",   price: tp["3"] },
    { hours: 6,   label: "6 Std",   price: tp["6"] },
    { hours: 24,  label: "1 Tag",   price: tp["24"] },
    { hours: 168, label: "1 Woche", price: tp["168"] },
  ].filter(t => t.price && t.price > 0);
  const hasTiers = tierDefs.length > 0;
  const inquiryThresholdH = (v && v.inquiryThresholdH) ? v.inquiryThresholdH : 168;
  const isInquiry = inquiryThresholdH > 0 && currentHours > inquiryThresholdH;
  return (
    <div>
      <div className="h-2" style={{ margin: "0 0 24px" }}>Wann{showLocations ? " und wo" : ""}?</div>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }} className="booking-fields">
        {showLocations && (
          <>
            <div className="field">
              <label>Abholort</label>
              <select className="select" value={data.pickupLoc} onChange={e => update("pickupLoc", e.target.value)}>
                {locations.map(l => <option key={l}>{l}</option>)}
              </select>
            </div>
            <div className="field">
              <label>Rückgabeort</label>
              <select className="select" value={data.returnLoc} onChange={e => update("returnLoc", e.target.value)}>
                {locations.map(l => <option key={l}>{l}</option>)}
              </select>
            </div>
          </>
        )}
        {!showLocations && (
          <div className="field" style={{ gridColumn: "1 / -1" }}>
            <label>Standort</label>
            <div className="loc-display">
              <Icon.Map /> {locations[0]}
              <span style={{ color: "var(--ink-3)", fontSize: 12, marginLeft: 8 }}>
                · Abholung & Rückgabe am gleichen Standort
              </span>
            </div>
          </div>
        )}
        {/* v2.2.21 — Datum + Zeit prominenter (eyebrow-Label + grössere Box,
            konsistent mit dem Mietdauer-Feld darunter)
            v2.2.41 — Im Aktion-Slot-Modus (weekendActive) sind die Felder
            readOnly und visuell als „fixiert" markiert. Der Slot wurde von
            der Aktion-Karte vorgegeben und darf nicht editiert werden. */}
        <div className={"field field-prominent" + (weekendActive ? " field-prominent--locked" : "")}>
          <label className="field-prominent-label">
            Abholung — Datum &amp; Zeit
            {weekendActive && <span className="field-locked-hint" aria-label="Aktion-Slot fixiert"><Icon.Sparkle /> Aktion-Slot</span>}
          </label>
          <input
            className="input input-prominent"
            type="datetime-local"
            value={data.pickupAt}
            readOnly={weekendActive}
            disabled={weekendActive}
            onChange={e => update("pickupAt", e.target.value)}
          />
        </div>
        <div className={"field field-prominent" + (weekendActive ? " field-prominent--locked" : "")}>
          <label className="field-prominent-label">
            Rückgabe — Datum &amp; Zeit
            {weekendActive && <span className="field-locked-hint" aria-label="Aktion-Slot fixiert"><Icon.Sparkle /> Aktion-Slot</span>}
          </label>
          <input
            className="input input-prominent"
            type="datetime-local"
            value={data.returnAt}
            readOnly={weekendActive}
            disabled={weekendActive}
            onChange={e => update("returnAt", e.target.value)}
          />
        </div>
        {weekendActive && (
          <div className="field-prominent-slot-hint" style={{ gridColumn: "1 / -1" }}>
            <Icon.Info />
            <span>
              Aktion-Slot fixiert. Diese Daten kommen aus der Aktion und sind nicht änderbar.
              Brauchst du einen anderen Zeitraum? Buche das Fahrzeug regulär ohne Aktion.
            </span>
          </div>
        )}
      </div>

      {/* v2.2.5 — Im Weekend-Modus: keine Mietdauer-Auswahl (Pauschalpreis ist fix) */}
      {!weekendActive && (
        <div style={{ marginTop: 16 }}>
          {/* v2.2.7 — Tier-Pauschalen-Pills entfernt: nur noch Slider + Schnellauswahl,
              um die UI klarer zu halten. Der Slider rastet auf den Tier-Stunden ein
              (siehe DurationSlider) und der Server-Quote zeigt den passenden Tier-Preis an. */}

          {/* v2.2.6 — Inquiry-Mode: über Schwelle = Anfrage statt Live-Preis */}
          {isInquiry ? (
            <div className="inquiry-notice">
              <div className="inquiry-notice-icon"><Icon.Info /></div>
              <div>
                <div className="inquiry-notice-title">Längere Mieten — auf Anfrage</div>
                <div className="inquiry-notice-sub">
                  Über {inquiryThresholdH} Std. ({Math.round(inquiryThresholdH/24)} Tage) erstellen wir gerne ein
                  individuelles Angebot. Senden Sie uns Ihre Anfrage über das Formular — wir melden uns
                  innerhalb von 2 Stunden mit einer persönlichen Offerte.
                </div>
              </div>
            </div>
          ) : null}

          {/* v2.2.20 — Mietdauer-Dropdown (ersetzt den Doppel-Slider)
              v2.2.21 — Box-Wrapper mit prominentem Eyebrow-Header für bessere
              Lesbarkeit und Konsistenz mit den Datum-Feldern. */}
          <div className="duration-select-card">
            <div className="duration-select-card-eyebrow">Mietdauer</div>
            <div className="duration-select-card-title">Wie lange möchtest du fahren?</div>
            <div className="field duration-select-field">
              <select
                className="select duration-select"
                value={durationSelectValue}
                onChange={(e) => handleDurationChange(e.target.value)}
                aria-label="Mietdauer"
              >
                {durationSelectValue === "custom" && (
                  <option value="custom" disabled>
                    {currentHours} Std. (individuell)
                  </option>
                )}
                {durationOptions.map(o => (
                  <option key={o.value} value={o.value}>{o.label}</option>
                ))}
              </select>
              <div className="duration-select-hint">
                Brauchst du etwas dazwischen? Wähle „Länger – auf Anfrage" und wir
                erstellen dir ein individuelles Angebot.
              </div>
            </div>
          </div>
          <div className="duration-quick">
            <span className="duration-quick-label">Schnellauswahl:</span>
            {buckets.map(b => {
              const active = currentHours === b.hours;
              return (
                <button
                  key={b.hours}
                  type="button"
                  className="duration-quick-pill"
                  data-active={active ? "1" : ""}
                  onClick={() => setBucket(b.hours)}
                >
                  {b.label}
                </button>
              );
            })}
          </div>
        </div>
      )}

      {/* Mindestmietdauer-Warnung */}
      {summary && summary.tooShort && (
        <div className="hint hint-warn">
          <Icon.Info />
          Für dieses Fahrzeug beträgt die Mindestmietdauer <strong>{summary.minHours} Std.</strong>
          {" "}Aktuell sind nur {summary.hours} Std. ausgewählt.
        </div>
      )}

      {/* Inkl. km + Extra-km kaufen */}
      <KmBlock
        kmIncluded={summary && summary.kmIncluded}
        extraKm={parseInt(data.extraKm || 0, 10)}
        extraKmPrice={summary && summary.extraKmPrice}
        extraKmCost={summary && summary.extraKmCost}
        onChange={(n) => update("extraKm", Math.max(0, parseInt(n || 0, 10)))}
      />

      {/* Stundenmodus-Hint: günstigerer Stundentarif aktiv */}
      {summary && summary.priceMode === "hour" && summary.pricePerHour > 0 && (
        <div className="hint hint-deal">
          <Icon.Bolt />
          Stundentarif aktiv: {summary.hours} Std. × CHF {chf(summary.pricePerHour)}
          {" "}— günstiger als der Tagestarif für diese Mietdauer.
        </div>
      )}

      {/* Smart-Hint: Stunden-Tipp (weniger als 24h gewählt → Tag günstiger) */}
      {summary && summary.hourTip && (
        <div className="hint hint-info">
          <Icon.Bolt />
          {summary.hourTip.message}
        </div>
      )}

      {/* Smart-Hint: Aktive Rabatte */}
      {summary && summary.appliedDisc && summary.appliedDisc.length > 0 && !summary.weekendApplied && summary.discountAmount > 0 && (
        <div className="hint hint-deal">
          <Icon.Sparkle />
          <strong>Smart-Rabatt aktiv:</strong>{" "}
          {summary.appliedDisc.filter(d => d.kind !== 'weekend_deal').map((d, i) => (
            <span key={i}>
              {i > 0 && ", "}
              {d.label} (−{d.pct}%)
            </span>
          ))}
          {" — Sie sparen CHF "}{chf(summary.discountAmount)}.
        </div>
      )}

      {/* Weekend-Pauschale-Hint */}
      {summary && summary.weekendApplied && (
        <div className="hint hint-deal" style={{ background: "linear-gradient(90deg, color-mix(in srgb, var(--accent) 18%, transparent) 0%, color-mix(in srgb, var(--accent) 6%, transparent) 100%)", borderColor: "var(--accent)" }}>
          <Icon.Sparkle />
          <strong>Weekend-Pauschale aktiv</strong>
          {summary.weekendLabel ? <span>: {summary.weekendLabel}</span> : null}
          {" — alles inklusive für Ihr Wochenende. Pauschalpreis: CHF "}{chf(summary.baseTotal)}.
        </div>
      )}

      {/* After-Hours-Warnung */}
      {summary && summary.afterHoursReasons && summary.afterHoursReasons.length > 0 && (
        <div className="hint hint-warn" style={{ background: "linear-gradient(90deg, rgba(255,138,76,0.15) 0%, rgba(255,138,76,0.05) 100%)", borderColor: "#FF8A4C", color: "var(--ink-1)" }}>
          <Icon.Clock />
          <span>
            <strong>Hinweis:</strong>{" "}
            {summary.afterHoursReasons.map((r, i) => (
              <span key={i}>{i > 0 ? ", " : ""}{r.label}</span>
            ))}
            {" — Aufschlag CHF "}{chf(summary.afterHoursCost)}{" wird der Buchung automatisch hinzugefügt."}
          </span>
        </div>
      )}

      <div style={{ marginTop: 32, display: "flex", justifyContent: "flex-end" }}>
        <button className="btn btn-primary btn-lg" onClick={onNext}>Weiter <Icon.ArrowRight /></button>
      </div>
    </div>
  );
}

function Step2({ data, update, vehicles, onNext, onBack }) {
  return (
    <div>
      <div className="h-2" style={{ margin: "0 0 24px" }}>Welches Fahrzeug?</div>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit,minmax(240px,1fr))", gap: 12 }}>
        {vehicles.map(v => (
          <button
            key={v.id}
            className="card vcard-pick"
            onClick={() => update("vehicleId", v.id)}
            style={{
              textAlign: "left",
              padding: 0,
              cursor: "pointer",
              border: data.vehicleId === v.id ? "2px solid var(--accent)" : "1px solid var(--line)",
              background: "var(--bg-elev)",
              overflow: "hidden",
            }}
          >
            <div style={{ aspectRatio: "16/10", backgroundImage: `url(${v.image})`, backgroundSize: "cover", backgroundPosition: "center" }} />
            <div style={{ padding: 14 }}>
              <div style={{ fontSize: 11, color: "var(--ink-3)", letterSpacing: ".06em", textTransform: "uppercase" }}>{v.brand}</div>
              <div style={{ fontWeight: 600, fontSize: 16, marginTop: 2 }}>{v.model}</div>
              <div style={{ marginTop: 8, fontFamily: "var(--font-display)", fontSize: 18, fontWeight: 600 }}>
                CHF {chf(v.pricePerDay)} <span style={{ fontSize: 12, color: "var(--ink-3)", fontWeight: 400 }}>/Tag</span>
              </div>
            </div>
          </button>
        ))}
      </div>
      <div style={{ marginTop: 32, display: "flex", justifyContent: "space-between" }}>
        <button className="btn btn-ghost btn-lg" onClick={onBack}>Zurück</button>
        <button className="btn btn-primary btn-lg" onClick={onNext}>Weiter <Icon.ArrowRight /></button>
      </div>
    </div>
  );
}

function Step3({ data, addons, toggleAddon, onNext, onBack }) {
  return (
    <div>
      <div className="h-2" style={{ margin: "0 0 24px" }}>Extras & Versicherung</div>
      <div style={{ display: "grid", gap: 8 }}>
        {addons.map(a => {
          const active = data.addons.includes(a.id);
          return (
            <div
              key={a.id}
              onClick={() => !a.locked && toggleAddon(a.id)}
              className="card addon-row"
              style={{
                padding: "16px 20px",
                display: "flex",
                alignItems: "center",
                gap: 16,
                cursor: a.locked ? "default" : "pointer",
                borderColor: active ? "var(--accent)" : "var(--line)",
              }}
            >
              <div style={{
                width: 22, height: 22, borderRadius: 6,
                border: "1.5px solid " + (active ? "var(--accent)" : "var(--line-strong)"),
                background: active ? "var(--accent)" : "transparent",
                color: "var(--bg)",
                display: "grid", placeItems: "center", flexShrink: 0,
              }}>
                {active && <Icon.Check />}
              </div>
              <div style={{ flex: 1 }}>
                <div style={{ fontWeight: 500 }}>{a.label}</div>
                {a.note && <div style={{ fontSize: 13, color: "var(--ink-3)" }}>{a.note}</div>}
              </div>
              <div className="mono" style={{ fontWeight: 600 }}>
                {a.price === 0 ? "Inklusive" : `CHF ${chf(a.price)} / ${a.per}`}
              </div>
            </div>
          );
        })}
      </div>
      <div style={{ marginTop: 32, display: "flex", justifyContent: "space-between" }}>
        <button className="btn btn-ghost btn-lg" onClick={onBack}>Zurück</button>
        <button className="btn btn-primary btn-lg" onClick={onNext}>Weiter <Icon.ArrowRight /></button>
      </div>
    </div>
  );
}

function Step4({ data, update, summary, locations, contact, onConfirm, onBack }) {
  // v2.2.29 — WhatsApp-Vorlage mit Buchungs-Daten füllen
  const fmtDt = (iso) => {
    if (!iso) return "—";
    try {
      const d = new Date(iso);
      const pad = n => String(n).padStart(2, "0");
      return `${pad(d.getDate())}.${pad(d.getMonth() + 1)}.${d.getFullYear()}`;
    } catch { return iso; }
  };
  const fmtTm = (iso) => {
    if (!iso) return "—";
    try {
      const d = new Date(iso);
      const pad = n => String(n).padStart(2, "0");
      return `${pad(d.getHours())}:${pad(d.getMinutes())}`;
    } catch { return ""; }
  };
  const totalH = Math.max(1, Math.round((new Date(data.returnAt) - new Date(data.pickupAt)) / 3600000));
  const days   = Math.floor(totalH / 24);
  const extraH = totalH - days * 24;
  const durationStr = days > 0
    ? (extraH > 0 ? `${days} Tag${days === 1 ? "" : "e"} ${extraH} Std` : `${days} Tag${days === 1 ? "" : "e"}`)
    : `${totalH} Std`;
  const locName = (() => {
    if (!data.pickupLoc) return "Nach Absprache";
    const lst = Array.isArray(locations) ? locations : [];
    const m = lst.find(l => String(l.id) === String(data.pickupLoc));
    return m ? (m.name || m.label || m.title || "Nach Absprache") : "Nach Absprache";
  })();
  const v = summary.vehicle || {};
  const waTpl = (contact && contact.whatsappTemplateBooking)
    ? contact.whatsappTemplateBooking
    : "Hallo ACN-Cars, ich möchte den {brand} {model} buchen. Abholung {pickup_date} bis {return_date}. Total CHF {total_price}. Name: {customer_name}";
  const waText = waTpl
    .replace(/\{brand\}/g,           v.brand || "")
    .replace(/\{model\}/g,           v.model || "")
    .replace(/\{pricePerDay\}/g,     chf(v.pricePerDay))
    .replace(/\{price\}/g,           "CHF " + chf(v.pricePerDay) + "/Tag")
    .replace(/\{pickup_date\}/g,     fmtDt(data.pickupAt))
    .replace(/\{pickup_time\}/g,     fmtTm(data.pickupAt))
    .replace(/\{return_date\}/g,     fmtDt(data.returnAt))
    .replace(/\{return_time\}/g,     fmtTm(data.returnAt))
    .replace(/\{duration\}/g,        durationStr)
    .replace(/\{pickup_location\}/g, locName)
    .replace(/\{total_price\}/g,     chf(summary.total))
    .replace(/\{customer_name\}/g,   data.name || "—");
  const waBase = (contact && contact.whatsappLink)
    ? contact.whatsappLink.split("?")[0]
    : "https://wa.me/41789480304";
  const waUrl = `${waBase}?text=${encodeURIComponent(waText)}`;
  // v2.2.6 — Im Inquiry-Mode ist tooShort egal (kein Live-Preis nötig)
  const can = data.name && data.email && data.phone && data.consent && (summary.isInquiry || !summary.tooShort);
  return (
    <div className="booking-form-card">
      <div className="booking-form-head">
        <div className="booking-form-head-icon"><Icon.User /></div>
        <div>
          <div className="booking-form-eyebrow">Letzter Schritt</div>
          <h2 className="booking-form-title">Ihre Kontaktdaten</h2>
          <p className="booking-form-sub">Wir bestätigen Ihre Anfrage innerhalb von 2 Stunden per E-Mail oder WhatsApp.</p>
        </div>
      </div>

      <div className="booking-form-grid">
        <div className="field-pretty">
          <span className="field-pretty-icon"><Icon.User /></span>
          <input
            className="input-pretty"
            value={data.name}
            onChange={e => update("name", e.target.value)}
            placeholder=" "
            id="acn-name"
          />
          <label htmlFor="acn-name">Vor- und Nachname *</label>
        </div>
        <div className="field-pretty">
          <span className="field-pretty-icon"><Icon.Mail /></span>
          <input
            className="input-pretty"
            type="email"
            value={data.email}
            onChange={e => update("email", e.target.value)}
            placeholder=" "
            id="acn-email"
          />
          <label htmlFor="acn-email">E-Mail *</label>
        </div>
        <div className="field-pretty">
          <span className="field-pretty-icon"><Icon.Phone /></span>
          <input
            className="input-pretty"
            value={data.phone}
            onChange={e => update("phone", e.target.value)}
            placeholder=" "
            id="acn-phone"
          />
          <label htmlFor="acn-phone">Telefon *</label>
        </div>
        <div className="field-pretty">
          <span className="field-pretty-icon"><Icon.Card /></span>
          <input
            className="input-pretty"
            value={data.license}
            onChange={e => update("license", e.target.value)}
            placeholder=" "
            id="acn-license"
          />
          <label htmlFor="acn-license">Führerschein-Nr. (optional)</label>
        </div>
        <div className="field-pretty field-pretty-full">
          <span className="field-pretty-icon"><Icon.MessageSquare /></span>
          <textarea
            className="input-pretty"
            rows="3"
            value={data.message}
            onChange={e => update("message", e.target.value)}
            placeholder=" "
            id="acn-message"
            style={{ resize: "vertical", minHeight: 90, fontFamily: "inherit" }}
          />
          <label htmlFor="acn-message">Besondere Wünsche, Lieferadresse, Fragen…</label>
        </div>
      </div>

      {/* Honeypot — unsichtbar für Menschen */}
      <div style={{ position: "absolute", left: "-9999px", height: 0, overflow: "hidden" }} aria-hidden="true">
        <label>Website</label>
        <input type="text" tabIndex="-1" autoComplete="off" value={data.website} onChange={e => update("website", e.target.value)} />
      </div>

      <div className="booking-trust-row">
        <div className="booking-trust-item">
          <span className="booking-trust-dot" /> Unverbindlich
        </div>
        <div className="booking-trust-item">
          <span className="booking-trust-dot" /> Keine Vorauszahlung
        </div>
        <div className="booking-trust-item">
          <span className="booking-trust-dot" /> Antwort in 2 Std
        </div>
      </div>

      <label className="consent-row">
        <input
          type="checkbox"
          checked={data.consent}
          onChange={e => update("consent", e.target.checked)}
        />
        <span>
          Ich akzeptiere, dass meine Angaben zur Bearbeitung meiner Anfrage gespeichert und per E-Mail übermittelt werden.
          Es entstehen keine Kosten — die Buchung ist erst nach schriftlicher Bestätigung verbindlich.
        </span>
      </label>

      {summary.tooShort && (
        <div className="hint hint-warn">
          <Icon.Info />
          Bitte passen Sie zuerst die Mietdauer an (mindestens {summary.minHours} Std.).
        </div>
      )}

      {/* v2.2.29 — Alternative WhatsApp-Anfrage mit vorgefüllter Buchungs-Übersicht */}
      <a
        href={waUrl}
        target="_blank"
        rel="noopener"
        className="btn btn-lg"
        style={{
          background: "#25D366", color: "#fff", width: "100%",
          marginTop: 12, marginBottom: 12, display: "inline-flex",
          alignItems: "center", justifyContent: "center", gap: 8,
          textDecoration: "none",
        }}
      >
        <Icon.WhatsApp /> Lieber per WhatsApp anfragen
      </a>

      <div className="booking-form-foot">
        <button className="btn btn-ghost btn-lg" onClick={onBack}>Zurück</button>
        <button
          className="btn btn-accent btn-lg"
          disabled={!can}
          onClick={() => onConfirm({ ...data, total: summary.total })}
          style={{ opacity: can ? 1 : 0.5, cursor: can ? "pointer" : "not-allowed" }}
        >
          {summary.isInquiry
            ? <>Anfrage senden <Icon.ArrowRight /></>
            : <>Unverbindlich anfragen · CHF {chf(summary.total)}</>
          }
        </button>
      </div>
    </div>
  );
}

function Summary({ summary, addons, selectedAddons, pickupLoc, pickupAt, returnAt }) {
  const v = summary.vehicle;
  return (
    <div className="summary">
      <div className="eyebrow" style={{ marginBottom: 12 }}>Ihre Reservierung</div>
      <div style={{
        aspectRatio: "16/10",
        backgroundImage: `url(${v.image})`,
        backgroundSize: "cover",
        backgroundPosition: "center",
        borderRadius: "var(--r-md)",
        marginBottom: 14,
      }} />
      <div style={{ fontSize: 12, color: "var(--ink-3)", textTransform: "uppercase", letterSpacing: ".06em" }}>{v.brand}</div>
      <div className="h-3" style={{ margin: "2px 0 14px" }}>{v.model}</div>

      <div style={{ display: "flex", flexDirection: "column", gap: 8, fontSize: 13, color: "var(--ink-2)", borderTop: "1px solid var(--line)", paddingTop: 14 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}><Icon.Map /> {pickupLoc}</div>
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}><Icon.Cal /> {fmtDate(pickupAt)} → {fmtDate(returnAt)}</div>
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          · {summary.hours} Std. ({summary.days} Tag{summary.days !== 1 ? "e" : ""})
        </div>
      </div>

      <div style={{ borderTop: "1px solid var(--line)", marginTop: 18, paddingTop: 14 }}>
        {/* v2.2.6 — Inquiry-Mode: kein Preis sondern "Auf Anfrage" */}
        {summary.isInquiry ? (
          <div className="summary-inquiry">
            <div className="summary-inquiry-eyebrow">Auf Anfrage</div>
            <div className="summary-inquiry-title">Persönliches Angebot</div>
            <div className="summary-inquiry-sub">
              Bei Mietdauern über {summary.inquiryThresholdH} Std. erstellen wir Ihnen ein
              individuelles Angebot. Senden Sie das Formular ab — wir melden uns innerhalb
              von 2 Stunden mit der Offerte.
            </div>
          </div>
        ) : (
          <>
        {summary.priceMode === "weekend"
          ? <Row
              l={
                <span>
                  <span style={{ color: "var(--accent)", fontWeight: 600 }}>Weekend-Pauschale</span>
                  {summary.weekendLabel ? <span style={{ color: "var(--ink-3)", marginLeft: 6, fontSize: 12 }}>· {summary.weekendLabel}</span> : null}
                </span>
              }
              r={`CHF ${chf(summary.baseTotal)}`}
            />
          : (summary.priceMode && summary.priceMode.indexOf("tier_") === 0
              ? (() => {
                  // v2.2.44 — „Pauschale" statt „Tier-Pauschale" + Streichpreis bei Aktion
                  const tierKey = summary.priceMode === "tier_3h" ? "3"
                                : summary.priceMode === "tier_6h" ? "6"
                                : summary.priceMode === "tier_24h" ? "24"
                                : summary.priceMode === "tier_48h" ? "48"
                                : "168";
                  const tierLbl = summary.priceMode === "tier_3h" ? "3 Std"
                                : summary.priceMode === "tier_6h" ? "6 Std"
                                : summary.priceMode === "tier_24h" ? "1 Tag"
                                : summary.priceMode === "tier_48h" ? "2 Tage"
                                : "1 Woche";
                  const top = (summary.vehicle && summary.vehicle.tierOldPrices) || {};
                  const struck = parseInt(top[tierKey], 10);
                  const dealActive = struck > 0 && struck > summary.baseTotal;
                  return (
                    <Row
                      l={
                        <span>
                          <span style={{ color: "var(--accent)", fontWeight: 600 }}>Pauschale</span>
                          <span style={{ color: "var(--ink-3)", marginLeft: 6, fontSize: 12 }}>· {tierLbl}</span>
                        </span>
                      }
                      r={
                        dealActive ? (
                          <span>
                            <span style={{ color: "var(--ink-3)", textDecoration: "line-through", marginRight: 8, fontWeight: 400 }}>
                              CHF {chf(struck)}
                            </span>
                            <span style={{ color: "var(--accent)", fontWeight: 700 }}>
                              CHF {chf(summary.baseTotal)}
                            </span>
                          </span>
                        ) : `CHF ${chf(summary.baseTotal)}`
                      }
                    />
                  );
                })()
              : (summary.priceMode === "hour" && summary.pricePerHour > 0
                  ? <Row l={`Fahrzeug (${summary.hours} Std. × ${chf(summary.pricePerHour)})`} r={`CHF ${chf(summary.baseTotal)}`} />
                  : <Row l={`Fahrzeug (${summary.days} × ${chf(v.pricePerDay)})`} r={`CHF ${chf(summary.baseTotal)}`} />
                )
            )
        }
        {selectedAddons.map(id => {
          const a = addons.find(x => x.id === id);
          if (!a || a.price === 0) return null;
          const cost = a.per === "Tag" ? a.price * summary.days : a.price;
          return <Row key={id} l={a.label} r={`CHF ${chf(cost)}`} small />;
        })}
        {summary.kmIncluded > 0 && (
          <Row l={`Inkl. ${summary.kmIncluded} km`} r="—" small />
        )}
        {summary.extraKm > 0 && (
          <Row
            l={`Extra-km (${summary.extraKm} × CHF ${(summary.extraKmPrice || 0).toFixed(2).replace('.', ',')})`}
            r={`CHF ${chf(summary.extraKmCost || 0)}`}
            small
          />
        )}
        {summary.discountAmount > 0 && (
          <Row
            l={<span style={{ color: "var(--accent)" }}>Smart-Rabatt (−{summary.discountPct}%)</span>}
            r={<span style={{ color: "var(--accent)" }}>− CHF {chf(summary.discountAmount)}</span>}
            small
          />
        )}
        {summary.weekendBonusUsed && summary.weekendBonusSurcharge > 0 && (
          <Row
            l={<span style={{ color: "var(--accent)" }}>Bonus-Tag (Aktion verlängert)</span>}
            r={<span style={{ color: "var(--accent)" }}>+ CHF {chf(summary.weekendBonusSurcharge)}</span>}
            small
          />
        )}
        {(summary.afterHoursReasons || []).map((reason, i) => (
          <Row
            key={"ah-"+i}
            l={
              <span style={{ color: "#FF8A4C" }}>
                {reason.label}
                <span style={{ color: "var(--ink-3)", marginLeft: 6, fontSize: 11 }}>(After-Hours)</span>
              </span>
            }
            r={<span style={{ color: "#FF8A4C" }}>+ CHF {chf(reason.fee)}</span>}
            small
          />
        ))}
        <Row l={`davon MwSt ${(summary.vatRate * 100).toFixed(1).replace(/\.0$/, "")}%`} r={`CHF ${chf(summary.vat)}`} small />
        <div style={{ borderTop: "1px solid var(--line)", margin: "12px 0", paddingTop: 12, display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
          <span style={{ fontSize: 14, fontWeight: 500 }}>Gesamt <span style={{ fontSize: 11, color: "var(--ink-3)", fontWeight: 400 }}>(inkl. MwSt)</span></span>
          <span style={{ fontFamily: "var(--font-display)", fontSize: 28, fontWeight: 600, letterSpacing: "-0.02em" }}>
            CHF {chf(summary.total)}
            {summary.quoting && <span style={{ fontSize: 12, marginLeft: 6, color: "var(--ink-3)", fontWeight: 400 }}>…</span>}
          </span>
        </div>
          </>
        )}
      </div>
    </div>
  );
}
function Row({ l, r, small }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", padding: "6px 0", fontSize: small ? 13 : 14, color: small ? "var(--ink-3)" : "var(--ink-2)" }}>
      <span>{l}</span><span className="mono">{r}</span>
    </div>
  );
}
function fmtDate(s) {
  const d = new Date(s);
  return d.toLocaleString("de-CH", { day: "2-digit", month: "short", hour: "2-digit", minute: "2-digit" });
}

// Wiederverwendbare KM-Komponente — wird auch im Inline-Calc / Calc-Page genutzt
function KmBlock({ kmIncluded, extraKm, extraKmPrice, extraKmCost, onChange, compact }) {
  const km = parseInt(extraKm || 0, 10);
  const price = parseFloat(extraKmPrice || 1.5);
  const cost = parseInt(extraKmCost || Math.round(km * price), 10);
  const dec = () => onChange && onChange(Math.max(0, km - 50));
  const inc = () => onChange && onChange(km + 50);
  return (
    <div className={"km-row" + (compact ? " km-row-compact" : "")}>
      <div className="km-row-head">
        <div style={{ display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap" }}>
          <span style={{ fontWeight: 600, fontSize: 14 }}>Inklusive Kilometer</span>
          {kmIncluded > 0
            ? <span className="km-included-pill">{kmIncluded} km enthalten</span>
            : <span className="km-extra-info">— für gewählte Dauer keine km-Pauschale</span>
          }
        </div>
        <span className="km-extra-info">
          Extra-km: <strong style={{ color: "var(--ink)" }}>CHF {price.toFixed(2).replace('.', ',')}</strong>/km
        </span>
      </div>
      <div className="km-extra-row">
        <span style={{ fontSize: 13, color: "var(--ink-2)" }}>Zusätzliche km kaufen:</span>
        <div className="km-stepper" role="group" aria-label="Extra-Kilometer wählen">
          <button type="button" onClick={dec} aria-label="50 km weniger">−</button>
          <input
            type="number"
            min="0"
            step="50"
            value={km}
            onChange={(e) => onChange && onChange(Math.max(0, parseInt(e.target.value || 0, 10)))}
            aria-label="Extra-Kilometer"
          />
          <button type="button" onClick={inc} aria-label="50 km mehr">+</button>
        </div>
        <span style={{ fontSize: 13, color: "var(--ink-2)" }}>km</span>
        {km > 0 && (
          <span className="km-extra-info">
            = <strong style={{ color: "var(--ink)" }}>CHF {cost}</strong>
          </span>
        )}
      </div>
    </div>
  );
}

window.KmBlock = KmBlock;
window.BookingPage = BookingPage;
