// vehicle.jsx — Vehicle Detail page + booking widget

function VehicleDetail({ car, t, locale, onBack, onOpenCar }) {
  const [tab, setTab] = React.useState("specs");
  const [gIdx, setGIdx] = React.useState(0);
  // Demo: we have 1 image per car. Fake a small gallery using the same image with different crops/zooms.
  const galleryImgs = [car.image, car.image, car.image, car.image];

  const similar = window.FLEET.filter(c => c.id !== car.id && c.available).slice(0, 3);

  return (
    <div className="veh">
      <div className="veh-crumbs">
        <button className="link-arrow link-back" onClick={onBack}>
          <Icon.Arrow size={12} dir="left" /> <span>{t.detail.back}</span>
        </button>
        <span className="crumbs">
          <span className="dim">Fleet</span>
          <span className="crumb-sep">/</span>
          <span className="dim">{car.body.split("·")[0].trim()}</span>
          <span className="crumb-sep">/</span>
          <span>{car.make} {car.model}</span>
        </span>
      </div>

      <header className="veh-head">
        <div>
          <div className="veh-year">{car.year}</div>
          <h1 className="veh-h">
            <span>{car.make}</span>
            <span className="hl-italic"> {car.model}</span>
          </h1>
          <div className="veh-sub">
            <span>{car.body}</span>
            <span className="crumb-sep">·</span>
            <span>{car.colour}</span>
            <span className="crumb-sep">·</span>
            <span>{car.seats}-seat</span>
          </div>
        </div>
        <div className="veh-quick">
          <div><span className="hf-k">Power</span><span className="hf-v">{car.power}</span></div>
          <div><span className="hf-k">0–100</span><span className="hf-v">{car.accel}</span></div>
          <div><span className="hf-k">Top</span><span className="hf-v">{car.topSpeed}</span></div>
          <div className="veh-rate"><span className="hf-k">{t.fleet.from}</span><span className="hf-v">{car.daily}<small>/{t.fleet.day}</small></span></div>
        </div>
      </header>

      <div className="veh-grid">
        {/* Left: media + content */}
        <div className="veh-main">
          <div className="gallery">
            <div className="gallery-main">
              <img src={galleryImgs[gIdx]} alt={`${car.make} ${car.model}`} style={{ transform: gIdx === 0 ? "none" : gIdx === 1 ? "scale(1.4) translate(-10%, 0)" : gIdx === 2 ? "scale(1.6) translate(15%, 5%)" : "scale(1.3) translate(0, -8%)" }} />
              <div className="gallery-cap">
                <span className="kicker-dot live" />
                <span>{car.colour}</span>
                <span className="dim">· frame {gIdx + 1} / {galleryImgs.length}</span>
              </div>
              <button className="gallery-arr gallery-arr-l" onClick={() => setGIdx((gIdx - 1 + galleryImgs.length) % galleryImgs.length)}>
                <Icon.Arrow size={16} dir="left" />
              </button>
              <button className="gallery-arr gallery-arr-r" onClick={() => setGIdx((gIdx + 1) % galleryImgs.length)}>
                <Icon.Arrow size={16} />
              </button>
            </div>
            <div className="gallery-thumbs">
              {galleryImgs.map((src, i) => (
                <button key={i} className={`thumb ${i === gIdx ? "thumb-on" : ""}`} onClick={() => setGIdx(i)}>
                  <img src={src} alt="" />
                </button>
              ))}
            </div>
          </div>

          <div className="veh-tabs">
            <div className="veh-tabs-row">
              <button className={`tab ${tab === "specs" ? "tab-on" : ""}`} onClick={() => setTab("specs")}>{t.detail.specs}</button>
              <button className={`tab ${tab === "incl" ? "tab-on" : ""}`} onClick={() => setTab("incl")}>{t.detail.included}</button>
              <button className={`tab ${tab === "rate" ? "tab-on" : ""}`} onClick={() => setTab("rate")}>{t.detail.rate}</button>
            </div>

            {tab === "specs" && (
              <div className="veh-specs">
                {[
                  ["Body", car.body],
                  ["Seats", car.seats],
                  ["Transmission", car.transmission],
                  ["Drivetrain", car.drivetrain],
                  ["Engine", car.engine],
                  ["Power", car.power],
                  ["Torque", car.torque],
                  ["Top speed", car.topSpeed],
                  ["0–100 km/h", car.accel],
                  [t.detail.colour, car.colour],
                ].map(([k, v], i) => (
                  <div key={i} className="spec-row">
                    <span className="spec-k">{k}</span>
                    <span className="spec-dots" />
                    <span className="spec-v">{v}</span>
                  </div>
                ))}
                {car.note && <p className="veh-note">{car.note}</p>}
              </div>
            )}

            {tab === "incl" && (
              <div className="veh-incl">
                <div>
                  <h4>{t.detail.included}</h4>
                  <ul>
                    {t.detail.included_items.map((x, i) => (
                      <li key={i}><Icon.Check size={12} /><span>{x}</span></li>
                    ))}
                  </ul>
                </div>
                <div>
                  <h4>{t.detail.not_included}</h4>
                  <ul className="ul-dim">
                    {t.detail.not_included_items.map((x, i) => (
                      <li key={i}><Icon.Close size={12} /><span>{x}</span></li>
                    ))}
                  </ul>
                </div>
              </div>
            )}

            {tab === "rate" && (
              <div className="veh-rates">
                <div className="rate-card">
                  <span className="rate-k">Daily</span>
                  <span className="rate-v">{car.daily}</span>
                  <span className="rate-note">200 km / day</span>
                </div>
                <div className="rate-card">
                  <span className="rate-k">Weekly</span>
                  <span className="rate-v">{car.weekly}</span>
                  <span className="rate-note">1,500 km / wk</span>
                </div>
                <div className="rate-card">
                  <span className="rate-k">Monthly</span>
                  <span className="rate-v">{car.monthly}</span>
                  <span className="rate-note">{t.fleet.enquire}</span>
                </div>
                <p className="veh-note">{t.detail.rate_note}</p>
              </div>
            )}
          </div>
        </div>

        {/* Right: sticky booking widget */}
        <aside className="veh-side">
          <BookingWidget car={car} t={t} locale={locale} />
        </aside>
      </div>

      {/* Similar */}
      <section className="veh-similar">
        <div className="services-head">
          <Kicker>{t.detail.similar}</Kicker>
          <h2 className="section-h">
            Also from the <span className="hl-italic">floor</span>
          </h2>
        </div>
        <div className="fleet-grid sim-grid">
          {similar.map((c, i) => (
            <CarCard key={c.id} car={c} t={t} onOpen={() => onOpenCar(c.id)} idx={i + 10} />
          ))}
        </div>
      </section>
    </div>
  );
}

