// Booking flow — vertical-rail layout, single focused canvas, sticky bottom summary.

function VerticalStepper({ step, onJump }) {
  const steps = [
    { name: "Service",  hint: "What's going" },
    { name: "Schedule", hint: "Day & window" },
    { name: "Address",  hint: "Where to go" },
    { name: "Review",   hint: "Confirm & book" },
  ];
  return (
    <nav className="bk2__rail">
      {steps.map((s, i) => {
        const state = i < step ? "done" : i === step ? "active" : "todo";
        return (
          <button key={s.name}
                  className={"bk2__rail-step is-" + state}
                  onClick={() => i < step && onJump(i)}
                  disabled={i > step}>
            <span className="bk2__rail-dot">
              {i < step ? (
                <svg viewBox="0 0 16 16" width="14" height="14" aria-hidden><path d="M3 8.5l3.2 3.2L13 5" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg>
              ) : (i + 1)}
            </span>
            <span className="bk2__rail-text">
              <span className="bk2__rail-name">{s.name}</span>
              <span className="bk2__rail-hint">{s.hint}</span>
            </span>
          </button>
        );
      })}
    </nav>
  );
}

function ItemPicker({ value, onChange }) {
  const options = window.TIERS;
  return (
    <div className="bk2__tiers">
      {options.map(t => {
        const on = value === t.id;
        return (
          <button key={t.id}
                  className={"bk2__tier" + (on ? " is-on" : "")}
                  onClick={() => onChange(t)}>
            <span className="bk2__tier-radio" aria-hidden>
              <span className="bk2__tier-radio-dot" />
            </span>
            <span className="bk2__tier-body">
              <span className="bk2__tier-name">{t.name}</span>
              <span className="bk2__tier-desc">{t.desc}</span>
            </span>
            <span className="bk2__tier-price">${t.price}</span>
          </button>
        );
      })}
    </div>
  );
}

