/* ============================================================
   Guest — public, no-login ride request page
   For guests who turn up off-schedule (early or late) while
   vans are staged. They flag HQ that they need a ride.
   ============================================================ */

const GUEST_REQ_KEY = "cd_guestReq";
const GUEST_NAME_KEY = "cd_guestName";

function GuestApp({ state, toast }) {
  const [reqId, setReqId] = useState(() => { try { return localStorage.getItem(GUEST_REQ_KEY) || ""; } catch (e) { return ""; } });
  const [showForm, setShowForm] = useState(false);
  const ride = reqId ? state.rides.find((r) => r.id === reqId) : null;
  const activeShuttles = (state.shuttles || []);

  const saveReq = (id) => { setReqId(id); try { localStorage.setItem(GUEST_REQ_KEY, id); } catch (e) {} };
  const clearReq = () => { setReqId(""); try { localStorage.removeItem(GUEST_REQ_KEY); } catch (e) {} };

  const StatusBar = () => (
    <div className="statusbar">
      <span>{new Date().toLocaleTimeString([], { hour: "numeric", minute: "2-digit" })}</span>
      <div className="icons mono" style={{ fontSize: 11 }}><span>◗</span><span>5G</span><span>87%</span></div>
    </div>
  );

  return (
    <>
      <StatusBar />
      <div className="g-brand">
        <span className="g-brand-mark"><Icon name="car2" style={{ width: 18, height: 18 }} /></span>
        <div><div className="g-brand-name">Conference Rides</div><div className="g-brand-sub">Drivers &amp; shuttle team</div></div>
      </div>
      <div className="mobile-body">
        {ride && ride.status !== "completed"
          ? <RequestStatus state={state} ride={ride} onCancel={() => { Store.removeRide(ride.id); clearReq(); toast("Request cancelled"); }} />
          : ride && ride.status === "completed"
            ? <RequestDone onAgain={clearReq} />
            : (activeShuttles.length > 0 && !showForm)
              ? <ShuttleNotice state={state} shuttles={activeShuttles} onRequest={() => setShowForm(true)} />
              : <RequestForm state={state} toast={toast} onSubmitted={saveReq} />}
      </div>
    </>
  );
}

/* ---------------- Shuttle notice (shown while shuttles run) ---------------- */
function ShuttleNotice({ state, shuttles, onRequest }) {
  return (
    <div className="fade-in g-scroll">
      <div className="g-status-hero" style={{ paddingTop: 26 }}>
        <div className="g-pulse"><span /><span /><Icon name="refresh" /></div>
        <h2>Shuttles are running</h2>
        <div className="dim" style={{ fontSize: 13.5, marginTop: 6, padding: "0 22px", lineHeight: 1.5 }}>
          No need to book — just head to your hotel lobby and hop on the next van. They’re looping every few minutes.
        </div>
      </div>

      <div className="m-sec">
        <div className="m-sec-h">Running now</div>
        {shuttles.map((s) => {
          const vans = state.drivers.filter((d) => d.shuttleId === s.id).length;
          return (
            <div className="sn-route" key={s.id}>
              <span className="sn-ic"><Icon name="home" /></span>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div className="sn-name">{locName(Store, s.origin)} ↔ {locName(Store, "venue")}</div>
                <div className="sn-meta">{vans > 0 ? vans + " van" + (vans === 1 ? "" : "s") + " · every few min" : "starting shortly"}</div>
              </div>
              <span className="sn-live"><span className="pdot" />LIVE</span>
            </div>
          );
        })}
      </div>

      <div className="m-sec">
        <div className="sn-other">
          <div>Going somewhere else, or need a hand?</div>
          <button className="btn btn-ghost" style={{ width: "100%", justifyContent: "center", marginTop: 9 }} onClick={onRequest}>Request a ride instead</button>
        </div>
      </div>
    </div>
  );
}

/* ---------------- Request form ---------------- */
function Stepper({ value, onChange, min = 1, max = 8 }) {
  return (
    <div className="stepper">
      <button onClick={() => onChange(Math.max(min, value - 1))} disabled={value <= min}>−</button>
      <span className="mono">{value}</span>
      <button onClick={() => onChange(Math.min(max, value + 1))} disabled={value >= max}>+</button>
    </div>
  );
}

