const { Button, Input, Select, Card, Icon, Badge, Checkbox } = window.FriendsCarsDesignSystem_f69f0e;

const STEP_LABELS = ["Car", "Dates", "Details", "Confirm"];

function Field({ error, children }) {
  return (
    <div className="fc-field" data-err={error ? "1" : "0"}>
      {children}
      {error ? <span className="fc-err"><Icon name="alert-circle" size={13} /> {error}</span> : null}
    </div>
  );
}

function Row({ label, note, value, tone }) {
  return (
    <div className="fc-sum" data-tone={tone || ""}>
      <span><strong>{label}</strong>{note ? <em>{note}</em> : null}</span>
      <span className="fc-sum-val">{value}</span>
    </div>
  );
}

function BookingScreen({ car, onOpen, onNavigate }) {
  const today = new Date().toISOString().slice(0, 10);
  const [step, setStep] = React.useState(car ? 1 : 0);
  const [sent, setSent] = React.useState(false);
  const [touched, setTouched] = React.useState(false);
  const [pick, setPick] = React.useState(car || null);
  const [from, setFrom] = React.useState(today);
  const [to, setTo] = React.useState(today);
  const [t1, setT1] = React.useState("10:00");
  const [t2, setT2] = React.useState("10:00");
  const [name, setName] = React.useState("");
  const [phone, setPhone] = React.useState("");
  const [dest, setDest] = React.useState("");
  const [self, setSelf] = React.useState(true);
  const [wa, setWa] = React.useState(true);
  const [delivery, setDelivery] = React.useState("doorstep");
  const [loc, setLoc] = React.useState("");
  const [kms, setKms] = React.useState("");

  const collect = delivery === "yard";
  const q = window.quote(pick, from, t1, to, t2, kms, collect);
  const handover = collect ? "Collecting from us" : delivery === "airport" ? "Airport terminal" : "Doorstep in " + window.BIZ.city;

  /* Inline validation — no alerts. Errors only surface once a step has been attempted. */
  const errs = {};
  if (!pick) errs.car = "Choose a car to continue.";
  if (!from) errs.from = "Pickup date is required.";
  if (!t1) errs.t1 = "Pickup time is required.";
  if (!to) errs.to = "Return date is required.";
  if (!t2) errs.t2 = "Return time is required.";
  if (from && to && t1 && t2 && !window.durationHours(from, t1, to, t2)) errs.to = "Return must be after pickup.";
  if (!name.trim()) errs.name = "We need a name for the booking.";
  else if (name.trim().length < 3) errs.name = "Please enter your full name.";
  const digits = phone.replace(/\D/g, "");
  if (!digits) errs.phone = "A mobile number is required.";
  else if (digits.length < 10) errs.phone = "Enter a 10-digit mobile number.";
  if (!dest.trim()) errs.dest = "Tell us where the car is going.";

  const stepErrs = [["car"], ["from", "t1", "to", "t2"], ["name", "phone", "dest"], []][step] || [];
  const blocked = stepErrs.filter((k) => errs[k]);
  const show = (k) => (touched && stepErrs.indexOf(k) > -1 ? errs[k] : null);

  const message = () => [
    "Hello, I would like to book a car.",
    "",
    "Car: " + pick.name,
    "Pickup: " + window.prettyWhen(from, t1),
    "Return: " + window.prettyWhen(to, t2),
    "Duration: " + q.hours + (q.hours === 1 ? " hour" : " hours"),
    "Rental: " + window.rupees(q.rental) + " (" + window.rupees(q.rate) + " x " + q.days + (q.days === 1 ? " day" : " days") + ")",
    "Extra hours: " + q.extraHours,
    "Extra hour charge: " + window.rupees(q.extraCost),
    "Included KM: " + window.km(q.kmIncluded),
    "Pickup & Drop: " + (collect ? "Not required — collecting from you" : (loc.trim() || handover) + (kms ? " (" + kms + " KM)" : "")),
    "Pickup & Drop Charge: " + (q.pd.over ? "On request — beyond 20 KM" : q.pd.set ? window.rupees(q.pdCharge) : "Not applicable"),
    "Security Deposit: " + window.rupees(q.deposit) + " (refundable)",
    "Estimated Rental: " + window.rupees(q.estRental),
    "",
    "Name: " + name.trim(),
    "Mobile: " + phone.trim(),
    "Where are you going: " + dest.trim(),
    "",
    self ? "I am the person who will drive the car." : "Another named driver will drive the car.",
    wa ? "Please send the confirmation on WhatsApp." : "",
    "Please confirm availability and booking details."
  ].filter(Boolean).join("\n");

  const waLink = () => "https://wa.me/" + window.BIZ.waBook + "?text=" + encodeURIComponent(message());

  const advance = () => {
    if (blocked.length) { setTouched(true); return; }
    setTouched(false);
    setStep((s) => Math.min(3, s + 1));
  };
  const send = () => {
    const bad = ["car", "from", "t1", "to", "t2", "name", "phone", "dest"].filter((k) => errs[k]);
    if (bad.length) { setTouched(true); setStep(errs.car ? 0 : (errs.from || errs.t1 || errs.to || errs.t2) ? 1 : 2); return; }
    window.open(waLink(), "_blank", "noopener");
    setSent(true);
  };
  const back = () => { setTouched(false); setStep((s) => Math.max(0, s - 1)); };
  const goto = (n) => { if (n <= step) { setTouched(false); setStep(n); } };

  const extraNote = q.extraHours ? q.extraHours + (q.extraHours === 1 ? " hour" : " hours") + " × " + window.rupees(q.extraRate) : "";

  return (
    <window.Shell style={{ paddingTop: "calc(var(--navbar-h) + var(--space-12))" }}>
      <window.Heading eyebrow="Booking" title={sent ? "That is with us." : "Four short steps."}
        body={sent ? "" : "Nothing is charged here. Send the request on WhatsApp and we confirm availability on the phone."} />

      <ol className="fc-steps" data-reveal>
        {STEP_LABELS.map((s, i) => (
          <li key={s} data-on={i <= step ? "1" : "0"} data-done={i < step ? "1" : "0"}>
            <button onClick={() => goto(i)} disabled={i > step}>
              <span>{i < step ? <Icon name="check" size={14} /> : "0" + (i + 1)}</span>{s}
            </button>
          </li>
        ))}
      </ol>

      <div className="fc-booking">
        <div className="fc-booking-main">
          {step === 0 ? (
            <React.Fragment>
              {touched && errs.car ? <div className="fc-note" data-tone="err"><Icon name="alert-circle" size={15} /><span>{errs.car}</span></div> : null}
              <div className="fc-grid fc-grid-sm">
                {window.FLEET.map((c) => (
                  <button key={c.id} className="fc-pickcar" data-on={pick && pick.id === c.id ? "1" : "0"} onClick={() => { setPick(c); setTouched(false); setStep(1); }}>
                    <span className="fc-eyebrow">{c.marque}</span>
                    <strong>{c.name}</strong>
                    <span>{window.rupees(c.price)} / day · {c.seats} seats · {c.gearbox}</span>
                  </button>
                ))}
              </div>
            </React.Fragment>
          ) : null}

          {step === 1 ? (
            <Card variant="glass" padding="var(--space-8)" radius="var(--radius-hero)">
              <div className="fc-book-grid">
                <Field error={show("from")}><Input label="Pickup date" type="date" value={from} onChange={(e) => setFrom(e.target.value)} /></Field>
                <Field error={show("t1")}><Input label="Pickup time" type="time" value={t1} onChange={(e) => setT1(e.target.value)} /></Field>
                <Field error={show("to")}><Input label="Return date" type="date" min={from} value={to} onChange={(e) => setTo(e.target.value)} /></Field>
                <Field error={show("t2")}><Input label="Return time" type="time" value={t2} onChange={(e) => setT2(e.target.value)} /></Field>
              </div>
              <div className="fc-note" style={{ marginTop: "var(--space-6)" }}>
                <Icon name="clock" size={15} color="var(--accent)" />
                <span>{q.hours ? "That is " + window.prettyDuration(q) + ". Each rate covers a complete 24-hour period; extra hours are " + window.rupees(q.extraRate) + " each on this car." : "Set both dates and times to see the estimate."}</span>
              </div>
              <div style={{ marginTop: "var(--space-8)", display: "grid", gap: "var(--space-4)" }}>
                <div className="fc-book-grid">
                  <Select label="Handover" value={delivery} onChange={(e) => setDelivery(e.target.value)}
                    options={[{ value: "doorstep", label: "Doorstep in " + window.BIZ.city }, { value: "airport", label: "Airport terminal" }, { value: "yard", label: "Collect from us" }]} />
                  {collect ? null : <Input label="Pickup &amp; drop location" icon="map-pin" placeholder="Area or address" value={loc} onChange={(e) => setLoc(e.target.value)} />}
                  {collect ? null : <Input label="Distance from us (KM)" type="number" min="0" placeholder="e.g. 8" hint={window.PICKUP.help} value={kms} onChange={(e) => setKms(e.target.value)} />}
                </div>
                {q.pd.over ? <div className="fc-note"><Icon name="phone" size={15} color="var(--accent)" /><span>{window.PICKUP.beyond}</span></div> : null}
              </div>
            </Card>
          ) : null}

          {step === 2 ? (
            <Card variant="glass" padding="var(--space-8)" radius="var(--radius-hero)">
              <div className="fc-book-grid">
                <Field error={show("name")}><Input label="Your name" placeholder="As printed on your licence" value={name} onChange={(e) => setName(e.target.value)} /></Field>
                <Field error={show("phone")}><Input label="Mobile" type="tel" icon="phone" placeholder="10 digits" value={phone} onChange={(e) => setPhone(e.target.value)} /></Field>
              </div>
              <div style={{ marginTop: "var(--space-4)" }}>
                <Field error={show("dest")}>
                  <Input label="Where are you going?" icon="map-pin" placeholder="Tell us your destination or travel plan" hint="Goa · Lonavala · Mahabaleshwar · Mumbai · Pune · Jaipur" value={dest} onChange={(e) => setDest(e.target.value)} />
                </Field>
              </div>
              <div style={{ marginTop: "var(--space-8)", display: "grid", gap: "var(--space-3)" }}>
                <Checkbox label="I am the person who will drive the car" checked={self} onChange={(e) => setSelf(e.target.checked)} />
                <Checkbox label="Send the confirmation on WhatsApp" checked={wa} onChange={(e) => setWa(e.target.checked)} />
              </div>
            </Card>
          ) : null}

          {step === 3 && !sent ? (
            <Card variant="glass" padding="var(--space-8)" radius="var(--radius-hero)">
              <span className="fc-eyebrow">Review your booking</span>
              <div className="fc-review">
                <Row label="Car" value={pick ? pick.name : "—"} />
                <Row label="Pickup" value={window.prettyWhen(from, t1)} />
                <Row label="Return" value={window.prettyWhen(to, t2)} />
                <Row label="Total duration" value={q.hours + (q.hours === 1 ? " hour" : " hours")} />
                <Row label="Rental" note={window.rupees(q.rate) + " × " + q.days + (q.days === 1 ? " day" : " days")} value={window.rupees(q.rental)} />
                {q.extraHours ? <Row label="Extra hours" note={extraNote} value={window.rupees(q.extraCost)} /> : null}
                <Row label="Included distance" value={window.km(q.kmIncluded)} />
                <Row label="Pickup &amp; drop" note={collect ? "Not required" : (loc.trim() || handover) + (kms ? " · " + kms + " KM" : "")}
                  value={collect ? "—" : q.pd.over ? "On request" : q.pd.set ? window.rupees(q.pdCharge) : "—"} />
                <Row label="Estimated rental" value={window.rupees(q.estRental)} tone="total" />
                <Row label="Security deposit" note="Refundable" value={window.rupees(q.deposit)} />
                <Row label="Estimated amount" note="Rental plus refundable deposit" value={window.rupees(q.estAmount)} tone="grand" />
                <Row label="Driver" value={name.trim() + " · " + phone.trim()} />
                <Row label="Going to" value={dest.trim()} />
              </div>
              <p className="fc-fine">{window.BIZ.depositNote}</p>
              <div className="fc-send">
                <Button variant="floating" size="lg" fullWidth iconRight="arrow-right" onClick={send}>Send the request</Button>
                <span className="fc-fine">Opens WhatsApp with the details filled in. Nothing is sent until you press send there.</span>
              </div>
            </Card>
          ) : null}

          {sent ? (
            <Card variant="glass" padding="var(--space-12)" radius="var(--radius-hero)" glow style={{ display: "grid", gap: "var(--space-6)", justifyItems: "start" }}>
              <Badge tone="accent" icon="check">Request opened in WhatsApp</Badge>
              <h3 style={{ fontSize: "var(--fs-subsection)", letterSpacing: "var(--ls-title)", fontWeight: "var(--fw-semibold)", lineHeight: "var(--lh-title)" }}>
                {pick.name} — {window.prettyDuration(q)}, {window.rupees(q.estRental)} estimated.
              </h3>
              <p style={{ color: "var(--text-secondary)", maxWidth: "var(--measure-lead)" }}>
                Press send in WhatsApp and one of us will confirm on {phone.trim()} shortly. Deposit of {window.rupees(q.deposit)} is refundable and nothing has been charged here.
              </p>
              <div style={{ display: "flex", gap: "var(--space-3)", flexWrap: "wrap" }}>
                <Button variant="primary" iconRight="arrow-right" as="a" href={waLink()} target="_blank" rel="noopener">Open WhatsApp again</Button>
                <Button variant="secondary" iconLeft="phone" as="a" href={"tel:" + window.BIZ.tel2}>Call {window.BIZ.phone2}</Button>
                <Button variant="ghost" onClick={() => onNavigate("Fleet")}>Back to the fleet</Button>
              </div>
            </Card>
          ) : null}

          {!sent && step < 3 ? (
            <div className="fc-booking-nav">
              <Button variant="ghost" iconLeft="arrow-left" onClick={back} disabled={step === 0}>Back</Button>
              <Button variant="primary" size="lg" iconRight="arrow-right" onClick={advance}>{step === 2 ? "Review the booking" : "Continue"}</Button>
            </div>
          ) : null}
        </div>

        <aside className="fc-booking-side">
          <Card variant="glass" padding="var(--space-8)" radius="var(--radius-lg)" className="fc-summary" style={{ display: "grid", gap: "var(--space-6)" }}>
            <span className="fc-eyebrow">Your booking</span>
            {pick ? (
              <React.Fragment>
                <div style={{ display: "grid", gap: 4 }}>
                  <strong style={{ fontSize: "var(--fs-card-title)", fontWeight: "var(--fw-medium)", letterSpacing: "var(--ls-title)", lineHeight: "var(--lh-title)" }}>{pick.name}</strong>
                  <span style={{ color: "var(--text-muted)", fontSize: "var(--fs-small)" }}>{pick.fuel} · {pick.gearbox} · {pick.seats} seats</span>
                </div>
                {q.hours ? <Row label="Duration" note={window.prettyWhen(from, t1) + " → " + window.prettyWhen(to, t2)} value={q.hours + (q.hours === 1 ? " hour" : " hours")} /> : null}
                <Row label="Rental" note={window.rupees(q.rate) + " × " + q.days + (q.days === 1 ? " day" : " days")} value={window.rupees(q.rental)} />
                {q.extraHours ? <Row label="Extra hours" note={extraNote} value={window.rupees(q.extraCost)} /> : null}
                <Row label="Included distance" value={window.km(q.kmIncluded)} />
                {collect ? null : <Row label="Pickup &amp; drop" note={q.pd.set ? q.pd.label : "Add a distance to price it"} value={q.pd.over ? "On request" : q.pd.set ? window.rupees(q.pdCharge) : "—"} />}
                <Row label="Estimated rental" value={window.rupees(q.estRental)} tone="total" />
                <Row label="Security deposit" note="Refundable" value={window.rupees(q.deposit)} />
                <Row label="Estimated amount" value={window.rupees(q.estAmount)} tone="grand" />
                {q.pd.over ? <p className="fc-fine">{window.PICKUP.beyond}</p> : null}
                <p className="fc-fine">{window.BIZ.depositNote}</p>
                <Button variant="ghost" size="sm" iconLeft="arrow-left-right" onClick={() => { setSent(false); setStep(0); }}>Change the car</Button>
              </React.Fragment>
            ) : <p style={{ color: "var(--text-muted)", fontSize: "var(--fs-small)" }}>Pick a car to see the estimate.</p>}
          </Card>
        </aside>
      </div>
    </window.Shell>
  );
}
Object.assign(window, { BookingScreen });
