/* global React, Icon, chf */
// ACN-Cars · Pages: Deals, Calculator, Admin
// v2.2.14 — DealsPage Premium-Magazin-Layout: Back-Bar, hellerer Hero (Cream
//           + Gold), breite Aktion-Karten (Bild links, Story rechts), klare
//           Typo, sichtbarer Countdown, prominenter „Jetzt sichern"-CTA.
// v2.2.15 — Fahrzeug-Reihen in den Magazin-Karten klickbar (öffnen Detailseite).
// v2.2.16 — Klick auf Fahrzeug-Reihe übergibt jetzt zusätzlich die Aktion an
//           onOpen(v, deal), damit die Detailseite den Aktion-Banner und
//           Aktion-Preise anzeigen kann. Weekend-Deals zeigen jetzt korrekt
//           die Wochenend-Pauschale (statt eines −%-Rabatts auf den Tagespreis).

function DealsPage({ deals, vehicles, onBook, onOpen, onHome, onFleet }) {
  const totalDeals = deals.length;
  const maxPct = deals.reduce((m, d) => Math.max(m, Number(d.discount) || 0), 0);
  return (
    <main className="deals-page">
      {/* Premium Back-Bar */}
      <div className="deals-page-backbar">
        <div className="container deals-page-backbar-inner">
          <button
            type="button"
            className="btn btn-ghost btn-sm deals-page-back-btn"
            onClick={() => (onHome ? onHome() : window.history.back())}
          >
            ← Zurück zur Startseite
          </button>
          {onFleet && (
            <button
              type="button"
              className="btn btn-ghost btn-sm"
              onClick={onFleet}
            >
              Zur Flotte <Icon.ArrowRight />
            </button>
          )}
        </div>
      </div>

      {/* Magazin-Hero — Cream + Gold, kompakt, lesbar */}
      <section className="deals-page-hero">
        <div className="deals-page-hero-bg" aria-hidden />
        <div className="container deals-page-hero-inner">
          <div className="deals-page-hero-eyebrow">
            <span className="deals-page-hero-eyebrow-dot" aria-hidden />
            <Icon.Sparkle />
            <span>Aktionen &amp; Deals</span>
          </div>
          <h1 className="deals-page-hero-title">
            Kurz <span className="deals-page-hero-title-accent">&amp; exklusiv</span>.<br />
            Solange verfügbar.
          </h1>
          <p className="deals-page-hero-lead">
            Handverlesene Aktionen auf unsere Premium-Flotte. Jede Aktion ist zeitlich
            begrenzt — sichern Sie sich Ihren Wagen, bevor der Countdown abläuft.
          </p>
          <div className="deals-page-hero-meta">
            <div className="deals-page-hero-meta-item">
              <span className="deals-page-hero-meta-num">{totalDeals}</span>
              <span className="deals-page-hero-meta-label">aktive Aktion{totalDeals === 1 ? "" : "en"}</span>
            </div>
            {maxPct > 0 && (
              <div className="deals-page-hero-meta-item">
                <span className="deals-page-hero-meta-num">−{maxPct}%</span>
                <span className="deals-page-hero-meta-label">Top-Rabatt</span>
              </div>
            )}
            <div className="deals-page-hero-meta-item">
              <span className="deals-page-hero-meta-num"><Icon.Sparkle /></span>
              <span className="deals-page-hero-meta-label">Limitiert</span>
            </div>
          </div>
        </div>
      </section>

      {/* Aktion-Karten — Bild links, Story rechts (Magazin-Stil) */}
      <section className="deals-page-list">
        <div className="container">
          {deals.length === 0 && (
            <div className="deals-page-empty">
              <div className="muted">Aktuell keine aktiven Aktionen — schauen Sie bald wieder vorbei.</div>
            </div>
          )}
          {deals.map((deal, idx) => {
            const dealVehicles = vehicles.filter(v => deal.vehicles.includes(v.id));
            const heroVeh = dealVehicles[0];
            return (
              <article key={deal.id} className="deal-mag-card" data-flip={idx % 2 === 1 ? "1" : ""}>
                <div
                  className="deal-mag-card-img"
                  style={heroVeh ? { backgroundImage: `url(${heroVeh.image})` } : {}}
                >
                  <div className="deal-mag-card-pills">
                    <span className="pill pill-deal deal-mag-card-pct">−{deal.discount}%</span>
                    {deal.accent && <span className="pill pill-accent">Limited</span>}
                  </div>
                </div>
                <div className="deal-mag-card-body">
                  <div className="deal-mag-card-eyebrow">Aktion {String(idx + 1).padStart(2, "0")}</div>
                  <h2 className="deal-mag-card-title">{deal.title}</h2>
                  <p className="deal-mag-card-sub">{deal.subtitle}</p>

                  <div className="deal-mag-card-countdown">
                    <div className="deal-mag-card-countdown-label">Endet in</div>
                    <Countdown to={deal.endsAt} />
                  </div>

                  {dealVehicles.length > 0 && (
                    <div className="deal-mag-card-vehicles">
                      <div className="deal-mag-card-vehicles-label">Verfügbare Fahrzeuge</div>
                      <div className="deal-mag-card-vehicles-list">
                        {dealVehicles.map(v => {
                          // v2.2.16 — Weekend-Deals: per-Vehicle-Pauschale, sonst Prozent-Rabatt.
                          // v2.2.32 — Strikethrough vergleicht Pauschal mit (Tagespreis × Wochenend-Tage),
                          // nicht mit dem Tagespreis allein (sonst sieht es so aus als wäre die
                          // Pauschal teurer als der Tagespreis).
                          const isWeekendDeal = !!(deal.isWeekend && deal.weekend);
                          const oldP = v.pricePerDay;
                          let newP, perLabel, oldDisplay;
                          if (isWeekendDeal) {
                            const vp = (deal.weekend.vehiclePrices && typeof deal.weekend.vehiclePrices === "object")
                              ? deal.weekend.vehiclePrices : {};
                            const wPrice = vp[v.id] && Number(vp[v.id]) > 0
                              ? Number(vp[v.id])
                              : (deal.weekend.price > 0 ? Number(deal.weekend.price) : 0);
                            newP = wPrice > 0 ? wPrice : Math.round(oldP * (1 - (Number(deal.discount) || 0) / 100));
                            perLabel = "Pauschale";
                            // Anzahl Wochenend-Tage aus Pickup/Return-Day berechnen
                            const pd = Number(deal.weekend.pickupDay);
                            const rd = Number(deal.weekend.returnDay);
                            const wDays = (Number.isFinite(pd) && Number.isFinite(rd))
                              ? ((rd - pd + 7) % 7) + 1
                              : 0;
                            oldDisplay = wDays > 0 ? oldP * wDays : 0;
                          } else {
                            newP = Math.round(oldP * (1 - (Number(deal.discount) || 0) / 100));
                            perLabel = "/Tag";
                            oldDisplay = oldP;
                          }
                          // Strikethrough nur zeigen wenn echte Ersparnis vorhanden
                          const showOldPrice = oldDisplay > newP;
                          const clickable = typeof onOpen === "function";
                          // v2.2.16 — Aktion mitgeben, damit DetailPage den Aktions-Banner zeigt.
                          const handleOpen = () => clickable && onOpen(v, deal);
                          return (
                            <div
                              key={v.id}
                              className="deal-mag-vehicle"
                              data-clickable={clickable ? "1" : ""}
                              role={clickable ? "button" : undefined}
                              tabIndex={clickable ? 0 : undefined}
                              onClick={handleOpen}
                              onKeyDown={(e) => {
                                if (clickable && (e.key === "Enter" || e.key === " ")) {
                                  e.preventDefault();
                                  handleOpen();
                                }
                              }}
                              title={clickable ? `${v.brand} ${v.model} ansehen` : undefined}
                            >
                              <div
                                className="deal-mag-vehicle-thumb"
                                style={{ backgroundImage: `url(${v.image})` }}
                              />
                              <div className="deal-mag-vehicle-meta">
                                <div className="deal-mag-vehicle-brand">{v.brand}</div>
                                <div className="deal-mag-vehicle-model">{v.model}</div>
                              </div>
                              <div className="deal-mag-vehicle-price">
                                {showOldPrice && (
                                  <span className="price-old">
                                    <span className="price-old-amount">CHF {chf(oldDisplay)}</span>
                                  </span>
                                )}
                                <span className="deal-mag-vehicle-new">CHF {chf(newP)}</span>
                                <span className="deal-mag-vehicle-per">{perLabel}</span>
                              </div>
                              {clickable && (
                                <span className="deal-mag-vehicle-arrow" aria-hidden>
                                  <Icon.ArrowRight />
                                </span>
                              )}
                            </div>
                          );
                        })}
                      </div>
                    </div>
                  )}

                  <button
                    className="btn btn-primary btn-lg deal-mag-card-cta"
                    onClick={() => onBook && onBook(deal)}
                  >
                    Jetzt sichern <Icon.ArrowRight />
                  </button>
                </div>
              </article>
            );
          })}
        </div>
      </section>
    </main>
  );
}

