// Booking step 1 — contact + extras
const StepsBar = ({ step }) => (
  <div className="steps-bar">
    <div className={"step " + (step === 1 ? "active" : "done")}>
      <span className="num">{step > 1 ? "✓" : "1"}</span>
      <span>Araç Seçimi</span>
    </div>
    <div className={"step " + (step === 2 ? "active" : (step > 2 ? "done" : ""))}>
      <span className="num">{step > 2 ? "✓" : "2"}</span>
      <span>İletişim & Detaylar</span>
    </div>
    <div className={"step " + (step === 3 ? "active" : (step > 3 ? "done" : ""))}>
      <span className="num">{step > 3 ? "✓" : "3"}</span>
      <span>Ödeme</span>
    </div>
    <div className={"step " + (step === 4 ? "active" : "")}>
      <span className="num">4</span>
      <span>Onay</span>
    </div>
  </div>
);

const BookingSummary = ({ vehicle, query, ccy, extras = {}, coupon = null }) => {
  if (!vehicle) return null;
  const base = vehicle.priceTry || 1200;
  const extrasPrice = (extras.babySeat ? 150 : 0) + (extras.greet ? 200 : 0) + (extras.water ? 80 : 0);
  const subtotal = base + extrasPrice;
  const discount = coupon ? Math.round(subtotal * 0.1) : 0;
  const total = subtotal - discount;
  const p = fmtPrice(total, ccy);
  const fromName = query.from?.name || "Antalya Havalimanı (AYT)";
  const toName = query.to?.name || "Lara Bölgesi";

  return (
    <div className="summary">
      <div className="summary-vehicle">
        <div className="summary-vehicle-img">PLACEHOLDER<br/>{vehicle.img}</div>
        <div>
          <div className="summary-vehicle-cat">{vehicle.catLabel}</div>
          <div className="summary-vehicle-name">{vehicle.name}</div>
          <div style={{ fontSize: 12, opacity: .7 }}>{vehicle.pax} yolcu · {vehicle.bag} bagaj</div>
        </div>
      </div>
      <div className="summary-body">
        <div className="summary-trip">
          <div className="summary-trip-point">
            <div className="dot"></div>
            <div>
              <div style={{ fontSize: 11, fontFamily: "var(--font-mono)", color: "var(--gray-500)", textTransform: "uppercase", letterSpacing: ".08em" }}>Alış · {query.pickupDate || "12.05.2026"} · {query.pickupTime || "14:30"}</div>
              <div style={{ fontWeight: 600 }}>{fromName}</div>
            </div>
          </div>
          <div className="summary-trip-line"></div>
          <div className="summary-trip-point end">
            <div className="dot"></div>
            <div>
              <div style={{ fontSize: 11, fontFamily: "var(--font-mono)", color: "var(--gray-500)", textTransform: "uppercase", letterSpacing: ".08em" }}>Bırakış</div>
              <div style={{ fontWeight: 600 }}>{toName}</div>
            </div>
          </div>
        </div>

        <div className="summary-row"><span className="label">Araç ücreti</span><span className="val">{fmtPrice(base, ccy).symbol}{fmtPrice(base, ccy).value}</span></div>
        {extras.babySeat && <div className="summary-row"><span className="label">Bebek koltuğu</span><span className="val">{fmtPrice(150, ccy).symbol}{fmtPrice(150, ccy).value}</span></div>}
        {extras.greet && <div className="summary-row"><span className="label">Karşılama tabelası</span><span className="val">{fmtPrice(200, ccy).symbol}{fmtPrice(200, ccy).value}</span></div>}
        {extras.water && <div className="summary-row"><span className="label">Su & atıştırmalık</span><span className="val">{fmtPrice(80, ccy).symbol}{fmtPrice(80, ccy).value}</span></div>}
        {coupon && <div className="summary-row" style={{ color: "var(--red)" }}><span className="label">Kupon ({coupon})</span><span className="val">−{fmtPrice(discount, ccy).symbol}{fmtPrice(discount, ccy).value}</span></div>}

        <div className="summary-divider"></div>
        <div className="summary-total">
          <div>
            <div className="label">Toplam ödeme</div>
            <div style={{ fontSize: 11, color: "var(--gray-500)", fontFamily: "var(--font-mono)", textTransform: "uppercase", letterSpacing: ".08em" }}>· KDV dahil</div>
          </div>
          <div className="val"><span className="currency">{p.symbol}</span>{p.value}</div>
        </div>

        <div style={{ background: "rgba(22,163,74,.06)", border: "1px solid rgba(22,163,74,.2)", borderRadius: 10, padding: 12, marginTop: 18, fontSize: 12.5, color: "#15803D" }}>
          <Icon name="check" size={14} style={{ verticalAlign: "middle", marginRight: 6 }}/>
          <b>Ücretsiz iptal</b> · Yolculuktan 24 saat öncesine kadar
        </div>
      </div>
    </div>
  );
};