function RequestForm({ state, toast, onSubmitted }) {
  const [step, setStep] = useState(0);
  const [name, setName] = useState(() => { try { return localStorage.getItem(GUEST_NAME_KEY) || ""; } catch (e) { return ""; } });
  const [from, setFrom] = useState("");
  const [to, setTo] = useState("");
  const [party, setParty] = useState(1);
  const [note, setNote] = useState("");
  const iconFor = (k) => k === "airport" ? "plane" : k === "venue" ? "star" : "home";

  const pickFrom = (id) => { setFrom(id); if (to === id) setTo(""); setStep(1); };
  const pickTo = (id) => { setTo(id); setStep(2); };

  const submit = () => {
    if (!from || !to) return;
    try { localStorage.setItem(GUEST_NAME_KEY, name.trim()); } catch (e) {}
    const id = Store.addGuestRequest({ guestName: name.trim(), from, to, party, note: note.trim() });
    toast("Sent — HQ has been notified");
    onSubmitted(id);
  };

  return (
    <div className="g-flow">
      {/* progress + breadcrumb */}
      <div className="g-flow-top">
        <div className="su-dots" style={{ maxWidth: 120 }}>
          {[0, 1, 2].map((i) => <span key={i} className={"su-dot" + (i === step ? " on" : i < step ? " done" : "")} />)}
        </div>
        {(from || to) && (
          <div className="g-crumb">
            {from && <button className="g-crumb-chip" onClick={() => setStep(0)}>{locName(Store, from)}</button>}
            {from && <Icon name="arrow" style={{ width: 13, height: 13, color: "var(--ink-faint)" }} />}
            {to ? <button className="g-crumb-chip" onClick={() => setStep(1)}>{locName(Store, to)}</button>
                : from && <span className="g-crumb-chip ghost">Drop-off?</span>}
          </div>
        )}
      </div>

      <div className="g-step" key={step}>
        {step === 0 && (
          <>
            <div className="g-head">
              <h2>Where are you now?</h2>
              <p>Vans run scheduled pickups before each session and drop-offs after. Turned up early or late? Tap where you are.</p>
            </div>
            <div className="loc-tiles big">
              {state.locations.map((l) => (
                <button key={l.id} className={"loc-tile" + (from === l.id ? " sel" : "")} onClick={() => pickFrom(l.id)}>
                  <Icon name={iconFor(l.kind)} /><span>{l.name}</span>
                </button>
              ))}
            </div>
          </>
        )}

        {step === 1 && (
          <>
            <div className="g-head">
              <h2>Where do you need to go?</h2>
              <p>Picking you up from <b>{locName(Store, from)}</b>.</p>
            </div>
            <div className="loc-tiles big">
              {state.locations.filter((l) => l.id !== from).map((l) => (
                <button key={l.id} className={"loc-tile" + (to === l.id ? " sel" : "")} onClick={() => pickTo(l.id)}>
                  <Icon name={iconFor(l.kind)} /><span>{l.name}</span>
                </button>
              ))}
            </div>
            <button className="g-back" onClick={() => setStep(0)}><Icon name="arrow" style={{ width: 15, height: 15, transform: "rotate(180deg)" }} /> Change pickup</button>
          </>
        )}

        {step === 2 && (
          <>
            <div className="g-head">
              <h2>Almost done</h2>
              <p>Just so the driver knows who to look for.</p>
            </div>
            <div className="g-route-summary">
              <div className="grs-end"><span className="grs-cap">PICKUP</span><span className="grs-loc">{locName(Store, from)}</span></div>
              <div className="grs-arrow"><Icon name="arrow" /></div>
              <div className="grs-end"><span className="grs-cap">DROP-OFF</span><span className="grs-loc">{locName(Store, to)}</span></div>
            </div>

            <div className="m-sec" style={{ padding: "4px 0 0" }}>
              <label className="lbl">Your name</label>
              <input className="field" value={name} onChange={(e) => setName(e.target.value)} placeholder="So the driver knows who to look for" autoFocus />
            </div>
            <div className="m-sec" style={{ padding: "14px 0 0" }}>
              <div className="g-row">
                <div className="g-q" style={{ margin: 0 }}>How many people?</div>
                <Stepper value={party} onChange={setParty} />
              </div>
            </div>
            <div className="m-sec" style={{ padding: "14px 0 0" }}>
              <label className="lbl">Anything HQ should know? (optional)</label>
              <input className="field" value={note} onChange={(e) => setNote(e.target.value)} placeholder="e.g. wheelchair, lots of luggage, by the main doors" />
            </div>

            <button className="g-back" onClick={() => setStep(1)}><Icon name="arrow" style={{ width: 15, height: 15, transform: "rotate(180deg)" }} /> Change drop-off</button>
          </>
        )}
      </div>

      {step === 2 && (
        <div className="g-flow-cta">
          <button onClick={submit}>Confirm ride</button>
        </div>
      )}
    </div>
  );
}

