// Boekingswizard — 4-stap, gewired aan API
function Boeking({ onNav }) {
  const [step, setStep] = React.useState(1);
  const [service, setService] = React.useState(null);
  // Pre-vul kenteken + voertuig vanuit home (sessionStorage)
  const [plate, setPlate] = React.useState(() => {
    try { return sessionStorage.getItem('gd_plate') || ""; } catch (_) { return ""; }
  });
  const [vehicle, setVehicle] = React.useState(() => {
    try {
      const v = sessionStorage.getItem('gd_vehicle');
      return v ? JSON.parse(v) : null;
    } catch (_) { return null; }
  });
  const [mileage, setMileage] = React.useState("");
  const [userVehicles, setUserVehicles] = React.useState([]);   // opgeslagen voertuigen van ingelogde klant
  const [selectedVehicleId, setSelectedVehicleId] = React.useState(null); // gekozen opgeslagen voertuig
  const [selDay, setSelDay] = React.useState(null);
  const [selTime, setSelTime] = React.useState(null);
  const [form, setForm] = React.useState({
    name: "", email: "", phone: "", address: "", notes: "",
    haalbreng: false, vervangend: false, terms: false,
  });
  const [confirmed, setConfirmed] = React.useState(false);
  const [submitError, setSubmitError] = React.useState(null);
  const [submitting, setSubmitting] = React.useState(false);
  const [services, setServices] = React.useState([]);
  const [slots, setSlots] = React.useState([]);

  // Fallback iconen per service slug
  const ICON_BY_SLUG = {
    apk: I.Apk, "apk-combi": I.Apk, herkeuring: I.Apk,
    "beurt-klein": I.Wrench, "beurt-groot": I.Cog,
    "remmen-voor": I.Cog, "remmen-set": I.Cog, distributie: I.Cog,
    diagnose: I.Diag, "diag-oem": I.Diag, "diag-mech": I.Diag,
    reparatie: I.Cog,
    "banden-wis": I.Tire, "banden-mont": I.Tire, "banden-opsl": I.Tire,
    airco: I.Snow, "airco-lek": I.Snow,
    uitlaat: I.Cog, accu: I.Battery, ruit: I.ShieldCheck,
  };

  // Diensten ophalen bij mount
  React.useEffect(() => {
    if (!window.api) return;
    window.api.services()
      .then(d => {
        const top = d.services.filter(s => s.duration_min > 0).slice(0, 8).map(s => ({
          id: s.id, slug: s.slug, name: s.name, duration: s.duration_min,
          price: s.price, desc: s.description,
          icon: ICON_BY_SLUG[s.slug] || I.Wrench,
        }));
        setServices(top);
      })
      .catch(() => {/* fallback to mock below */});

    // Opgeslagen voertuigen van ingelogde klant ophalen (faalt stil als niet ingelogd)
    window.api.auth.me()
      .then(d => {
        const vs = d.vehicles || [];
        setUserVehicles(vs);
        if (vs.length && !plate) {
          // Auto-select het primaire (eerste) voertuig
          setSelectedVehicleId(vs[0].id);
          setPlate(vs[0].license_plate);
          setVehicle({
            make: vs[0].make, model: vs[0].model, year: vs[0].year,
            fuel_type: vs[0].fuel_type, apk_expiry: vs[0].apk_expiry,
          });
          // Naam/email/telefoon ook prefillen voor stap 4
          setForm(f => ({ ...f, name: d.user.name || f.name, email: d.user.email || f.email, phone: d.user.phone || f.phone }));
        }
      })
      .catch(() => {/* niet ingelogd, dat mag */});
  }, []);

  // Mock fallback als API niet werkt
  const fallbackServices = [
    { id: 1, slug: "apk", icon: I.Apk, name: "APK keuring", duration: 45, price: 55, desc: "RDW erkend. Inclusief uitgebreid rapport." },
    { id: 4, slug: "beurt-klein", icon: I.Wrench, name: "Kleine beurt", duration: 60, price: 89, desc: "Olie + filter + 30-punts inspectie." },
    { id: 5, slug: "beurt-groot", icon: I.Cog, name: "Grote beurt", duration: 180, price: 249, desc: "Volledig onderhoud." },
    { id: 16, slug: "airco", icon: I.Snow, name: "Airco service", duration: 30, price: 69, desc: "F-gassen — R134a + R1234yf." },
    { id: 13, slug: "banden-wis", icon: I.Tire, name: "Banden wisselen (4)", duration: 30, price: 40, desc: "Op velg." },
    { id: 9, slug: "diagnose", icon: I.Diag, name: "Diagnose / uitleescode", duration: 30, price: 45, desc: "Universeel." },
    { id: 12, slug: "reparatie", icon: I.Cog, name: "Reparatie / anders", duration: null, price: null, desc: "Op maat." },
  ];
  const displayServices = services.length ? services : fallbackServices;

  // Vehicle lookup wanneer plate >= 6
  React.useEffect(() => {
    const clean = plate.replace(/[^A-Z0-9]/gi, "");
    if (clean.length < 6 || !window.api) { return; }
    const t = setTimeout(async () => {
      try { const v = await window.api.kenteken.lookup(plate); setVehicle(v); }
      catch (e) { setVehicle(null); }
    }, 400);
    return () => clearTimeout(t);
  }, [plate]);

  // Vrije slots ophalen wanneer dag + service gekozen
  React.useEffect(() => {
    if (!service || !selDay || !window.api) { setSlots([]); return; }
    const dateStr = selDay instanceof Date
      ? selDay.toISOString().slice(0, 10)
      : selDay;
    window.api.availability(service.id, dateStr)
      .then(d => setSlots(d.slots || []))
      .catch(() => setSlots([]));
  }, [service, selDay]);

  const goNext = () => setStep(s => Math.min(s + 1, 4));
  const goBack = () => setStep(s => Math.max(s - 1, 1));

  // Validation per step
  const canNext = (
    (step === 1 && service) ||
    (step === 2 && plate.length >= 6) ||
    (step === 3 && selDay && selTime) ||
    (step === 4 && form.name && form.email && form.phone && form.terms)
  );

  return (
    <div style={{ background: "var(--bg)", minHeight: "calc(100vh - 73px)" }}>
      {/* Heading band */}
      <section style={{ borderBottom: "1px solid var(--border)", background: "var(--surface)" }}>
        <div style={{ maxWidth: 1080, margin: "0 auto", padding: "48px 32px" }}>
          <button onClick={() => onNav("home")} className="btn btn-ghost btn-sm" style={{ marginBottom: 24 }}>
            <I.ArrowLeft size={14}/> Terug naar home
          </button>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", flexWrap: "wrap", gap: 24 }}>
            <div>
              <div className="eyebrow" style={{ marginBottom: 10 }}>Afspraak maken</div>
              <h1 className="headline" style={{ fontSize: 40 }}>
                {confirmed ? "Bevestigd, tot ziens." : "Plan uw bezoek in 4 stappen."}
              </h1>
            </div>
            {!confirmed && (
              <div className="text-muted" style={{ fontSize: 14, display: "flex", alignItems: "center", gap: 8 }}>
                <I.Clock size={14}/> Duurt &lt; 60 seconden
              </div>
            )}
          </div>
        </div>
      </section>

      {/* Stepper */}
      {!confirmed && <Stepper step={step}/>}

      <div style={{ maxWidth: 1080, margin: "0 auto", padding: "56px 32px 80px" }}>
        {confirmed ? (
          <ConfirmationCard
            service={service} vehicle={vehicle} plate={plate}
            day={selDay} time={selTime} form={form}
            onNav={onNav}
          />
        ) : (
          <div style={{ display: "grid", gridTemplateColumns: "1.5fr 1fr", gap: 48, alignItems: "flex-start" }}>
            {/* Left: step content */}
            <div>
              {step === 1 && (
                <Step1 services={displayServices} value={service} onChange={setService}/>
              )}
              {step === 2 && (
                <Step2
                  plate={plate} setPlate={setPlate}
                  vehicle={vehicle} setVehicle={setVehicle}
                  mileage={mileage} setMileage={setMileage}
                  userVehicles={userVehicles}
                  selectedVehicleId={selectedVehicleId}
                  setSelectedVehicleId={setSelectedVehicleId}
                />
              )}
              {step === 3 && (
                <Step3
                  service={service}
                  selDay={selDay} setSelDay={setSelDay}
                  selTime={selTime} setSelTime={setSelTime}
                />
              )}
              {step === 4 && (
                <Step4 form={form} setForm={setForm}/>
              )}

              {/* Nav buttons */}
              <div style={{ display: "flex", justifyContent: "space-between", marginTop: 40, alignItems: "center" }}>
                <button
                  className="btn btn-ghost"
                  onClick={goBack}
                  disabled={step === 1}
                  style={{ opacity: step === 1 ? 0.4 : 1 }}
                >
                  <I.ArrowLeft size={16}/> Vorige
                </button>
                <button
                  className="btn btn-primary btn-lg"
                  onClick={async () => {
                    if (step !== 4) return goNext();
                    if (!window.api) { setConfirmed(true); return; }
                    setSubmitError(null);
                    setSubmitting(true);
                    try {
                      // Probeer eerst registreren als nog geen account, fallback op direct boeken
                      try {
                        await window.api.auth.register({
                          email: form.email,
                          password: form.phone || `Garage${Date.now()}`,
                          name: form.name,
                          phone: form.phone,
                        });
                      } catch (_) { /* bestaat al — proberen we te boeken */ }

                      const startDate = selDay instanceof Date ? selDay.toISOString().slice(0, 10) : selDay;
                      const startAt = `${startDate}T${selTime}:00`;
                      const apptPayload = {
                        service_id: service.id,
                        start_at: startAt,
                        notes: form.notes || null,
                      };
                      if (selectedVehicleId) {
                        apptPayload.vehicle_id = selectedVehicleId;
                      } else {
                        apptPayload.vehicle = {
                          license_plate: plate,
                          make: vehicle?.make,
                          model: vehicle?.model,
                          year: vehicle?.year,
                          fuel_type: vehicle?.fuel_type,
                          mileage: mileage ? Number(mileage) : null,
                          apk_expiry: vehicle?.apk_expiry,
                        };
                      }
                      await window.api.appointments.create(apptPayload);
                      try { sessionStorage.removeItem('gd_plate'); sessionStorage.removeItem('gd_vehicle'); } catch (_) {}
                      setConfirmed(true);
                    } catch (err) {
                      setSubmitError(err.message || "Er ging iets mis bij het boeken");
                    } finally {
                      setSubmitting(false);
                    }
                  }}
                  disabled={!canNext || submitting}
                  style={{ opacity: (canNext && !submitting) ? 1 : 0.4, pointerEvents: (canNext && !submitting) ? "auto" : "none" }}
                >
                  {submitting ? "Bezig..." : (step === 4 ? "Bevestig afspraak" : "Volgende")}
                  <I.ArrowRight size={16}/>
                </button>
                {submitError && (
                  <div className="pill danger" style={{ marginLeft: 12 }}>
                    <span className="dot"/> {submitError}
                  </div>
                )}
              </div>
            </div>

            {/* Right: live summary */}
            <SummaryPanel service={service} vehicle={vehicle} plate={plate} day={selDay} time={selTime} form={form}/>
          </div>
        )}
      </div>
    </div>
  );
}