function Scheduler({ day, windowId, onChange }) {
  const days = [
    { id: "mon", dow: "Mon", num: 4 }, { id: "tue", dow: "Tue", num: 5 },
    { id: "wed", dow: "Wed", num: 6 }, { id: "thu", dow: "Thu", num: 7 },
    { id: "fri", dow: "Fri", num: 8 }, { id: "sat", dow: "Sat", num: 9 },
    { id: "sun", dow: "Sun", num: 10 },
  ];
  const wins = [
    { id: "am",  time: "8 – 10 AM",   avail: "3 teams free" },
    { id: "mid", time: "10 AM – 12 PM", avail: "1 team free" },
    { id: "pm",  time: "1 – 3 PM",    avail: "4 teams free" },
  ];
  return (
    <div className="bk2__sched">
      <div className="bk2__sched-block">
        <div className="bk2__sched-label">Pick a day <span>· May 2026</span></div>
        <div className="bk2__days">
          {days.map(d => (
            <button key={d.id}
                    className={"bk2__day" + (day === d.id ? " is-on" : "")}
                    onClick={() => onChange({ day: d.id, dayLabel: `${d.dow}, May ${d.num}` })}>
              <span className="bk2__day-dow">{d.dow}</span>
              <span className="bk2__day-num">{d.num}</span>
            </button>
          ))}
        </div>
      </div>
      <div className="bk2__sched-block">
        <div className="bk2__sched-label">Arrival window</div>
        <div className="bk2__wins">
          {wins.map(w => (
            <button key={w.id}
                    className={"bk2__win" + (windowId === w.id ? " is-on" : "")}
                    onClick={() => onChange({ windowId: w.id, windowLabel: w.time })}>
              <span className="bk2__win-time">{w.time}</span>
              <span className="bk2__win-avail">{w.avail}</span>
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}

function AddressForm({ values, errors, onChange }) {
  const set = (k) => (e) => onChange({ ...values, [k]: e.target.value });
  const Field = ({ label, name, placeholder, full, type = "text", help }) => (
    <label className={"bk2__field" + (full ? " bk2__field--full" : "")}>
      <span className="bk2__flabel">{label}</span>
      <input type={type}
             className={"bk2__input" + (errors[name] ? " is-err" : "")}
             placeholder={placeholder} value={values[name] || ""} onChange={set(name)} />
      {errors[name] && <span className="bk2__ferr">{errors[name]}</span>}
      {help && !errors[name] && <span className="bk2__fhelp">{help}</span>}
    </label>
  );
  return (
    <div className="bk2__form">
      <Field label="Street address" name="street" placeholder="123 Main St" full />
      <Field label="Apt / unit (optional)" name="unit" placeholder="—" />
      <Field label="ZIP" name="zip" placeholder="11215" />
      <Field label="Where will the items be?" name="notes" placeholder="Garage, side door, second floor" full
             help="Helps us send the right team. We'll text on the way." />
      <Field label="Your name" name="name" placeholder="Full name" />
      <Field label="Mobile" name="phone" placeholder="(555) 123-4567" type="tel" />
    </div>
  );
}

function ReviewPanel({ tier, dayLabel, windowLabel, address, name, phone, onEdit }) {
  const rows = [
    { k: "Service",  v: tier?.name, edit: 0 },
    { k: "Date",     v: dayLabel, edit: 1 },
    { k: "Window",   v: windowLabel, edit: 1 },
    { k: "Address",  v: address, edit: 2 },
    { k: "Contact",  v: name && phone ? `${name} · ${phone}` : null, edit: 2 },
  ];
  return (
    <div className="bk2__review">
      <div className="bk2__review-list">
        {rows.map(r => (
          <div key={r.k} className="bk2__review-row">
            <span className="bk2__review-k">{r.k}</span>
            <span className="bk2__review-v">{r.v || "—"}</span>
            <button className="bk2__review-edit" onClick={() => onEdit(r.edit)}>Edit</button>
          </div>
        ))}
      </div>
      <div className="bk2__review-total">
        <span>Total</span>
        <strong>${tier?.price}</strong>
      </div>
      <p className="bk2__review-fine">
        No deposit. We charge after the job, when you're satisfied. Reschedule any time
        from the link in your confirmation email.
      </p>
    </div>
  );
}

function StickyBar({ tier, dayLabel, windowLabel, canNext, onBack, onNext, step, isLast }) {
  return (
    <div className="bk2__sticky">
      <div className="bk2__sticky-inner">
        <div className="bk2__sticky-summary">
          {tier ? (
            <>
              <span className="bk2__sticky-label">Your</span>
              <span className="bk2__sticky-tier"><em>{tier.name}</em></span>
              {dayLabel && <span className="bk2__sticky-meta">· {dayLabel.split(",")[0]}{windowLabel ? `, ${windowLabel}` : ""}</span>}
              <span className="bk2__sticky-price">${tier.price}</span>
            </>
          ) : (
            <span className="bk2__sticky-empty">Pick a service to see your price</span>
          )}
        </div>
        <div className="bk2__sticky-actions">
          {step > 0 && <button className="bk2__back" onClick={onBack}>Back</button>}
          <button className="btn btn--primary btn--lg"
                  disabled={!canNext} onClick={onNext}
                  style={!canNext ? { opacity: 0.4, cursor: "not-allowed" } : {}}>
            {isLast ? "Confirm booking" : "Continue"} <span className="arrow" aria-hidden>→</span>
          </button>
        </div>
      </div>
    </div>
  );
}

function BookingFlow({ navigate, initialTier }) {
  const initial = initialTier ? window.TIERS.find(t => t.id === initialTier) : null;
  const [step, setStep] = React.useState(0);
  const [tier, setTier] = React.useState(initial);
  const [sched, setSched] = React.useState({ day: null, dayLabel: null, windowId: null, windowLabel: null });
  const [addr, setAddr] = React.useState({ street: "", unit: "", zip: "", notes: "", name: "", phone: "" });
  const [errors, setErrors] = React.useState({});

  const addressLine = addr.street ? (addr.street + (addr.unit ? `, ${addr.unit}` : "") + (addr.zip ? `, ${addr.zip}` : "")) : "";

  const validateAddress = () => {
    const e = {};
    if (!addr.street.trim()) e.street = "Required";
    if (!addr.zip.trim()) e.zip = "Required";
    else if (!/^\d{5}$/.test(addr.zip.trim())) e.zip = "5 digits";
    if (!addr.name.trim()) e.name = "Required";
    if (!addr.phone.trim()) e.phone = "Required";
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const canNext =
    (step === 0 && !!tier) ||
    (step === 1 && sched.day && sched.windowId) ||
    (step === 2) ||
    (step === 3);

  const next = () => {
    if (step === 2 && !validateAddress()) return;
    setStep(s => Math.min(s + 1, 4));
    window.scrollTo({ top: 0, behavior: "smooth" });
  };
  const back = () => setStep(s => Math.max(s - 1, 0));

  if (step === 4) {
    return (
      <div className="bk2">
        <header className="bk2__topbar">
          <img src="assets/tossit-logo.svg" alt="Tossit" onClick={() => navigate("home")} style={{cursor:"pointer"}} />
          <button className="bk2__help" onClick={() => navigate("contact")}>Need help?</button>
        </header>
        <div className="bk2__confirm">
          <div className="bk2__confirm-mark" aria-hidden>
            <svg viewBox="0 0 32 32" width="32" height="32"><path d="M7 16.5l5.5 5.5L25 9" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"/></svg>
          </div>
          <h1 className="bk2__confirm-title">You're <em>booked.</em></h1>
          <p className="bk2__confirm-sub">
            See you {sched.dayLabel?.split(",")[0] || "soon"}. We'll text you the morning of with your team's name and a photo.
          </p>
          <div className="bk2__confirm-card">
            <div className="bk2__review-row"><span className="bk2__review-k">Service</span><span className="bk2__review-v">{tier.name}</span></div>
            <div className="bk2__review-row"><span className="bk2__review-k">When</span><span className="bk2__review-v">{sched.dayLabel} · {sched.windowLabel}</span></div>
            <div className="bk2__review-row"><span className="bk2__review-k">Where</span><span className="bk2__review-v">{addressLine}</span></div>
            <div className="bk2__review-row"><span className="bk2__review-k">Confirmation</span><span className="bk2__review-v">TS-{(Math.random()*9000+1000).toFixed(0)}</span></div>
            <div className="bk2__review-total"><span>Total</span><strong>${tier.price}</strong></div>
          </div>
          <div className="bk2__confirm-actions">
            <button className="btn btn--dark btn--lg" onClick={() => navigate("home")}>Back to home</button>
            <button className="btn btn--ghost" onClick={() => { setStep(0); setTier(null); setSched({ day:null,dayLabel:null,windowId:null,windowLabel:null }); setAddr({street:"",unit:"",zip:"",notes:"",name:"",phone:""}); }}>
              Book another
            </button>
          </div>
        </div>
      </div>
    );
  }

  const heads = [
    { title: <>What's <em>going?</em></>,        sub: "Pick the option that fits. The price is locked when you book." },
    { title: <>Pick a <em>window.</em></>,       sub: "Two-hour arrival windows. We'll text the morning of." },
    { title: <>Where are <em>we headed?</em></>, sub: "We need this to route the right team." },
    { title: <>One last <em>look.</em></>,       sub: "No deposit. We charge after the job, when you're satisfied." },
  ];
  const head = heads[step];

  return (
    <div className="bk2">
      <header className="bk2__topbar">
        <img src="assets/tossit-logo.svg" alt="Tossit" onClick={() => navigate("home")} style={{cursor:"pointer"}} />
        <button className="bk2__help" onClick={() => navigate("contact")}>Need help?</button>
      </header>

      <div className="bk2__layout">
        <aside className="bk2__sidebar">
          <VerticalStepper step={step} onJump={setStep} />
          <div className="bk2__sidebar-foot">
            <span className="bk2__sidebar-foot-k">Need a hand?</span>
            <span className="bk2__sidebar-foot-v">(415) 555‑8866</span>
            <span className="bk2__sidebar-foot-v">help@tossit.co</span>
          </div>
        </aside>

        <main className="bk2__main">
          <div className="bk2__head">
            <span className="bk2__crumb">Step {step + 1} of 4</span>
            <h1 className="bk2__title">{head.title}</h1>
            <p className="bk2__sub">{head.sub}</p>
          </div>
          <div className="bk2__panel">
            {step === 0 && <ItemPicker value={tier?.id} onChange={setTier} />}
            {step === 1 && <Scheduler day={sched.day} windowId={sched.windowId}
                            onChange={(patch) => setSched(prev => ({ ...prev, ...patch }))} />}
            {step === 2 && <AddressForm values={addr} errors={errors} onChange={setAddr} />}
            {step === 3 && <ReviewPanel tier={tier} dayLabel={sched.dayLabel} windowLabel={sched.windowLabel}
                                        address={addressLine} name={addr.name} phone={addr.phone}
                                        onEdit={(s) => setStep(s)} />}
          </div>
        </main>
      </div>

      <StickyBar tier={tier} dayLabel={sched.dayLabel} windowLabel={sched.windowLabel}
                 canNext={canNext} onBack={back} onNext={next}
                 step={step} isLast={step === 3} />
    </div>
  );
}
window.BookingFlow = BookingFlow;