/* ---------------- Request status ---------------- */
function RequestStatus({ state, ride, onCancel }) {
  const driver = state.drivers.find((d) => d.id === ride.driverId);
  const vehicle = driver && state.vehicles.find((v) => v.id === driver.vehicleId);
  const steps = ["requested", "assigned", "enroute", "completed"];
  const stepLabels = {
    requested: "HQ has your request",
    assigned: "A van is assigned to you",
    enroute: "Your van is on the way",
    completed: "Picked up",
  };
  const curIdx = steps.indexOf(ride.status);
  const headline = ride.status === "requested" ? "We’ve let HQ know"
    : ride.status === "assigned" ? "A van is coming for you"
    : ride.status === "enroute" ? "Your van is on the way" : "All set";

  return (
    <div className="fade-in g-scroll">
      <div className="g-status-hero">
        <div className="g-pulse"><span /><span /><Icon name="car2" /></div>
        <h2>{headline}</h2>
        <div className="g-route mono">{locName(Store, ride.from)} → {locName(Store, ride.to)} · party {ride.party}</div>
      </div>

      <div className="m-sec">
        <div className="m-card">
          {steps.map((s, i) => (
            <div key={s} className={"track-step " + (i < curIdx ? "done" : i === curIdx ? "active" : "pending")}>
              <div className="tnode">{i <= curIdx ? <Icon name="check" style={{ width: 13, height: 13 }} /> : null}</div>
              <div><div className="tlabel">{stepLabels[s]}</div>{i === curIdx && <div className="ttime">Now</div>}</div>
            </div>
          ))}
        </div>
      </div>

      {driver && (
        <div className="m-sec">
          <div className="m-sec-h">Your driver</div>
          <div className="m-card" style={{ display: "flex", alignItems: "center", gap: 12 }}>
            <Avatar initials={driver.initials} tone="sky" size={42} />
            <div style={{ flex: 1 }}>
              <div style={{ fontWeight: 600, fontSize: 14 }}>{driver.name}</div>
              <div className="mono dim" style={{ fontSize: 11.5 }}>{vehicle.name} · {vehicle.plate}</div>
            </div>
            <button className="btn btn-ghost btn-sm"><Icon name="phone" style={{ width: 14, height: 14 }} /> Call</button>
          </div>
        </div>
      )}

      {ride.note && (
        <div className="m-sec">
          <div className="g-note">You told HQ: “{ride.note}”</div>
        </div>
      )}

      <div className="m-sec">
        <button className="btn btn-ghost" style={{ width: "100%", justifyContent: "center", color: "var(--rose)" }} onClick={onCancel}>
          Cancel this request
        </button>
        <div className="g-fineprint">If a scheduled van arrives first, just hop on — we’ll clear this for you.</div>
      </div>
    </div>
  );
}

function RequestDone({ onAgain }) {
  return (
    <div className="fade-in g-scroll">
      <div className="g-status-hero" style={{ paddingTop: 60 }}>
        <div className="g-done"><Icon name="check" /></div>
        <h2>You’ve been picked up</h2>
        <div className="dim" style={{ fontSize: 13.5, marginTop: 4 }}>Have a great session.</div>
      </div>
      <div className="m-cta">
        <button onClick={onAgain}>Request another ride</button>
      </div>
    </div>
  );
}

Object.assign(window, { GuestApp });