function Stepper({ step }) {
  const labels = ["Dienst", "Voertuig", "Tijdstip", "Gegevens"];
  return (
    <div style={{ borderBottom: "1px solid var(--border)", background: "var(--bg)" }}>
      <div style={{ maxWidth: 1080, margin: "0 auto", padding: "24px 32px" }}>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 12 }}>
          {labels.map((l, i) => {
            const n = i + 1;
            const done = n < step;
            const cur = n === step;
            return (
              <div key={n} style={{ display: "flex", alignItems: "center", gap: 12 }}>
                <div style={{
                  width: 32, height: 32, borderRadius: 999,
                  border: cur ? "2px solid var(--accent)" : done ? "2px solid var(--accent)" : "1px solid var(--border)",
                  background: done ? "var(--accent)" : "transparent",
                  color: done ? "#0B0B0C" : cur ? "var(--accent)" : "var(--text-muted)",
                  display: "flex", alignItems: "center", justifyContent: "center",
                  fontWeight: 700, fontSize: 13, fontFamily: "var(--font-mono)",
                  flexShrink: 0, transition: "all .25s ease",
                }}>
                  {done ? <I.Check size={14}/> : n}
                </div>
                <div>
                  <div className="text-muted" style={{ fontSize: 11, fontWeight: 600, letterSpacing: "0.08em", textTransform: "uppercase" }}>
                    Stap {n}
                  </div>
                  <div style={{ fontSize: 14, fontWeight: 600, color: cur || done ? "var(--text)" : "var(--text-muted)" }}>
                    {l}
                  </div>
                </div>
                {n < 4 && (
                  <div style={{ flex: 1, height: 1, background: done ? "var(--accent)" : "var(--border)",
                                marginLeft: 12, transition: "background .25s ease" }}/>
                )}
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

// ─── STEP 1 ─────────────────────────────────────────────
function Step1({ services, value, onChange }) {
  return (
    <div>
      <h2 style={{ fontSize: 28, fontWeight: 700, letterSpacing: "-0.02em", marginBottom: 8 }}>
        Welke service heeft u nodig?
      </h2>
      <p className="text-muted" style={{ marginTop: 0, marginBottom: 28, fontSize: 15 }}>
        Niet zeker? Kies "Reparatie / anders" en beschrijf het probleem.
      </p>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
        {services.map(s => {
          const sel = value?.id === s.id;
          return (
            <button key={s.id}
              onClick={() => onChange(s)}
              className="card lift"
              style={{
                padding: 22, textAlign: "left", cursor: "pointer",
                background: sel ? "color-mix(in oklab, var(--accent) 8%, var(--surface))" : "var(--surface)",
                border: sel ? "1.5px solid var(--accent)" : "1px solid var(--border)",
                color: "var(--text)",
                position: "relative",
              }}
            >
              <div style={{ display: "flex", alignItems: "flex-start", gap: 14, marginBottom: 14 }}>
                <div style={{ width: 40, height: 40, borderRadius: 10, background: "var(--surface-2)",
                              border: "1px solid var(--border)",
                              display: "flex", alignItems: "center", justifyContent: "center",
                              color: "var(--accent)", flexShrink: 0 }}>
                  <s.icon size={20}/>
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontWeight: 700, fontSize: 16, marginBottom: 4 }}>{s.name}</div>
                  <div className="text-muted" style={{ fontSize: 13, lineHeight: 1.5 }}>{s.desc}</div>
                </div>
                {sel && (
                  <div style={{ width: 22, height: 22, borderRadius: 999, background: "var(--accent)",
                                display: "flex", alignItems: "center", justifyContent: "center", color: "#0B0B0C" }}>
                    <I.Check size={14}/>
                  </div>
                )}
              </div>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center",
                            paddingTop: 14, borderTop: "1px dashed var(--border)" }}>
                <span className="text-muted" style={{ fontSize: 13 }}>
                  {s.duration ? `${s.duration} min` : "Variabel"}
                </span>
                <span className="text-mono" style={{ fontWeight: 700, fontSize: 14 }}>
                  {s.price ? `vanaf €${s.price}` : "op maat"}
                </span>
              </div>
            </button>
          );
        })}
      </div>
    </div>
  );
}