// ---- Standalone Calculator (mit Stunden-Buckets, inkl. MwSt) ----
function CalcPage({ vehicles, addons, boot, onHome, onFleet }) {
  const buckets = [
    { hours: 1,   label: "1 Std" },
    { hours: 3,   label: "3 Std" },
    { hours: 6,   label: "6 Std" },
    { hours: 24,  label: "1 Tag" },
    { hours: 48,  label: "2 Tage" },
    { hours: 72,  label: "3 Tage" },
    { hours: 168, label: "1 Woche" },
  ];
  const vatRate = (boot && typeof boot.vatRate === "number" ? boot.vatRate : 8.1) / 100;

  const [hours, setHours] = React.useState(24);
  const [vehicleId, setVehicleId] = React.useState(vehicles[0].id);
  const [picks, setPicks] = React.useState(addons.filter(a => a.default).map(a => a.id));
  const [extraKm, setExtraKm] = React.useState(0);
  const v = vehicles.find(x => x.id === vehicleId) || vehicles[0];
  const togg = id => setPicks(p => p.includes(id) ? p.filter(x => x !== id) : [...p, id]);

  const days = Math.max(1, Math.ceil(hours / 24));
  const pricePerHour = +v.pricePerHour || 0;
  const baseDay  = v.pricePerDay * days;
  const baseHour = pricePerHour > 0 ? pricePerHour * hours : 0;
  let priceMode = "day";
  let base = baseDay;
  if (pricePerHour > 0 && baseHour > 0 && baseHour < baseDay) {
    priceMode = "hour";
    base = baseHour;
  }

  const ad = picks.reduce((s, id) => {
    const a = addons.find(x => x.id === id); if (!a) return s;
    return s + (a.per === "Tag" ? a.price * days : a.price);
  }, 0);

  // Inkl.-km für gewählte Dauer + Extra-km
  const kmIncluded = window.ACN_kmIncludedFor ? window.ACN_kmIncludedFor(v, hours) : 0;
  const kmExtraPrice = parseFloat(v.kmExtraPrice || 1.5);
  const extraKmCost = Math.round(parseInt(extraKm || 0, 10) * kmExtraPrice);

  // Inkl. MwSt: total = brutto, MwSt herausrechnen.
  const total = base + ad + extraKmCost;
  const net   = Math.round(total / (1 + vatRate));
  const vat   = total - net;

  const hasDeal = (typeof v.dealPct === "number" && v.dealPct > 0) || (v.oldPrice && v.oldPrice > v.pricePerDay);
  const dealPct = hasDeal
    ? (typeof v.dealPct === "number" && v.dealPct > 0
        ? v.dealPct
        : Math.round((1 - v.pricePerDay / v.oldPrice) * 100))
    : 0;

  return (
    <main className="section">
      <div className="container">
        <div className="booking-back-bar">
          <button type="button" className="back-link" onClick={() => onHome && onHome()}>
            <Icon.ArrowLeft /> Zurück zur Startseite
          </button>
          <button type="button" className="back-link back-link-secondary" onClick={() => onFleet && onFleet()}>
            Andere Fahrzeuge ansehen <Icon.ArrowRight />
          </button>
        </div>
        <div className="eyebrow" style={{ marginBottom: 12 }}>Preis-Kalkulator</div>
        <h1 className="h-1" style={{ margin: 0, marginBottom: 32, maxWidth: "16ch" }}>Sehen Sie den Preis sofort.</h1>

        <div style={{ display: "grid", gridTemplateColumns: "1fr 380px", gap: 48, alignItems: "start" }}>
          <div className="card" style={{ padding: 32 }}>
            <div className="field" style={{ marginBottom: 24 }}>
              <label>Fahrzeug</label>
              <select className="select" value={vehicleId} onChange={e => setVehicleId(e.target.value)}>
                {vehicles.map(x => (
                  <option key={x.id} value={x.id}>
                    {x.brand} {x.model} — CHF {chf(x.pricePerDay)}/Tag{x.pricePerHour ? ` (CHF ${chf(x.pricePerHour)}/h)` : ""}
                  </option>
                ))}
              </select>
            </div>

            <div style={{ marginBottom: 28 }}>
              {window.DurationSlider
                ? <window.DurationSlider hours={hours} onChangeHours={setHours} maxDays={30} />
                : <label style={{ fontSize: 12, textTransform: "uppercase", letterSpacing: ".04em", color: "var(--ink-3)", display: "block", marginBottom: 10 }}>Mietdauer</label>}
              <div className="duration-quick">
                <span className="duration-quick-label">Schnellauswahl:</span>
                {buckets.map(b => (
                  <button
                    key={b.hours}
                    type="button"
                    className="duration-quick-pill"
                    data-active={hours === b.hours ? "1" : ""}
                    onClick={() => setHours(b.hours)}
                  >
                    {b.label}
                  </button>
                ))}
              </div>
            </div>

            {/* Inkl. km + Extra-km */}
            {window.KmBlock && (
              <div style={{ marginBottom: 24 }}>
                <window.KmBlock
                  kmIncluded={kmIncluded}
                  extraKm={extraKm}
                  extraKmPrice={kmExtraPrice}
                  extraKmCost={extraKmCost}
                  onChange={(n) => setExtraKm(Math.max(0, parseInt(n || 0, 10)))}
                />
              </div>
            )}

            <div className="eyebrow" style={{ marginBottom: 12 }}>Zusatzleistungen</div>
            <div style={{ display: "grid", gap: 8 }}>
              {addons.filter(a => !a.locked).map(a => {
                const active = picks.includes(a.id);
                return (
                  <div key={a.id} onClick={() => togg(a.id)} style={{
                    display: "flex", alignItems: "center", gap: 12, cursor: "pointer",
                    padding: "10px 14px", borderRadius: "var(--r-md)",
                    border: "1px solid " + (active ? "var(--ink)" : "var(--line)"),
                    background: active ? "var(--bg-sunken)" : "transparent",
                  }}>
                    <div style={{
                      width: 18, height: 18, borderRadius: 4,
                      border: "1.5px solid " + (active ? "var(--ink)" : "var(--line-strong)"),
                      background: active ? "var(--ink)" : "transparent",
                      color: "var(--bg)", display: "grid", placeItems: "center",
                    }}>{active && <Icon.Check />}</div>
                    <span style={{ flex: 1, fontSize: 14 }}>{a.label}</span>
                    <span className="mono" style={{ fontSize: 13, fontWeight: 600 }}>
                      {a.price === 0 ? "Inkl." : `CHF ${chf(a.price)}/${a.per}`}
                    </span>
                  </div>
                );
              })}
            </div>
          </div>

          <div className="summary">
            <div className="eyebrow" style={{ marginBottom: 18 }}>Live-Berechnung</div>
            <div style={{ display: "flex", justifyContent: "space-between", padding: "8px 0", fontSize: 14 }}>
              <span>
                {priceMode === "hour"
                  ? `${hours} Std × CHF ${chf(pricePerHour)}`
                  : `${days} × CHF ${chf(v.pricePerDay)}`}
              </span>
              <span className="mono">CHF {chf(base)}</span>
            </div>
            {hasDeal && priceMode === "day" && v.oldPrice && (
              <div style={{ display: "flex", justifyContent: "space-between", padding: "4px 0", fontSize: 12, color: "var(--accent)" }}>
                <span>Aktion −{dealPct}%</span>
                <span className="mono" style={{ textDecoration: "line-through", opacity: 0.7 }}>CHF {chf(v.oldPrice * days)}</span>
              </div>
            )}
            <div style={{ display: "flex", justifyContent: "space-between", padding: "8px 0", fontSize: 14 }}>
              <span>Zusatzleistungen</span><span className="mono">CHF {chf(ad)}</span>
            </div>
            {kmIncluded > 0 && (
              <div style={{ display: "flex", justifyContent: "space-between", padding: "4px 0", fontSize: 13, color: "var(--ink-3)" }}>
                <span>Inkl. {kmIncluded} km</span><span className="mono">—</span>
              </div>
            )}
            {extraKm > 0 && (
              <div style={{ display: "flex", justifyContent: "space-between", padding: "8px 0", fontSize: 14 }}>
                <span>Extra-km ({extraKm} × CHF {kmExtraPrice.toFixed(2).replace('.', ',')})</span>
                <span className="mono">CHF {chf(extraKmCost)}</span>
              </div>
            )}
            <div style={{ display: "flex", justifyContent: "space-between", padding: "8px 0", fontSize: 13, color: "var(--ink-3)" }}>
              <span>davon MwSt {(vatRate * 100).toFixed(1).replace(/\.0$/, "")}%</span>
              <span className="mono">CHF {chf(vat)}</span>
            </div>
            <div style={{ borderTop: "1px solid var(--line)", marginTop: 12, paddingTop: 14, display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
              <span style={{ fontWeight: 500 }}>Gesamt <span style={{ fontSize: 11, color: "var(--ink-3)", fontWeight: 400 }}>(inkl. MwSt)</span></span>
              <span style={{ fontFamily: "var(--font-display)", fontSize: 32, fontWeight: 600, letterSpacing: "-0.02em" }}>
                CHF {chf(total)}
              </span>
            </div>
            <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 6, textAlign: "right" }}>
              {priceMode === "hour"
                ? `CHF ${chf(Math.round(total / hours))} pro Stunde (effektiv)`
                : `CHF ${chf(Math.round(total / days))} pro Tag (effektiv)`}
            </div>
            {priceMode === "hour" && (
              <div className="muted" style={{ fontSize: 11, marginTop: 6 }}>
                Stundentarif aktiv (günstiger als Tagespauschale).
              </div>
            )}
          </div>
        </div>
      </div>
    </main>
  );
}

