/* global React, Icon, VehicleCard, CV_INVENTORY, CV_FACTS */
const { useState, useEffect, useMemo, useRef } = React;

// ─────────────────────────────────────────────────────────────────────────────
// VEHICLE DETAIL  — the hero deliverable
// ─────────────────────────────────────────────────────────────────────────────
function VehiclePage({ v, setPage, openVehicle }) {
  const gallery = useMemo(() => {
    return [v.image, v.detail, v.interiorShot, v.mirror].filter(Boolean);
  }, [v]);

  const [active, setActive] = useState(0);
  const [tab, setTab] = useState("enquire");
  const [submitted, setSubmitted] = useState(false);
  const [form, setForm] = useState({
    intent: "enquire",
    name: "", phone: "", email: "",
    message: `Hi CV Auto, I'm interested in the ${v.year} ${v.make} ${v.model}. Please share asking price and availability for a viewing.`
  });

  useEffect(() => { setActive(0); setSubmitted(false); }, [v.id]);

  const onSubmit = e => {
    e.preventDefault();
    setSubmitted(true);
  };

  const similar = CV_INVENTORY
    .filter(x => x.id !== v.id && (x.tag === v.tag || x.body === v.body))
    .slice(0, 4);

  const specs = [
    ["Year", v.year],
    ["Make", v.make],
    ["Model", v.model],
    ["Body", v.body],
    ["Drivetrain", v.drivetrain],
    ["Transmission", v.transmission],
    ["Exterior", v.exterior],
    ["Interior", v.interior],
    ["Mileage", v.mileage ?? "On request"],
    ["Stock ID", `CV-${v.id.toUpperCase().slice(0, 12)}`]
  ];

  return (
    <main data-screen-label="Vehicle Detail" className="cv-detail">
      {/* Top breadcrumb */}
      <div className="cv-detail-crumbs">
        <div className="cv-container">
          <button onClick={() => setPage({ name: "home" })}>Home</button>
          <span>›</span>
          <button onClick={() => setPage({ name: "inventory" })}>Inventory</button>
          <span>›</span>
          <span className="cv-crumbs-current">{v.year} {v.make} {v.model}</span>
        </div>
      </div>

      {/* Cinematic full-bleed gallery */}
      <section className="cv-vehicle-stage">
        <div className="cv-stage-main">
          <img key={gallery[active]} src={gallery[active]} alt={`${v.year} ${v.make} ${v.model}`} />
          <button
            className="cv-stage-nav cv-stage-nav-prev"
            onClick={() => setActive((active - 1 + gallery.length) % gallery.length)}
            aria-label="Previous frame"
          >
            <Icon.chev style={{ transform: "rotate(90deg)" }} />
          </button>
          <button
            className="cv-stage-nav cv-stage-nav-next"
            onClick={() => setActive((active + 1) % gallery.length)}
            aria-label="Next frame"
          >
            <Icon.chev style={{ transform: "rotate(-90deg)" }} />
          </button>
          <div className="cv-stage-counter">
            {String(active + 1).padStart(2, "0")} / {String(gallery.length).padStart(2, "0")}
          </div>
        </div>

        <div className="cv-stage-strip">
          {gallery.map((src, i) => (
            <button
              key={i}
              className={`cv-stage-thumb ${i === active ? "is-on" : ""}`}
              onClick={() => setActive(i)}
            >
              <img src={src} alt="" />
            </button>
          ))}
          {/* placeholder slots for client to supply more hi-res frames */}
          {Array.from({ length: Math.max(0, 6 - gallery.length) }).map((_, i) => (
            <div key={`p${i}`} className="cv-stage-thumb cv-stage-thumb-empty">
              <span>+ frame</span>
            </div>
          ))}
        </div>
      </section>

      {/* Headline + price + key actions */}
      <section className="cv-vehicle-meta">
        <div className="cv-container cv-vehicle-meta-grid">
          <div className="cv-vehicle-meta-l">
            <div className="cv-eyebrow">
              {v.tag} · Stock CV-{v.id.toUpperCase().slice(0, 12)}
              {v.badge && <span className="cv-pill cv-pill-accent" style={{ marginLeft: 12 }}>{v.badge}</span>}
            </div>
            <h1 className="cv-h1">
              {v.year} {v.make} <em className="cv-italic">{v.model}</em>
            </h1>
            <p className="cv-detail-headline">{v.headline}</p>
          </div>

          <div className="cv-vehicle-meta-r">
            <div className="cv-price-label">Price</div>
            <div className="cv-price-value">
              {v.price === "POA" ? <em>Price on application</em> : v.price}
            </div>
            <div className="cv-price-fine">
              Asking figures shared on enquiry. Excludes registration &amp; transfer fees.
            </div>
            <div className="cv-meta-cta">
              <button className="cv-btn cv-btn-primary cv-btn-full" onClick={() => setTab("enquire")}>
                Request the price <Icon.arrow />
              </button>
              <div className="cv-meta-cta-row">
                <a className="cv-btn cv-btn-ghost" href={CV_FACTS.whatsapp} target="_blank" rel="noopener">
                  <Icon.wa /> WhatsApp
                </a>
                <a className="cv-btn cv-btn-ghost" href={`tel:${CV_FACTS.phone.replace(/\s/g,"")}`}>
                  <Icon.phone /> Call
                </a>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* Body: spec table + actions panel */}
      <section className="cv-vehicle-body">
        <div className="cv-container cv-vehicle-body-grid">
          {/* Left — spec, story, what's covered */}
          <div className="cv-vehicle-left">
            <h3 className="cv-h3">Specification</h3>
            <table className="cv-spec">
              <tbody>
                {specs.map(([k, val]) => (
                  <tr key={k}>
                    <th>{k}</th>
                    <td>{val}</td>
                  </tr>
                ))}
              </tbody>
            </table>
            <div className="cv-spec-note">
              Spec fields populate from the vehicle feed; only verified fields are rendered.
              Anything not published by the showroom stays "On request" rather than guessed.
            </div>

            <h3 className="cv-h3" style={{ marginTop: 56 }}>Concierge notes</h3>
            <ul className="cv-notes">
              <li>
                <strong>Pre-purchase inspection.</strong> Independent inspection booked on request,
                including paint, panel and mechanical report.
              </li>
              <li>
                <strong>GCC handover.</strong> Registration, transfer and export paperwork handled
                in-house. Re-export packages available for GCC and CIS buyers.
              </li>
              <li>
                <strong>Finance &amp; insurance support.</strong> CV Auto introduces buyers to
                preferred partners. No rates are published — enquiry-based only.
              </li>
              <li>
                <strong>Trade-in.</strong> Bring your current car for a same-day desk offer; can be
                set against the asking figure on this vehicle.
              </li>
            </ul>
          </div>

          {/* Right — interactive enquiry tabs */}
          <aside className="cv-vehicle-right">
            <div className="cv-enquire">
              <div className="cv-enquire-tabs">
                {[
                  ["enquire", "Enquire"],
                  ["view", "Book viewing"],
                  ["trade", "Trade-in"],
                  ["finance", "Finance"]
                ].map(([k, label]) => (
                  <button
                    key={k}
                    className={tab === k ? "is-on" : ""}
                    onClick={() => { setTab(k); setSubmitted(false); }}
                  >{label}</button>
                ))}
              </div>

              {submitted ? (
                <div className="cv-enquire-success">
                  <div className="cv-tick cv-tick-lg" />
                  <h4>Enquiry received.</h4>
                  <p>
                    A desk advisor will reply within business hours, prefilled with the
                    {" "}{v.year} {v.make} {v.model} reference. For an immediate response, message
                    the showroom on WhatsApp.
                  </p>
                  <a className="cv-btn cv-btn-primary" href={CV_FACTS.whatsapp} target="_blank" rel="noopener">
                    <Icon.wa /> Open WhatsApp now
                  </a>
                </div>
              ) : (
                <form className="cv-enquire-form" onSubmit={onSubmit}>
                  <div className="cv-enquire-h">
                    {tab === "enquire" && "Request price & details"}
                    {tab === "view" && "Book a private viewing"}
                    {tab === "trade" && "Set my car against this one"}
                    {tab === "finance" && "Finance this car"}
                  </div>
                  <div className="cv-enquire-fine">
                    Pre-filled for the <strong>{v.year} {v.make} {v.model}</strong> · CV-{v.id.toUpperCase().slice(0, 12)}
                  </div>

                  <div className="cv-field">
                    <label>Full name</label>
                    <input required value={form.name} onChange={e => setForm({...form, name: e.target.value})} />
                  </div>
                  <div className="cv-field-row">
                    <div className="cv-field">
                      <label>Phone</label>
                      <input required value={form.phone} onChange={e => setForm({...form, phone: e.target.value})} placeholder="+971…" />
                    </div>
                    <div className="cv-field">
                      <label>Email</label>
                      <input type="email" required value={form.email} onChange={e => setForm({...form, email: e.target.value})} />
                    </div>
                  </div>

                  {tab === "view" && (
                    <div className="cv-field-row">
                      <div className="cv-field">
                        <label>Preferred date</label>
                        <input type="date" />
                      </div>
                      <div className="cv-field">
                        <label>Time</label>
                        <select>
                          <option>10:00 – 12:00</option>
                          <option>12:00 – 14:00</option>
                          <option>14:00 – 17:00</option>
                          <option>17:00 – 21:00</option>
                        </select>
                      </div>
                    </div>
                  )}

                  {tab === "trade" && (
                    <div className="cv-field-row">
                      <div className="cv-field">
                        <label>Your car — make/model</label>
                        <input placeholder="e.g. Porsche 911 Turbo" />
                      </div>
                      <div className="cv-field">
                        <label>Year</label>
                        <input placeholder="2021" />
                      </div>
                    </div>
                  )}

                  {tab === "finance" && (
                    <div className="cv-field-row">
                      <div className="cv-field">
                        <label>Down payment</label>
                        <input placeholder="AED" />
                      </div>
                      <div className="cv-field">
                        <label>Term</label>
                        <select>
                          <option>24 months</option>
                          <option>36 months</option>
                          <option>48 months</option>
                          <option>60 months</option>
                        </select>
                      </div>
                    </div>
                  )}

                  <div className="cv-field">
                    <label>Message</label>
                    <textarea rows="3" value={form.message} onChange={e => setForm({...form, message: e.target.value})} />
                  </div>

                  <div className="cv-checks">
                    <label><input type="checkbox" defaultChecked /> Send to my WhatsApp too</label>
                    <label><input type="checkbox" /> Subscribe to the arrivals list</label>
                  </div>

                  <button type="submit" className="cv-btn cv-btn-primary cv-btn-full">
                    Send enquiry <Icon.arrow />
                  </button>
                  <div className="cv-enquire-fine cv-enquire-fine-c">
                    By submitting you agree to be contacted about this enquiry. We never sell your data.
                  </div>
                </form>
              )}
            </div>

            <div className="cv-side-card">
              <div className="cv-side-h">Visit the car</div>
              <p>
                {CV_FACTS.address}.<br />
                Showroom hours Mon–Sat 10:00–21:00, Sunday 12:00–18:00.
              </p>
              <button className="cv-link" onClick={() => setPage({ name: "contact" })}>
                Directions & map <Icon.arrow />
              </button>
            </div>
          </aside>
        </div>
      </section>

      {/* Similar cars */}
      {similar.length > 0 && (
        <section className="cv-band cv-band-noir">
          <div className="cv-container">
            <header className="cv-section-head">
              <div>
                <div className="cv-eyebrow">In the same vein</div>
                <h2 className="cv-h2">Other cars on the floor.</h2>
              </div>
              <button className="cv-link" onClick={() => setPage({ name: "inventory" })}>
                All inventory <Icon.arrow />
              </button>
            </header>
            <div className="cv-card-grid">
              {similar.map(s => <VehicleCard key={s.id} v={s} onOpen={openVehicle} />)}
            </div>
          </div>
        </section>
      )}
    </main>
  );
}

window.VehiclePage = VehiclePage;