const BookingPage = ({ lang, ccy, query, vehicle, onContinue, onBack }) => {
  const [contact, setContact] = React.useState({
    title: "Mr", firstName: "", lastName: "", email: "", phone: "+90 ",
    flightNo: "", hotelName: "", note: ""
  });
  const [extras, setExtras] = React.useState({ babySeat: false, greet: false, water: false });
  const [coupon, setCoupon] = React.useState("");
  const [appliedCoupon, setAppliedCoupon] = React.useState(null);
  const [couponMsg, setCouponMsg] = React.useState(null);
  const [submitting, setSubmitting] = React.useState(false);
  const [submitError, setSubmitError] = React.useState(null);

  const set = (k, v) => setContact(c => ({ ...c, [k]: v }));
  const toggle = k => setExtras(e => ({ ...e, [k]: !e[k] }));

  const applyCoupon = async () => {
    if (!coupon) return;
    try {
      const data = await engApi.get(`/api/coupon/validate?code=${encodeURIComponent(coupon)}&subtotal=${vehicle?.priceTry || 0}`);
      if (data.isValid) {
        setAppliedCoupon(coupon.toUpperCase());
        setCouponMsg(`%${data.discountPercent} indirim uygulandı — ${data.message}`);
      } else {
        setCouponMsg(data.message);
        setAppliedCoupon(null);
      }
    } catch {
      setAppliedCoupon(coupon.toUpperCase()); // API yoksa optimistik kabul et
      setCouponMsg("%10 indirim uygulandı");
    }
  };

  const handleContinue = async () => {
    if (!contact.firstName || !contact.lastName || !contact.email || !contact.phone) {
      setSubmitError("Lütfen zorunlu alanları doldurun (Ad, Soyad, E-posta, Telefon).");
      return;
    }
    setSubmitting(true);
    setSubmitError(null);
    try {
      const tripTypeMap = { oneway: 0, round: 1, hourly: 2 };
      const body = {
        tripType: tripTypeMap[query.trip] ?? 0,
        fromLocationId: query.from?.apiId || query.from?.id,
        toLocationId: query.to?.apiId || query.to?.id,
        pickupDate: query.pickupDate,
        pickupTime: (query.pickupTime || "14:30") + ":00",
        returnDate: query.returnDate || null,
        returnTime: query.returnTime ? query.returnTime + ":00" : null,
        adultCount: query.adults || 1,
        childCount: query.children || 0,
        vehicleId: vehicle?.apiId || vehicle?.id,
        contactTitle: contact.title,
        contactFirstName: contact.firstName,
        contactLastName: contact.lastName,
        contactEmail: contact.email,
        contactPhone: contact.phone,
        flightNumber: contact.flightNo || null,
        hotelName: contact.hotelName || null,
        notes: contact.note || null,
        couponCode: appliedCoupon || null,
        extraIds: []
      };
      const result = await engApi.post("/api/reservation", body);
      onContinue(result); // { id, referenceCode } → page-payment'a ilet
    } catch (err) {
      // API yoksa devam et (prototip modu)
      onContinue({ id: null, referenceCode: null });
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div className="page-section">
      <div className="booking-layout">
        <div>
          <button className="btn btn-ghost" style={{ marginBottom: 16 }} onClick={onBack}>
            <Icon name="arrowLeft" size={14}/> Araç seçimine dön
          </button>
          <StepsBar step={2}/>

          <div className="booking-card">
            <h2>İletişim Bilgileri</h2>
            <p className="sub">Şoförümüz ve yolculuk bilgileri için iletişim bilgilerinizi giriniz.</p>
            <div className="form-grid">
              <div className="form-field">
                <label>Hitap</label>
                <select value={contact.title} onChange={e => set("title", e.target.value)}>
                  <option>Mr</option><option>Mrs</option><option>Ms</option>
                </select>
              </div>
              <div className="form-field">
                <label>Telefon Numarası *</label>
                <input value={contact.phone} onChange={e => set("phone", e.target.value)} placeholder="+90 5XX XXX XX XX"/>
                <span className="hint">WhatsApp kullanılabilir bir numara öneririz</span>
              </div>
              <div className="form-field">
                <label>Ad *</label>
                <input value={contact.firstName} onChange={e => set("firstName", e.target.value)} placeholder="Mehmet"/>
              </div>
              <div className="form-field">
                <label>Soyad *</label>
                <input value={contact.lastName} onChange={e => set("lastName", e.target.value)} placeholder="Yılmaz"/>
              </div>
              <div className="form-field span-2">
                <label>E-posta *</label>
                <input type="email" value={contact.email} onChange={e => set("email", e.target.value)} placeholder="ornek@email.com"/>
                <span className="hint">Rezervasyon onayı bu adrese gönderilecek</span>
              </div>
            </div>
          </div>

          <div className="booking-card">
            <h2>Yolculuk Detayları</h2>
            <p className="sub">Şoförümüzün sizi rahatlıkla bulabilmesi için bu bilgiler önemli.</p>
            <div className="form-grid">
              <div className="form-field">
                <label>Uçuş Numarası</label>
                <input value={contact.flightNo} onChange={e => set("flightNo", e.target.value)} placeholder="TK 2422"/>
                <span className="hint">Uçuşunuzu otomatik takip ederiz</span>
              </div>
              <div className="form-field">
                <label>Otel / Adres Adı</label>
                <input value={contact.hotelName} onChange={e => set("hotelName", e.target.value)} placeholder="Maxx Royal Belek"/>
              </div>
              <div className="form-field span-2">
                <label>Ek Notlar (opsiyonel)</label>
                <textarea rows="3" value={contact.note} onChange={e => set("note", e.target.value)} placeholder="Bagaj fazlalığı, özel istek vb."></textarea>
              </div>
            </div>
          </div>

          <div className="booking-card">
            <h2>Ek Hizmetler</h2>
            <p className="sub">Yolculuğunuzu kişiselleştirin.</p>
            <label className={"checkbox-row " + (extras.babySeat ? "checked" : "")}>
              <input type="checkbox" checked={extras.babySeat} onChange={() => toggle("babySeat")}/>
              <div>
                <div className="name"><Icon name="child" size={15} style={{ verticalAlign: "middle", marginRight: 6, color: "var(--blue)" }}/>Bebek / Çocuk Koltuğu</div>
                <div className="desc">0–6 yaş için ECE R44/04 sertifikalı koltuk</div>
              </div>
              <span className="price">+{fmtPrice(150, ccy).symbol}{fmtPrice(150, ccy).value}</span>
            </label>
            <label className={"checkbox-row " + (extras.greet ? "checked" : "")}>
              <input type="checkbox" checked={extras.greet} onChange={() => toggle("greet")}/>
              <div>
                <div className="name"><Icon name="sign" size={15} style={{ verticalAlign: "middle", marginRight: 6, color: "var(--blue)" }}/>Karşılama Tabelası</div>
                <div className="desc">Adınızın yazılı olduğu tabela ile gelişlerde karşılama</div>
              </div>
              <span className="price">+{fmtPrice(200, ccy).symbol}{fmtPrice(200, ccy).value}</span>
            </label>
            <label className={"checkbox-row " + (extras.water ? "checked" : "")}>
              <input type="checkbox" checked={extras.water} onChange={() => toggle("water")}/>
              <div>
                <div className="name"><Icon name="sparkle" size={15} style={{ verticalAlign: "middle", marginRight: 6, color: "var(--blue)" }}/>Su & Atıştırmalık İkramı</div>
                <div className="desc">Soğuk su ve hafif atıştırmalık paketi</div>
              </div>
              <span className="price">+{fmtPrice(80, ccy).symbol}{fmtPrice(80, ccy).value}</span>
            </label>
          </div>

          <div className="booking-card">
            <h2>Kupon Kodu</h2>
            <p className="sub">İndirim kodunuz varsa buraya girebilirsiniz.</p>
            <div style={{ display: "flex", gap: 10 }}>
              <input className="form-field" style={{ flex: 1, padding: "12px 14px", border: "1px solid var(--gray-200)", borderRadius: 10 }}
                     placeholder="Kupon kodu" value={coupon} onChange={e => setCoupon(e.target.value)}/>
              <button className="btn btn-secondary" onClick={applyCoupon}>Uygula</button>
            </div>
            {couponMsg && (
              <div style={{ marginTop: 12, padding: 12, background: appliedCoupon ? "rgba(22,163,74,.06)" : "rgba(220,38,38,.06)", border: `1px solid ${appliedCoupon ? "rgba(22,163,74,.2)" : "rgba(220,38,38,.2)"}`, borderRadius: 10, fontSize: 13, color: appliedCoupon ? "#16A34A" : "#B91C1C" }}>
                <Icon name={appliedCoupon ? "check" : "info"} size={14} style={{ verticalAlign: "middle", marginRight: 6 }}/>
                {couponMsg}
              </div>
            )}
          </div>

          {submitError && (
            <div style={{ padding: 12, background: "rgba(220,38,38,.06)", border: "1px solid rgba(220,38,38,.2)", borderRadius: 10, fontSize: 13, color: "#B91C1C", marginBottom: 8 }}>
              {submitError}
            </div>
          )}
          <div style={{ display: "flex", gap: 12, justifyContent: "flex-end" }}>
            <button className="btn btn-ghost" onClick={onBack}>Geri</button>
            <button className="btn btn-primary btn-lg" onClick={handleContinue} disabled={submitting} style={{ opacity: submitting ? .7 : 1 }}>
              {submitting ? "Kaydediliyor..." : <>Ödemeye Geç <Icon name="arrowRight" size={16}/></>}
            </button>
          </div>
        </div>

        <BookingSummary vehicle={vehicle} query={query} ccy={ccy} extras={extras} coupon={appliedCoupon}/>
      </div>
    </div>
  );
};

window.BookingPage = BookingPage;
window.BookingSummary = BookingSummary;
window.StepsBar = StepsBar;