// ─── STEP 2 ─────────────────────────────────────────────
function Step2({ plate, setPlate, vehicle, setVehicle, mileage, setMileage,
                 userVehicles = [], selectedVehicleId, setSelectedVehicleId }) {
  // "Ander voertuig" mode — toont kenteken-input ook al heeft de klant opgeslagen voertuigen
  const [otherMode, setOtherMode] = React.useState(false);
  const showSavedPicker = userVehicles.length > 0 && !otherMode;

  // Een opgeslagen voertuig kiezen
  const pickSaved = (v) => {
    setSelectedVehicleId(v.id);
    setPlate(v.license_plate);
    setVehicle({ make: v.make, model: v.model, year: v.year, fuel_type: v.fuel_type, apk_expiry: v.apk_expiry });
    setMileage(v.mileage ? String(v.mileage) : "");
  };

  // Schakelen naar "ander voertuig" — wis selectie zodat kenteken-input opent
  const switchToOther = () => {
    setOtherMode(true);
    setSelectedVehicleId(null);
    setPlate("");
    setVehicle(null);
    setMileage("");
  };

  // RDW lookup wanneer in "ander voertuig" mode of niet ingelogd
  React.useEffect(() => {
    if (selectedVehicleId) return; // niet looken-up als opgeslagen voertuig actief is
    const clean = plate.replace(/[^A-Z0-9]/gi, "");
    if (clean.length < 6) { setVehicle(null); return; }
    if (!window.api) return;
    const t = setTimeout(async () => {
      try {
        const v = await window.api.kenteken.lookup(plate);
        setVehicle(v);
      } catch (e) {
        setVehicle(null);
      }
    }, 400);
    return () => clearTimeout(t);
  }, [plate, selectedVehicleId]);

  return (
    <div>
      <h2 style={{ fontSize: 28, fontWeight: 700, letterSpacing: "-0.02em", marginBottom: 8 }}>
        Welk voertuig?
      </h2>
      <p className="text-muted" style={{ marginTop: 0, marginBottom: 28, fontSize: 15 }}>
        {showSavedPicker
          ? "Kies een opgeslagen voertuig of voeg er een toe via kenteken."
          : "We halen de auto-gegevens automatisch op via de RDW."}
      </p>

      {showSavedPicker && (
        <div style={{ display: "flex", flexDirection: "column", gap: 10, marginBottom: 14 }}>
          {userVehicles.map(v => {
            const sel = selectedVehicleId === v.id;
            const apkDate = v.apk_expiry ? new Date(v.apk_expiry) : null;
            return (
              <button key={v.id}
                onClick={() => pickSaved(v)}
                className="card lift"
                style={{
                  padding: 18, textAlign: "left", cursor: "pointer",
                  background: sel ? "color-mix(in oklab, var(--accent) 8%, var(--surface))" : "var(--surface)",
                  border: sel ? "1.5px solid var(--accent)" : "1px solid var(--border)",
                  display: "flex", justifyContent: "space-between", alignItems: "center", gap: 16,
                }}>
                <div style={{ display: "flex", alignItems: "center", gap: 16 }}>
                  <Plate value={v.license_plate} size="sm"/>
                  <div>
                    <div style={{ fontWeight: 700, fontSize: 15 }}>
                      {[v.make, v.model].filter(Boolean).join(" ") || "Onbekend"}
                    </div>
                    <div className="text-muted" style={{ fontSize: 12 }}>
                      {v.year ? `Bouwjaar ${v.year}` : ""}
                      {v.fuel_type ? ` · ${v.fuel_type}` : ""}
                      {apkDate ? ` · APK tot ${apkDate.toLocaleDateString("nl-NL")}` : ""}
                    </div>
                  </div>
                </div>
                {sel && <span className="pill accent"><span className="dot"/> Gekozen</span>}
              </button>
            );
          })}
          <button onClick={switchToOther}
            className="card lift"
            style={{
              padding: 16, background: "transparent", border: "1.5px dashed var(--border)",
              cursor: "pointer", color: "var(--text-muted)",
              display: "flex", alignItems: "center", justifyContent: "center", gap: 8, fontWeight: 600,
            }}>
            <I.Plus size={14}/> Ander voertuig (kenteken invoeren)
          </button>
        </div>
      )}

      {!showSavedPicker && userVehicles.length > 0 && (
        <button onClick={() => { setOtherMode(false); }}
          className="btn btn-ghost btn-sm" style={{ marginBottom: 14 }}>
          <I.ArrowLeft size={12}/> Terug naar mijn voertuigen
        </button>
      )}

      <div className="card" style={{ padding: 28, background: "var(--surface)", display: showSavedPicker ? "none" : "block" }}>
        <label style={{ display: "block", marginBottom: 8, fontSize: 12, fontWeight: 600,
                        color: "var(--text-muted)", textTransform: "uppercase", letterSpacing: "0.08em" }}>
          Kenteken
        </label>
        <div style={{ position: "relative", maxWidth: 360 }}>
          <div style={{ position: "absolute", left: 0, top: 0, bottom: 0, width: 44,
                        background: "#003399", display: "flex", alignItems: "center", justifyContent: "center",
                        color: "white", fontWeight: 800, fontFamily: "var(--font-display)",
                        fontSize: 12,
                        borderRadius: "6px 0 0 6px",
                        border: "2px solid #1a1a1a", borderRight: 0 }}>
            NL
          </div>
          <input
            value={plate}
            onChange={(e) => setPlate(e.target.value.toUpperCase())}
            placeholder="X-123-YZ"
            className="plate-input"
            style={{ paddingLeft: 60 }}
            maxLength={10}
          />
        </div>

        {/* RDW result */}
        <div style={{ minHeight: 130, marginTop: 20 }}>
          {plate.length < 6 ? (
            <div className="placeholder" style={{ height: 110 }}>
              voer kenteken in voor auto-detectie
            </div>
          ) : !vehicle ? (
            <div style={{ display: "flex", alignItems: "center", gap: 12, color: "var(--text-muted)", fontSize: 14, padding: 20 }}>
              <span style={{ width: 14, height: 14, borderRadius: 999, border: "2px solid var(--accent)",
                             borderTopColor: "transparent", animation: "spin 0.8s linear infinite" }}/>
              RDW raadplegen…
            </div>
          ) : (
            <div className="card" style={{ padding: 22, background: "var(--surface-2)",
                                            border: "1px solid color-mix(in oklab, var(--success) 30%, var(--border))" }}>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 14 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
                  <I.Car size={32} style={{ color: "var(--accent)" }}/>
                  <div>
                    <div style={{ fontWeight: 700, fontSize: 18 }}>
                      {[vehicle.make || vehicle.merk, vehicle.model].filter(Boolean).join(' ')}
                    </div>
                    <div className="text-muted" style={{ fontSize: 13, marginTop: 2 }}>
                      {vehicle.color || vehicle.kleur || ''}
                    </div>
                  </div>
                </div>
                <span className="pill success"><span className="dot"/> Gevonden</span>
              </div>
              <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 16,
                            paddingTop: 14, borderTop: "1px dashed var(--border)" }}>
                <Spec label="Bouwjaar" value={vehicle.year || vehicle.jaar}/>
                <Spec label="Brandstof" value={vehicle.fuel_type || vehicle.brandstof}/>
                <Spec label="APK verloopt" value={(vehicle.apk_expiry ? new Date(vehicle.apk_expiry).toLocaleDateString('nl-NL') : vehicle.apk)} accent/>
              </div>
            </div>
          )}
        </div>

        {vehicle && (
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14, marginTop: 18 }}>
            <div className="field">
              <label>Kilometerstand (optioneel)</label>
              <input className="input" placeholder="bv. 142.500"
                     value={mileage} onChange={(e) => setMileage(e.target.value)}/>
            </div>
            <div className="field">
              <label>Niet de juiste auto?</label>
              <button className="btn btn-ghost btn-sm" style={{ height: 44 }}>
                Handmatig invullen
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