// ---- Admin Concept ----
function AdminPage({ vehicles, deals, addons }) {
  const [tab, setTab] = React.useState("vehicles");
  return (
    <main className="section">
      <div className="container">
        <div className="eyebrow" style={{ marginBottom: 12 }}>Admin · Konzept</div>
        <h1 className="h-1" style={{ margin: 0, marginBottom: 24, maxWidth: "20ch" }}>Backend für Vermieter.</h1>
        <p className="lead" style={{ maxWidth: "60ch", marginBottom: 32 }}>
          Mockup des WordPress-Plugin-Backends. Im fertigen Plugin liegt diese Oberfläche unter <span className="mono" style={{ background: "var(--bg-sunken)", padding: "2px 6px", borderRadius: 4 }}>WP-Admin → ACN-Cars</span>.
        </p>

        <div className="admin-shell">
          <aside className="admin-side">
            <div style={{ padding: "0 8px 16px", borderBottom: "1px solid var(--line)", marginBottom: 8 }}>
              <div className="brand" style={{ fontSize: 14 }}>
                <div className="brand-mark">A</div>
                ACN-Cars
              </div>
            </div>
            <h5>Verwaltung</h5>
            <a data-active={tab === "vehicles"} onClick={() => setTab("vehicles")}>🚗 Fahrzeuge</a>
            <a data-active={tab === "bookings"} onClick={() => setTab("bookings")}>📋 Buchungen</a>
            <a data-active={tab === "deals"} onClick={() => setTab("deals")}>🏷 Aktionen</a>
            <a data-active={tab === "addons"} onClick={() => setTab("addons")}>➕ Zusatzleistungen</a>
            <a data-active={tab === "availability"} onClick={() => setTab("availability")}>📅 Verfügbarkeit</a>
            <h5>Einstellungen</h5>
            <a data-active={tab === "appearance"} onClick={() => setTab("appearance")}>🎨 Erscheinungsbild</a>
            <a data-active={tab === "shortcode"} onClick={() => setTab("shortcode")}>🔌 Shortcode</a>
          </aside>

          <div className="admin-main">
            {tab === "vehicles" && <AdminVehicles vehicles={vehicles} />}
            {tab === "bookings" && <AdminBookings />}
            {tab === "deals" && <AdminDeals deals={deals} vehicles={vehicles} />}
            {tab === "addons" && <AdminAddons addons={addons} />}
            {tab === "availability" && <AdminAvailability vehicles={vehicles} />}
            {tab === "appearance" && <AdminAppearance />}
            {tab === "shortcode" && <AdminShortcode />}
          </div>
        </div>
      </div>
    </main>
  );
}