// ──── Booking widget (inline, builds a WhatsApp deep link) ─────────────────
function BookingWidget({ car, t, locale }) {
  const today = new Date();
  const fmt = (d) => d.toISOString().slice(0, 10);
  const defaultPickup = fmt(new Date(today.getTime() + 86400000));
  const defaultReturn = fmt(new Date(today.getTime() + 4 * 86400000));

  const [pickup, setPickup] = React.useState(defaultPickup);
  const [ret, setRet] = React.useState(defaultReturn);
  const [delivery, setDelivery] = React.useState("dubai");
  const [chauffeur, setChauffeur] = React.useState(false);
  const [name, setName] = React.useState("");
  const [phone, setPhone] = React.useState("");
  const [open, setOpen] = React.useState(false);

  const days = Math.max(1, Math.round((new Date(ret) - new Date(pickup)) / 86400000));
  const dailyNum = parseInt(car.daily.replace(/[^\d]/g, ""), 10) || 0;
  const subtotal = dailyNum * days;
  const chauffeurFee = chauffeur ? 350 * days : 0;
  const total = subtotal + chauffeurFee;
  const totalStr = "AED " + total.toLocaleString();

  const deliveryLabel = t.booking.delivery_opts.find(o => o.id === delivery)?.label || "";

  const message = [
    `Hi Paddock,`,
    ``,
    `I'd like to book the ${car.year} ${car.make} ${car.model}.`,
    `• Pick-up: ${pickup}`,
    `• Return: ${ret}  (${days} day${days > 1 ? "s" : ""})`,
    `• Hand-over: ${deliveryLabel}`,
    chauffeur ? `• Chauffeur: yes` : null,
    name ? `• Name: ${name}` : null,
    phone ? `• My number: ${phone}` : null,
  ].filter(Boolean).join("\n");

  const waHref = `https://wa.me/971545265555?text=${encodeURIComponent(message)}`;

  return (
    <div className="book">
      <div className="book-head">
        <Kicker>{t.booking.title}</Kicker>
        <div className="book-rate">
          <span className="rate-v">{car.daily}</span>
          <span className="dim">/ {t.fleet.day}</span>
        </div>
      </div>

      <div className="book-dates">
        <label>
          <span className="book-lbl">{t.booking.pickup}</span>
          <input type="date" value={pickup} onChange={e => setPickup(e.target.value)} />
        </label>
        <label>
          <span className="book-lbl">{t.booking.return}</span>
          <input type="date" value={ret} min={pickup} onChange={e => setRet(e.target.value)} />
        </label>
      </div>

      <div className="book-field">
        <span className="book-lbl">{t.booking.delivery_label}</span>
        <div className="book-opts">
          {t.booking.delivery_opts.map(o => (
            <label key={o.id} className={`book-opt ${delivery === o.id ? "book-opt-on" : ""}`}>
              <input type="radio" name="delivery" checked={delivery === o.id} onChange={() => setDelivery(o.id)} />
              <span className="book-opt-label">{o.label}</span>
              <span className="book-opt-note">{o.note}</span>
            </label>
          ))}
        </div>
      </div>

      <label className={`book-chauffeur ${chauffeur ? "is-on" : ""}`}>
        <input type="checkbox" checked={chauffeur} onChange={e => setChauffeur(e.target.checked)} />
        <span className="book-chk"><Icon.Check size={11} /></span>
        <span className="book-chauffeur-text">
          <span className="book-chauffeur-title">{t.booking.chauffeur}</span>
          <span className="book-chauffeur-note">{t.booking.chauffeur_note}</span>
        </span>
        <span className="book-chauffeur-fee">+ AED 350/{t.fleet.day}</span>
      </label>

      <div className="book-totals">
        <div className="bt-row"><span>{car.daily} × {days} {days > 1 ? "days" : "day"}</span><span>AED {subtotal.toLocaleString()}</span></div>
        {chauffeur && <div className="bt-row dim"><span>Chauffeur × {days}</span><span>AED {chauffeurFee.toLocaleString()}</span></div>}
        <div className="bt-row bt-row-total"><span>{t.booking.total_label}</span><span>{totalStr}</span></div>
        <div className="bt-note">{t.booking.total_note}</div>
      </div>

      <div className="book-id">
        <input className="book-input" placeholder={t.booking.name} value={name} onChange={e => setName(e.target.value)} />
        <input className="book-input" placeholder={t.booking.phone} value={phone} onChange={e => setPhone(e.target.value)} />
      </div>

      <button className="book-preview-toggle" onClick={() => setOpen(o => !o)}>
        <Icon.ChevDown size={10} />
        <span>{t.booking.preview_label}</span>
      </button>
      {open && (
        <pre className="book-preview">{message}</pre>
      )}

      <a className="btn btn-solid btn-wa" href={waHref} target="_blank" rel="noopener">
        <Icon.Whatsapp size={16} />
        <span>{t.booking.open_whatsapp}</span>
        <Icon.Arrow size={12} />
      </a>
      <a className="book-call" href="tel:+971545265555">{t.booking.or_call}</a>
      <p className="book-privacy">{t.booking.privacy}</p>
    </div>
  );
}

Object.assign(window, { VehicleDetail, BookingWidget });