function Spec({ label, value, accent }) {
  return (
    <div>
      <div className="text-muted" style={{ fontSize: 11, fontWeight: 600, letterSpacing: "0.08em", textTransform: "uppercase", marginBottom: 4 }}>
        {label}
      </div>
      <div className="text-mono" style={{ fontSize: 14, fontWeight: 700, color: accent ? "var(--accent)" : "var(--text)" }}>
        {value}
      </div>
    </div>
  );
}

// ─── STEP 3 ─────────────────────────────────────────────
function Step3({ service, selDay, setSelDay, selTime, setSelTime }) {
  const today = new Date(2026, 4, 4); // 4 mei 2026 (maandag)
  const [monthOffset, setMonthOffset] = React.useState(0);

  // Build month grid
  const month = new Date(today.getFullYear(), today.getMonth() + monthOffset, 1);
  const monthName = month.toLocaleDateString("nl-NL", { month: "long", year: "numeric" });
  const firstDow = (month.getDay() + 6) % 7; // Mon=0
  const daysInMonth = new Date(month.getFullYear(), month.getMonth() + 1, 0).getDate();

  // Random availability stable per date
  const availabilityFor = (d) => {
    if (!d) return "none";
    const date = new Date(month.getFullYear(), month.getMonth(), d);
    if (date < today) return "past";
    const dow = date.getDay();
    if (dow === 0) return "closed"; // Sunday
    if (date.toDateString() === new Date(2026, 4, 5).toDateString()) return "closed"; // Bevrijdingsdag
    const seed = (d * 7 + month.getMonth() * 13) % 10;
    if (seed < 2) return "full";
    if (seed < 5) return "limited";
    return "free";
  };

  // Slots for selected day
  const slotsFor = (date) => {
    if (!date) return [];
    const all = ["08:00", "08:30", "09:00", "09:30", "10:00", "10:30", "11:00", "11:30",
                 "13:00", "13:30", "14:00", "14:30", "15:00", "15:30", "16:00", "16:30", "17:00"];
    const seed = (date * 31) % 10;
    return all.map((s, i) => ({
      time: s,
      free: ((i + seed) % 4) !== 0,
    }));
  };

  const cells = [];
  for (let i = 0; i < firstDow; i++) cells.push(null);
  for (let d = 1; d <= daysInMonth; d++) cells.push(d);
  while (cells.length < 42) cells.push(null);

  return (
    <div>
      <h2 style={{ fontSize: 28, fontWeight: 700, letterSpacing: "-0.02em", marginBottom: 8 }}>
        Wanneer komt het uit?
      </h2>
      <p className="text-muted" style={{ marginTop: 0, marginBottom: 28, fontSize: 15 }}>
        Geblokte tijden zijn al volgeboekt. Slot duurt {service?.duration || 60} min — buffer inclusief.
      </p>

      <div className="card" style={{ padding: 28 }}>
        <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 32 }}>
          {/* Calendar */}
          <div>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 16 }}>
              <button onClick={() => setMonthOffset(o => o - 1)} className="btn btn-ghost btn-sm">
                <I.ArrowLeft size={14}/>
              </button>
              <div style={{ fontWeight: 700, fontSize: 16, textTransform: "capitalize" }}>{monthName}</div>
              <button onClick={() => setMonthOffset(o => o + 1)} className="btn btn-ghost btn-sm">
                <I.ArrowRight size={14}/>
              </button>
            </div>

            <div style={{ display: "grid", gridTemplateColumns: "repeat(7, 1fr)", gap: 4 }}>
              {["Ma","Di","Wo","Do","Vr","Za","Zo"].map(d => (
                <div key={d} className="text-muted" style={{ fontSize: 11, fontWeight: 600, textAlign: "center", padding: "6px 0", letterSpacing: "0.05em" }}>
                  {d}
                </div>
              ))}
              {cells.map((d, i) => {
                if (!d) return <div key={i} style={{ height: 44 }}/>;
                const av = availabilityFor(d);
                const isSel = selDay === d && monthOffset === 0;
                const disabled = av === "past" || av === "full" || av === "closed" || av === "none";
                const colorMap = {
                  free: "var(--success)",
                  limited: "var(--warning)",
                  full: "var(--text-muted)",
                  closed: "var(--text-muted)",
                  past: "var(--text-muted)",
                };
                return (
                  <button key={i}
                    onClick={() => { if (!disabled) { setSelDay(d); setSelTime(null); } }}
                    disabled={disabled}
                    style={{
                      height: 44, borderRadius: 8,
                      background: isSel ? "var(--accent)" : "transparent",
                      border: isSel ? "1.5px solid var(--accent)" : "1px solid var(--border)",
                      color: isSel ? "#0B0B0C" : disabled ? "var(--text-muted)" : "var(--text)",
                      fontWeight: 600, fontSize: 14, fontFamily: "var(--font-mono)",
                      cursor: disabled ? "not-allowed" : "pointer",
                      opacity: av === "past" || av === "closed" ? 0.3 : 1,
                      position: "relative",
                      transition: "all .15s ease",
                    }}
                  >
                    {d}
                    {!isSel && !disabled && (
                      <span style={{
                        position: "absolute", bottom: 5, left: "50%", transform: "translateX(-50%)",
                        width: 4, height: 4, borderRadius: 999, background: colorMap[av],
                      }}/>
                    )}
                  </button>
                );
              })}
            </div>

            <div style={{ display: "flex", gap: 18, marginTop: 18, fontSize: 12, color: "var(--text-muted)" }}>
              <Legend color="var(--success)" label="Vrij"/>
              <Legend color="var(--warning)" label="Beperkt"/>
              <Legend color="transparent" border label="Vol / dicht"/>
            </div>
          </div>

          {/* Time slots */}
          <div>
            <div style={{ fontSize: 13, fontWeight: 600, color: "var(--text-muted)", textTransform: "uppercase",
                          letterSpacing: "0.08em", marginBottom: 14 }}>
              {selDay ? `${selDay} ${monthName}` : "Kies eerst een dag"}
            </div>
            {selDay ? (
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8, maxHeight: 380, overflowY: "auto" }}>
                {slotsFor(selDay).map((s, i) => (
                  <button key={i}
                    onClick={() => s.free && setSelTime(s.time)}
                    disabled={!s.free}
                    style={{
                      padding: "12px 14px",
                      borderRadius: 8,
                      background: selTime === s.time ? "var(--accent)" : "var(--surface-2)",
                      border: "1px solid " + (selTime === s.time ? "var(--accent)" : "var(--border)"),
                      color: selTime === s.time ? "#0B0B0C" : s.free ? "var(--text)" : "var(--text-muted)",
                      cursor: s.free ? "pointer" : "not-allowed",
                      opacity: s.free ? 1 : 0.4,
                      fontFamily: "var(--font-mono)", fontWeight: 600, fontSize: 13,
                      textDecoration: s.free ? "none" : "line-through",
                    }}>
                    {s.time}
                  </button>
                ))}
              </div>
            ) : (
              <div className="placeholder" style={{ height: 220 }}>kies een dag</div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

function Legend({ color, border, label }) {
  return (
    <span style={{ display: "flex", alignItems: "center", gap: 6 }}>
      <span style={{ width: 8, height: 8, borderRadius: 999,
                     background: color === "transparent" ? "transparent" : color,
                     border: border ? "1px solid var(--border)" : "none" }}/>
      {label}
    </span>
  );
}

// ─── STEP 4 ─────────────────────────────────────────────
function Step4({ form, setForm }) {
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));
  return (
    <div>
      <h2 style={{ fontSize: 28, fontWeight: 700, letterSpacing: "-0.02em", marginBottom: 8 }}>
        Uw gegevens
      </h2>
      <p className="text-muted" style={{ marginTop: 0, marginBottom: 28, fontSize: 15 }}>
        We sturen een bevestiging per e-mail en SMS-reminder 24u vooraf.
      </p>
      <div className="card" style={{ padding: 28 }}>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
          <div className="field" style={{ gridColumn: "1 / -1" }}>
            <label>Naam *</label>
            <input className="input" placeholder="Voor- en achternaam" value={form.name} onChange={(e) => set("name", e.target.value)}/>
          </div>
          <div className="field">
            <label>E-mail *</label>
            <input className="input" type="email" placeholder="naam@voorbeeld.nl" value={form.email} onChange={(e) => set("email", e.target.value)}/>
          </div>
          <div className="field">
            <label>Telefoon *</label>
            <input className="input" type="tel" placeholder="06 — …" value={form.phone} onChange={(e) => set("phone", e.target.value)}/>
          </div>
          <div className="field" style={{ gridColumn: "1 / -1" }}>
            <label>Adres (optioneel — voor haal/breng)</label>
            <input className="input" placeholder="Straatnaam, postcode, plaats" value={form.address} onChange={(e) => set("address", e.target.value)}/>
          </div>
          <div className="field" style={{ gridColumn: "1 / -1" }}>
            <label>Opmerkingen (optioneel)</label>
            <textarea className="input" rows={3}
              placeholder='bijv. "auto trekt naar links bij remmen", "lampje motormanagement brandt"'
              value={form.notes} onChange={(e) => set("notes", e.target.value)}/>
          </div>
        </div>

        <hr className="div" style={{ margin: "24px 0" }}/>

        <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
          <Toggle checked={form.haalbreng} onChange={(v) => set("haalbreng", v)}
                  label="Haal- en brengservice"
                  sub="We halen uw auto thuis op (binnen 15 km, +€19)"/>
          <Toggle checked={form.vervangend} onChange={(v) => set("vervangend", v)}
                  label="Vervangend vervoer"
                  sub="Leenauto beschikbaar (op aanvraag, gratis bij &gt; 4u werkplaatstijd)"/>
        </div>

        <hr className="div" style={{ margin: "24px 0" }}/>

        <Toggle checked={form.terms} onChange={(v) => set("terms", v)}
                label={<span>Ik ga akkoord met de <a style={{ color: "var(--accent)", textDecoration: "underline" }}>algemene voorwaarden</a> en het privacybeleid.</span>}
                required/>
      </div>
    </div>
  );
}