function AdminHeader({ title, action }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 24 }}>
      <h2 className="h-2" style={{ margin: 0 }}>{title}</h2>
      {action}
    </div>
  );
}

function AdminVehicles({ vehicles }) {
  return (
    <div>
      <AdminHeader title="Fahrzeuge" action={<button className="btn btn-primary btn-sm"><Icon.Plus /> Neues Fahrzeug</button>} />
      <table className="admin-table">
        <thead><tr><th></th><th>Modell</th><th>Kategorie</th><th>Preis/Tag</th><th>Status</th><th></th></tr></thead>
        <tbody>
          {vehicles.map(v => (
            <tr key={v.id}>
              <td style={{ width: 64 }}>
                <div style={{ width: 56, height: 36, borderRadius: 4, backgroundImage: `url(${v.image})`, backgroundSize: "cover", backgroundPosition: "center" }} />
              </td>
              <td>
                <div style={{ fontWeight: 500 }}>{v.brand} {v.model}</div>
                <div style={{ fontSize: 12, color: "var(--ink-3)" }}>{v.year} · ID {v.id}</div>
              </td>
              <td>{v.category}</td>
              <td className="mono">CHF {chf(v.pricePerDay)}{v.oldPrice && <span style={{ fontSize: 11, color: "var(--accent)", marginLeft: 8 }}>Aktion</span>}</td>
              <td>
                <span className={`status-dot ${v.deal ? "status-deal" : "status-active"}`} />
                {v.deal ? "Im Deal" : "Aktiv"}
              </td>
              <td style={{ textAlign: "right" }}>
                <button className="btn btn-ghost btn-sm">Bearbeiten</button>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

function AdminBookings() {
  const rows = [
    { id: "B-2401", name: "Sandra Keller", car: "Porsche 911 GT3", from: "02. Mai", to: "05. Mai", total: 3870, status: "Bestätigt" },
    { id: "B-2402", name: "Marco Bianchi", car: "Mercedes S 580", from: "03. Mai", to: "10. Mai", total: 4830, status: "Anzahlung offen" },
    { id: "B-2403", name: "Luca Hofer", car: "Audi RS6 Avant", from: "04. Mai", to: "06. Mai", total: 1440, status: "Bestätigt" },
    { id: "B-2404", name: "Nina Roth", car: "BMW i7", from: "10. Mai", to: "14. Mai", total: 2600, status: "Anfrage" },
  ];
  return (
    <div>
      <AdminHeader title="Buchungen" action={<button className="btn btn-ghost btn-sm">Export CSV</button>} />
      <table className="admin-table">
        <thead><tr><th>Nr</th><th>Kunde</th><th>Fahrzeug</th><th>Zeitraum</th><th>Total</th><th>Status</th></tr></thead>
        <tbody>
          {rows.map(r => (
            <tr key={r.id}>
              <td className="mono">{r.id}</td>
              <td style={{ fontWeight: 500 }}>{r.name}</td>
              <td>{r.car}</td>
              <td>{r.from} – {r.to}</td>
              <td className="mono">CHF {chf(r.total)}</td>
              <td>
                <span className={"status-dot " + (r.status === "Bestätigt" ? "status-active" : "status-paused")} />
                {r.status}
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

function AdminDeals({ deals, vehicles }) {
  return (
    <div>
      <AdminHeader title="Aktionen" action={<button className="btn btn-primary btn-sm"><Icon.Plus /> Neue Aktion</button>} />
      <div style={{ display: "grid", gap: 12 }}>
        {deals.map(d => (
          <div key={d.id} className="card" style={{ padding: 20, display: "flex", alignItems: "center", gap: 20 }}>
            <span className="pill pill-deal">−{d.discount}%</span>
            <div style={{ flex: 1 }}>
              <div style={{ fontWeight: 500 }}>{d.title}</div>
              <div style={{ fontSize: 13, color: "var(--ink-3)" }}>{d.subtitle} · {d.vehicles.length} Fahrzeuge</div>
            </div>
            <Countdown to={d.endsAt} />
            <button className="btn btn-ghost btn-sm">Bearbeiten</button>
          </div>
        ))}
      </div>
    </div>
  );
}

function AdminAddons({ addons }) {
  return (
    <div>
      <AdminHeader title="Zusatzleistungen" action={<button className="btn btn-primary btn-sm"><Icon.Plus /> Neue Leistung</button>} />
      <table className="admin-table">
        <thead><tr><th>Bezeichnung</th><th>Preis</th><th>Abrechnung</th><th>Standard</th></tr></thead>
        <tbody>
          {addons.map(a => (
            <tr key={a.id}>
              <td style={{ fontWeight: 500 }}>{a.label}</td>
              <td className="mono">{a.price === 0 ? "Inkl." : `CHF ${chf(a.price)}`}</td>
              <td>{a.per}</td>
              <td><span className="toggle" data-on={!!a.default} /></td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

function AdminAvailability({ vehicles }) {
  const days = Array.from({ length: 14 }, (_, i) => i);
  return (
    <div>
      <AdminHeader title="Verfügbarkeit (14 Tage)" />
      <div style={{ overflowX: "auto" }}>
        <table className="admin-table" style={{ minWidth: 800 }}>
          <thead>
            <tr>
              <th>Fahrzeug</th>
              {days.map(d => <th key={d} style={{ textAlign: "center", fontSize: 11 }}>{d + 1}</th>)}
            </tr>
          </thead>
          <tbody>
            {vehicles.slice(0, 6).map((v, i) => (
              <tr key={v.id}>
                <td style={{ fontSize: 13 }}>{v.brand} {v.model}</td>
                {days.map(d => {
                  const booked = (i + d) % 5 === 0 || (i + d) % 7 === 0;
                  return <td key={d} style={{ textAlign: "center" }}>
                    <div style={{
                      width: 20, height: 20, borderRadius: 4, margin: "0 auto",
                      background: booked ? "var(--ink)" : "color-mix(in oklab, var(--success) 30%, transparent)",
                    }} />
                  </td>;
                })}
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      <div style={{ display: "flex", gap: 16, marginTop: 16, fontSize: 12, color: "var(--ink-3)" }}>
        <span><span style={{ display: "inline-block", width: 12, height: 12, borderRadius: 2, background: "color-mix(in oklab, var(--success) 30%, transparent)", verticalAlign: "middle", marginRight: 6 }} />Verfügbar</span>
        <span><span style={{ display: "inline-block", width: 12, height: 12, borderRadius: 2, background: "var(--ink)", verticalAlign: "middle", marginRight: 6 }} />Gebucht</span>
      </div>
    </div>
  );
}

function AdminAppearance() {
  return (
    <div>
      <AdminHeader title="Erscheinungsbild" />
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 24 }}>
        <div className="card" style={{ padding: 24 }}>
          <div className="eyebrow" style={{ marginBottom: 12 }}>Akzentfarbe</div>
          <div style={{ display: "flex", gap: 8 }}>
            {["#A8916F", "#0066CC", "#1F8A4C", "#B23838", "#8C1D40"].map(c => (
              <div key={c} style={{ width: 36, height: 36, borderRadius: 8, background: c, border: c === "#A8916F" ? "2px solid var(--ink)" : "1px solid var(--line)", cursor: "pointer" }} />
            ))}
          </div>
        </div>
        <div className="card" style={{ padding: 24 }}>
          <div className="eyebrow" style={{ marginBottom: 12 }}>Modus</div>
          <div style={{ display: "flex", gap: 8 }}>
            <button className="chip" data-active="true">Auto</button>
            <button className="chip">Light</button>
            <button className="chip">Dark</button>
          </div>
        </div>
        <div className="card" style={{ padding: 24, gridColumn: "1/-1" }}>
          <div className="eyebrow" style={{ marginBottom: 12 }}>Logo</div>
          <div style={{ display: "flex", alignItems: "center", gap: 16 }}>
            <div style={{ width: 200, height: 60, background: "var(--bg-sunken)", borderRadius: 8, display: "grid", placeItems: "center", fontFamily: "var(--font-display)", fontWeight: 700, letterSpacing: "-0.02em" }}>
              ACN-CARS
            </div>
            <button className="btn btn-ghost btn-sm">Logo ersetzen</button>
          </div>
        </div>
      </div>
    </div>
  );
}

function AdminShortcode() {
  return (
    <div>
      <AdminHeader title="Shortcode" />
      <p className="muted" style={{ marginBottom: 16 }}>
        Bestehender Shortcode bleibt unverändert. Einfach in jede WordPress-Seite einfügen:
      </p>
      <div style={{
        background: "var(--bg-sunken)",
        border: "1px solid var(--line)",
        borderRadius: 8,
        padding: 20,
        fontFamily: "var(--font-mono)",
        fontSize: 14,
        marginBottom: 24,
      }}>
        [acn-automiete]
      </div>

      <div className="eyebrow" style={{ marginBottom: 8 }}>Erweiterte Parameter (optional)</div>
      <div style={{ display: "grid", gap: 8, fontFamily: "var(--font-mono)", fontSize: 13 }}>
        <div className="card" style={{ padding: 14 }}>
          <code>[acn-automiete view="fleet"]</code>
          <span style={{ marginLeft: 12, color: "var(--ink-3)", fontFamily: "var(--font-body)", fontSize: 13 }}>Nur Fahrzeugübersicht</span>
        </div>
        <div className="card" style={{ padding: 14 }}>
          <code>[acn-automiete view="booking" vehicle="p911-gt3"]</code>
          <span style={{ marginLeft: 12, color: "var(--ink-3)", fontFamily: "var(--font-body)", fontSize: 13 }}>Direktbuchung Fahrzeug</span>
        </div>
        <div className="card" style={{ padding: 14 }}>
          <code>[acn-automiete view="deals"]</code>
          <span style={{ marginLeft: 12, color: "var(--ink-3)", fontFamily: "var(--font-body)", fontSize: 13 }}>Aktionsseite</span>
        </div>
      </div>
    </div>
  );
}

// ============================================================
// v2.2.6 — ComparePage: Bis zu 3 Fahrzeuge nebeneinander vergleichen
// Ersetzt die alte CalcPage als Haupt-Service-Seite. Fahrzeug-Auswahl
// per Klick, Specs/Preise/Tier-Pauschalen und Inkl.-km im direkten Vergleich.
// ============================================================
function ComparePage({ vehicles, onHome, onFleet, onBook }) {
  const initial = vehicles.slice(0, Math.min(3, vehicles.length)).map(v => v.id);
  const [picked, setPicked] = React.useState(initial);

  const togglePick = (id) => {
    setPicked(p => {
      if (p.includes(id)) return p.filter(x => x !== id);
      if (p.length >= 3) return [...p.slice(1), id]; // ältesten verdrängen
      return [...p, id];
    });
  };

  const cmp = picked.map(id => vehicles.find(v => v.id === id)).filter(Boolean);

  // Helpers
  const tierFor = (v, h) => {
    if (!v || !v.tierPrices) return null;
    const x = v.tierPrices[String(h)];
    return (x && x > 0) ? x : null;
  };
  const kmFor = (v, h) => {
    if (window.ACN_kmIncludedFor) return window.ACN_kmIncludedFor(v, h);
    if (v && v.kmIncluded && v.kmIncluded[String(h)]) return parseInt(v.kmIncluded[String(h)], 10);
    return null;
  };

  // Best-Marker pro Zeile (niedrigster Wert / höchste Specs hervorheben)
  const bestOf = (vals, mode) => {
    const nums = vals.map(x => (typeof x === "number" ? x : (parseFloat(x) || null)));
    const valid = nums.filter(n => n != null);
    if (valid.length < 2) return -1;
    const target = mode === "min" ? Math.min(...valid) : Math.max(...valid);
    return nums.findIndex(n => n === target);
  };

  return (
    <main className="section">
      <div className="container">
        {/* Back-Bar */}
        <div className="booking-back-bar">
          <button type="button" className="back-link" onClick={() => onHome && onHome()}>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><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()}>
              <span>Zur Flotte</span>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h14M12 5l7 7-7 7"/></svg>
            </button>
          )}
        </div>

        <div className="eyebrow" style={{ marginBottom: 12, color: "var(--accent)" }}>Vergleichen</div>
        <h1 className="h-1" style={{ margin: 0, marginBottom: 12, maxWidth: "22ch" }}>
          Bis zu drei Fahrzeuge im direkten Vergleich.
        </h1>
        <p className="lead" style={{ maxWidth: "60ch", marginBottom: 32 }}>
          Specs, Pauschalpreise und inkludierte Kilometer auf einen Blick.
          Wählen Sie unten die Fahrzeuge, die Sie vergleichen möchten.
        </p>

        {/* Vehicle-Picker (Chips) */}
        <div className="compare-picker">
          {vehicles.map(v => {
            const active = picked.includes(v.id);
            return (
              <button
                key={v.id}
                type="button"
                className="compare-pick-chip"
                data-active={active ? "1" : ""}
                onClick={() => togglePick(v.id)}
                title={v.brand + " " + v.model}
              >
                <span className="compare-pick-thumb" style={{ backgroundImage: `url(${v.image})` }} />
                <span className="compare-pick-meta">
                  <span className="compare-pick-brand">{v.brand}</span>
                  <span className="compare-pick-model">{v.model}</span>
                </span>
                {active && <span className="compare-pick-check"><Icon.Check /></span>}
              </button>
            );
          })}
        </div>

        {cmp.length < 2 ? (
          <div className="compare-empty">
            <Icon.Info />
            <span>Wählen Sie mindestens 2 Fahrzeuge oben aus, um sie zu vergleichen.</span>
          </div>
        ) : (
          <div className="compare-table" style={{ "--cols": cmp.length }}>
            {/* Header-Reihe: Fahrzeug-Karten mit Bild, Marke/Modell und Buchen-Button */}
            <div className="compare-row compare-row-head">
              <div className="compare-cell compare-cell-key" />
              {cmp.map(v => (
                <div key={v.id} className="compare-cell compare-cell-head">
                  <div className="compare-img" style={{ backgroundImage: `url(${v.image})` }} />
                  <div className="compare-head-meta">
                    <div className="compare-head-brand">{v.brand}</div>
                    <div className="compare-head-model">{v.model}</div>
                  </div>
                  <button
                    className="btn btn-primary btn-sm compare-book-btn"
                    onClick={() => onBook && onBook(v)}
                  >
                    Jetzt buchen <Icon.ArrowRight />
                  </button>
                </div>
              ))}
            </div>

            {/* Preis-Reihe (CHF/Tag) */}
            {(() => {
              const vals = cmp.map(v => v.pricePerDay || 0);
              const best = bestOf(vals, "min");
              return (
                <div className="compare-row">
                  <div className="compare-cell compare-cell-key">Preis pro Tag</div>
                  {cmp.map((v, i) => (
                    <div key={v.id} className={`compare-cell ${i === best ? "is-best" : ""}`}>
                      <strong>CHF {chf(v.pricePerDay)}</strong>
                      {i === best && <span className="compare-best-tag">Günstigster</span>}
                    </div>
                  ))}
                </div>
              );
            })()}

            {/* Tier-Pauschalen */}
            {[
              { h: 3,   l: "Pauschale 3 Std." },
              { h: 6,   l: "Pauschale 6 Std." },
              { h: 24,  l: "Pauschale 1 Tag" },
              { h: 168, l: "Pauschale 1 Woche" },
            ].map(t => {
              const vals = cmp.map(v => tierFor(v, t.h));
              if (vals.every(x => x == null)) return null;
              const best = bestOf(vals, "min");
              return (
                <div key={t.h} className="compare-row">
                  <div className="compare-cell compare-cell-key">{t.l}</div>
                  {cmp.map((v, i) => {
                    const x = vals[i];
                    return (
                      <div key={v.id} className={`compare-cell ${i === best ? "is-best" : ""}`}>
                        {x ? <><strong>CHF {chf(x)}</strong>{i === best && vals.filter(Boolean).length > 1 && <span className="compare-best-tag">Günstigster</span>}</> : <span className="compare-na">—</span>}
                      </div>
                    );
                  })}
                </div>
              );
            })}

            {/* Inkl. km pro Tag */}
            {(() => {
              const vals = cmp.map(v => kmFor(v, 24));
              if (vals.every(x => x == null)) return null;
              const best = bestOf(vals, "max");
              return (
                <div className="compare-row">
                  <div className="compare-cell compare-cell-key">Inkl. km / Tag</div>
                  {cmp.map((v, i) => (
                    <div key={v.id} className={`compare-cell ${i === best ? "is-best" : ""}`}>
                      {vals[i] != null ? <strong>{vals[i]} km</strong> : <span className="compare-na">—</span>}
                    </div>
                  ))}
                </div>
              );
            })()}

            {/* Specs */}
            {[
              { k: "power",        l: "Leistung",       fmt: (x) => x ? `${x} PS` : "—",         mode: "max" },
              { k: "transmission", l: "Getriebe",       fmt: (x) => x || "—",                    mode: null  },
              { k: "fuel",         l: "Antrieb",        fmt: (x) => x || "—",                    mode: null  },
              { k: "seats",        l: "Plätze",         fmt: (x) => x ? `${x}` : "—",            mode: "max" },
              { k: "topSpeed",     l: "Höchstgeschw.",  fmt: (x) => x ? `${x} km/h` : "—",       mode: "max" },
              { k: "accel",        l: "0–100 km/h",     fmt: (x) => x ? `${x} s` : "—",          mode: "min" },
            ].map(spec => {
              const raws = cmp.map(v => v[spec.k]);
              if (raws.every(x => x == null || x === "" || x === 0)) return null;
              const numericFor = spec.mode ? raws.map(x => (typeof x === "number" ? x : (parseFloat(x) || null))) : raws;
              const best = spec.mode ? bestOf(numericFor, spec.mode) : -1;
              return (
                <div key={spec.k} className="compare-row">
                  <div className="compare-cell compare-cell-key">{spec.l}</div>
                  {cmp.map((v, i) => (
                    <div key={v.id} className={`compare-cell ${i === best ? "is-best" : ""}`}>
                      <strong>{spec.fmt(v[spec.k])}</strong>
                    </div>
                  ))}
                </div>
              );
            })}

            {/* Mindestmietdauer */}
            {(() => {
              const vals = cmp.map(v => parseInt(v.minHours || (v.minDays ? v.minDays * 24 : 0), 10) || 0);
              if (vals.every(x => x === 0)) return null;
              return (
                <div className="compare-row">
                  <div className="compare-cell compare-cell-key">Mindestmietdauer</div>
                  {cmp.map((v, i) => (
                    <div key={v.id} className="compare-cell">
                      <strong>{vals[i] > 0 ? `${vals[i]} Std.` : "—"}</strong>
                    </div>
                  ))}
                </div>
              );
            })()}
          </div>
        )}
      </div>
    </main>
  );
}

Object.assign(window, { DealsPage, CalcPage, ComparePage, AdminPage });