function Toggle({ checked, onChange, label, sub, required }) {
  return (
    <button onClick={() => onChange(!checked)} style={{
      background: "none", border: 0, padding: 0, textAlign: "left", cursor: "pointer",
      display: "flex", alignItems: "flex-start", gap: 14, color: "var(--text)",
    }}>
      <div style={{
        width: 22, height: 22, borderRadius: 6, flexShrink: 0,
        background: checked ? "var(--accent)" : "transparent",
        border: "1.5px solid " + (checked ? "var(--accent)" : "var(--border)"),
        display: "flex", alignItems: "center", justifyContent: "center",
        color: "#0B0B0C",
      }}>
        {checked && <I.Check size={14}/>}
      </div>
      <div>
        <div style={{ fontWeight: 600, fontSize: 14 }}>{label} {required && <span style={{ color: "var(--accent)" }}>*</span>}</div>
        {sub && <div className="text-muted" style={{ fontSize: 13, marginTop: 4 }} dangerouslySetInnerHTML={{ __html: sub }}/>}
      </div>
    </button>
  );
}

// ─── SUMMARY PANEL ─────────────────────────────────────
function SummaryPanel({ service, vehicle, plate, day, time, form }) {
  return (
    <div className="card" style={{ padding: 28, position: "sticky", top: 100,
                                     background: "linear-gradient(180deg, var(--surface), var(--surface-2))" }}>
      <div className="eyebrow" style={{ marginBottom: 14 }}>Uw boeking</div>

      <Row label="Service">
        {service ? (
          <div>
            <div style={{ fontWeight: 600 }}>{service.name}</div>
            <div className="text-muted text-mono" style={{ fontSize: 13 }}>
              {service.duration ? `${service.duration} min` : "variabel"} · {service.price ? `vanaf €${service.price}` : "op maat"}
            </div>
          </div>
        ) : <span className="text-muted">—</span>}
      </Row>

      <Row label="Voertuig">
        {plate ? (
          <div>
            <Plate value={plate || "X-123-YZ"} size="sm"/>
            {vehicle && <div className="text-muted" style={{ fontSize: 13, marginTop: 8 }}>
              {[vehicle.make || vehicle.merk, vehicle.model].filter(Boolean).join(' ')}
              {(vehicle.year || vehicle.jaar) ? ` (${vehicle.year || vehicle.jaar})` : ''}
            </div>}
          </div>
        ) : <span className="text-muted">—</span>}
      </Row>

      <Row label="Tijdstip">
        {day && time ? (
          <div>
            <div style={{ fontWeight: 600 }}>{day} mei 2026</div>
            <div className="text-muted text-mono" style={{ fontSize: 13 }}>{time} uur</div>
          </div>
        ) : <span className="text-muted">—</span>}
      </Row>

      <Row label="Klant" last>
        {form.name ? (
          <div>
            <div style={{ fontWeight: 600 }}>{form.name}</div>
            <div className="text-muted" style={{ fontSize: 13 }}>{form.email}</div>
          </div>
        ) : <span className="text-muted">—</span>}
      </Row>

      <hr className="div" style={{ margin: "20px 0" }}/>
      <div style={{ display: "flex", justifyContent: "space-between", fontSize: 14, marginBottom: 8 }}>
        <span className="text-muted">Verwachte kosten</span>
        <span className="text-mono" style={{ fontWeight: 700 }}>
          {service?.price ? `vanaf €${service.price}` : "op maat"}
        </span>
      </div>
      <div className="text-muted" style={{ fontSize: 12, lineHeight: 1.5 }}>
        Eindbedrag wordt na inspectie definitief. Geen verborgen kosten —
        bij meerwerk bellen we eerst.
      </div>
    </div>
  );
}

function Row({ label, children, last }) {
  return (
    <div style={{ paddingBottom: 16, marginBottom: 16,
                  borderBottom: last ? "none" : "1px dashed var(--border)" }}>
      <div className="text-muted" style={{ fontSize: 11, fontWeight: 600, letterSpacing: "0.08em", textTransform: "uppercase", marginBottom: 6 }}>
        {label}
      </div>
      {children}
    </div>
  );
}

// ─── CONFIRMATION ──────────────────────────────────────
function ConfirmationCard({ service, vehicle, plate, day, time, form, onNav }) {
  return (
    <div style={{ maxWidth: 720, margin: "0 auto" }}>
      <div className="card" style={{ padding: 48, textAlign: "center",
                                      background: "linear-gradient(180deg, var(--surface), color-mix(in oklab, var(--accent) 4%, var(--surface)))" }}>
        <div style={{ width: 72, height: 72, borderRadius: 999, background: "var(--accent)",
                      display: "flex", alignItems: "center", justifyContent: "center",
                      margin: "0 auto 24px", color: "#0B0B0C" }}>
          <I.Check size={36}/>
        </div>
        <h2 style={{ fontSize: 32, fontWeight: 700, letterSpacing: "-0.02em", marginBottom: 12 }}>
          Tot {form.name?.split(" ")[0] || "snel"}!
        </h2>
        <p className="subhead" style={{ margin: 0, marginBottom: 32 }}>
          Bevestiging is verzonden naar <strong style={{ color: "var(--text)" }}>{form.email}</strong>.<br/>
          24 uur voor uw afspraak ontvangt u een herinnering.
        </p>

        <div className="card" style={{ padding: 24, background: "var(--surface-2)", textAlign: "left", marginBottom: 24 }}>
          <Row label="Service">
            <div style={{ fontWeight: 600 }}>{service?.name}</div>
          </Row>
          <Row label="Voertuig">
            <Plate value={plate} size="sm"/>
            {vehicle && <span className="text-muted" style={{ fontSize: 13, marginLeft: 10 }}>
              {vehicle.merk} {vehicle.model}
            </span>}
          </Row>
          <Row label="Tijdstip" last>
            <div style={{ fontWeight: 600 }}>{day} mei 2026 — {time}</div>
            <div className="text-muted" style={{ fontSize: 13 }}>Vestiging Vijfhuizen — Spieringweg 1234</div>
          </Row>
        </div>

        <div style={{ display: "flex", gap: 12, justifyContent: "center" }}>
          <button className="btn btn-ghost">
            <I.Calendar size={16}/> Toevoegen aan agenda
          </button>
          <button className="btn btn-primary" onClick={() => onNav("home")}>
            Terug naar home <I.ArrowRight size={16}/>
          </button>
        </div>
      </div>
    </div>
  );
}

// expose
window.Boeking = Boeking;
