// Hotel Walks — Send a walk request.
// Multi-step flow:
// 1. Guest + nights  → 2. Routing strategy + partners  → 3. Review + send
// 4. Live broadcast view with timer and (faked) partner responses.

(function() {
  const { useState, useEffect, useMemo } = React;
  const { Caps, Btn, Field, Input, Stepper, Pill, Toggle, Hr, money } = window.UI;
  const { HOTELS, HOTEL_BY_ID, PARTNERS, ME } = window.HW_DATA;

  const STEPS = ["Guest", "Routing", "Review", "Broadcast"];

  function Stepper7({ step }) {
    return (
      <div style={{ display: "flex", gap: 0, padding: "0 48px", borderBottom: "1px solid var(--rule)", overflowX: "auto", background: "var(--paper)" }} className="step-strip">
        {STEPS.map((s, i) => {
          const done = i < step;
          const active = i === step;
          return (
            <div key={s} style={{
              padding: "20px 24px",
              borderRight: i < STEPS.length - 1 ? "1px solid var(--rule)" : undefined,
              opacity: active || done ? 1 : 0.4,
              flex: 1,
              minWidth: 130,
              borderTop: active ? "2px solid var(--ink)" : "2px solid transparent",
              marginTop: -1,
            }}>
              <div style={{ display: "flex", alignItems: "baseline", gap: 12 }}>
                <span className="mono" style={{ fontSize: 11, color: "var(--muted)" }}>{String(i+1).padStart(2,"0")}</span>
                <span className="serif-i" style={{ fontSize: 20 }}>{s}</span>
                {done && <Pill tone="muted">✓</Pill>}
              </div>
            </div>
          );
        })}
      </div>
    );
  }

  function PageShell({ step, title, sub, children, footer }) {
    return (
      <div data-screen-label={`Send walk · ${STEPS[step]}`} style={{ background: "var(--paper)" }}>
        <div className="pad-lg" style={{ padding: "44px 48px 28px", borderBottom: "1px solid var(--rule)" }}>
          <Caps>New walk request</Caps>
          <div className="serif-i page-title" style={{ fontSize: 52, lineHeight: 1, marginTop: 14 }}>{title}</div>
          {sub && <p className="page-intro" style={{ marginTop: 14, color: "var(--muted)", fontSize: 15 }}>{sub}</p>}
        </div>
        <Stepper7 step={step} />
        <div className="pad-md" style={{ padding: "48px 48px 32px", maxWidth: 1100 }}>
          {children}
        </div>
        {footer && (
          <div className="send-footer" style={{
            position: "sticky", bottom: 0,
            background: "var(--paper)",
            borderTop: "1px solid var(--rule-strong)",
            padding: "20px 48px",
            display: "flex", justifyContent: "space-between", alignItems: "center",
            gap: 12, flexWrap: "wrap",
            zIndex: 10,
          }}>
            {footer}
          </div>
        )}
      </div>
    );
  }

  /* ──────────────────  STEP 1  ────────────────── */
  function StepGuest({ form, setForm, onNext }) {
    return (
      <PageShell step={0}
        title="Who is being walked?"
        sub="Front desk staff fills this once. Everything else routes automatically."
        footer={
          <>
            <a href="#/app" style={{ textDecoration: "none" }}><Btn kind="ghost">← Cancel</Btn></a>
            <Btn onClick={onNext} disabled={!form.guest || !form.confirmation}>Routing →</Btn>
          </>
        }>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 56, alignItems: "start" }} className="form-cols">
          <div style={{ display: "flex", flexDirection: "column", gap: 36 }}>
            <Field label="Guest name">
              <Input value={form.guest} onChange={e => setForm({...form, guest: e.target.value})} placeholder="Maya Klein" />
            </Field>
            <Field label="Confirmation number" suffix="Wythe PMS">
              <Input mono value={form.confirmation} onChange={e => setForm({...form, confirmation: e.target.value})} placeholder="WY-882103" />
            </Field>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 16 }}>
              <Field label="Party">
                <Stepper value={form.party} onChange={v => setForm({...form, party: v})} min={1} max={8} width="100%" />
              </Field>
              <Field label="Nights">
                <Stepper value={form.nights} onChange={v => setForm({...form, nights: v})} min={1} max={14} width="100%" />
              </Field>
              <Field label="Max days we pay" hint="Length of relocation we'll cover">
                <Stepper value={form.maxDays} onChange={v => setForm({...form, maxDays: v})} min={1} max={form.nights} width="100%" />
              </Field>
            </div>
          </div>

          <div style={{ display: "flex", flexDirection: "column", gap: 36 }}>
            <Field label="Arrival date">
              <Input value={form.arrival} onChange={e => setForm({...form, arrival: e.target.value})} type="date" />
            </Field>
            <div>
              <Caps style={{ marginBottom: 16, display: "block" }}>Reason</Caps>
              <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
                {["Oversold","Mechanical","VIP bump","Guest request"].map(r => (
                  <button key={r} onClick={() => setForm({...form, reason: r})} style={{
                    background: form.reason === r ? "var(--ink)" : "transparent",
                    color: form.reason === r ? "var(--bone)" : "var(--ink)",
                    border: "1px solid var(--ink)",
                    padding: "9px 16px", fontSize: 12,
                    fontFamily: "'JetBrains Mono', monospace", letterSpacing: "0.10em",
                    textTransform: "uppercase", cursor: "pointer",
                  }}>{r}</button>
                ))}
              </div>
            </div>
            <Field label="Internal note" hint="Visible to receiving partner. Optional.">
              <Input value={form.note} onChange={e => setForm({...form, note: e.target.value})} placeholder="Late arrival, ETA 10pm" />
            </Field>
          </div>
        </div>
      </PageShell>
    );
  }

  /* ──────────────────  STEP 2  ────────────────── */
  function StepRouting({ form, setForm, onNext, onBack }) {
    const selectedPartners = form.partners;
    const togglePartner = (id) => {
      const cur = new Set(selectedPartners);
      cur.has(id) ? cur.delete(id) : cur.add(id);
      setForm({...form, partners: Array.from(cur)});
    };
    return (
      <PageShell step={1}
        title="Where should it go?"
        sub="Broadcast to ranked partners, or by best rate. Toggle Urgent to bypass timers and send to everyone at once."
        footer={
          <>
            <Btn kind="ghost" onClick={onBack}>← Back</Btn>
            <Btn onClick={onNext} disabled={selectedPartners.length === 0}>Review →</Btn>
          </>
        }>
        {/* Controls */}
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 24, marginBottom: 40 }} className="route-controls">
          <Field label="Target rate" hint="What we're willing to pay per night">
            <Input mono value={form.targetRate} onChange={e => setForm({...form, targetRate: e.target.value.replace(/[^0-9]/g,"")})} placeholder="425" />
          </Field>
          <Field label="Strategy" hint="How partners are prioritised">
            <div style={{ display: "flex", gap: 6, marginTop: 4 }}>
              {[["preference","By preference"], ["rate","By best rate"]].map(([v, l]) => (
                <button key={v} onClick={() => setForm({...form, strategy: v})} style={{
                  flex: 1,
                  background: form.strategy === v ? "var(--ink)" : "transparent",
                  color: form.strategy === v ? "var(--bone)" : "var(--ink)",
                  border: "1px solid var(--ink)",
                  padding: "10px 12px", fontSize: 11,
                  fontFamily: "'JetBrains Mono', monospace", letterSpacing: "0.10em", textTransform: "uppercase",
                  cursor: "pointer",
                }}>{l}</button>
              ))}
            </div>
          </Field>
          <Field label="Escalation timer" hint="Minutes per partner before moving on">
            <div style={{ marginTop: 4 }}>
              <Stepper value={form.timer} onChange={v => setForm({...form, timer: v})} min={0} max={180} step={5} prefix="" width="100%" />
            </div>
          </Field>
        </div>

        <div style={{
          background: form.urgent ? "var(--ink)" : "transparent",
          color: form.urgent ? "var(--bone)" : "var(--ink)",
          border: "1px solid var(--ink)",
          padding: "20px 24px", marginBottom: 32,
          display: "flex", justifyContent: "space-between", alignItems: "center", gap: 24,
        }}>
          <div>
            <Caps color={form.urgent ? "rgba(244,238,221,0.6)" : undefined}>Urgent mode</Caps>
            <div className="serif-i" style={{ fontSize: 22, marginTop: 6 }}>
              Bypass timers. Broadcast to all partners at once.
            </div>
          </div>
          <Toggle on={form.urgent} onChange={v => setForm({...form, urgent: v})} />
        </div>

        {/* Partners list */}
        <div style={{ marginBottom: 18, display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
          <Caps>Partners · {selectedPartners.length} selected</Caps>
          <button onClick={() => setForm({...form, partners: PARTNERS.map(p => p.id)})} style={{ background: "none", border: "none", padding: 0 }}>
            <Caps>Select all</Caps>
          </button>
        </div>
        <div style={{ borderTop: "1px solid var(--ink)" }}>
          {PARTNERS.map(p => {
            const hotel = HOTEL_BY_ID[p.id];
            const checked = selectedPartners.includes(p.id);
            return (
              <button key={p.id} onClick={() => togglePartner(p.id)} style={{
                width: "100%", textAlign: "left",
                background: "transparent", border: "none",
                borderBottom: "1px solid var(--rule)",
                padding: "20px 0", cursor: "pointer",
                display: "grid",
                gridTemplateColumns: "30px 60px 1fr 130px 130px 90px",
                gap: 16, alignItems: "center",
              }} className="partner-row">
                <div style={{
                  width: 18, height: 18, border: "1px solid var(--ink)",
                  background: checked ? "var(--ink)" : "transparent",
                  display: "inline-flex", alignItems: "center", justifyContent: "center",
                  color: "var(--bone)", fontSize: 11,
                }}>{checked ? "✓" : ""}</div>
                <div className="mono" style={{ fontSize: 13, color: "var(--muted)" }}>#{p.pref}</div>
                <div>
                  <div className="row-name" style={{ fontSize: 17 }}>{hotel.name}</div>
                  <div className="row-sub" style={{ marginTop: 4 }}>{hotel.area}</div>
                </div>
                <div>
                  <Caps>Last rate</Caps>
                  <div className="mono" style={{ fontSize: 15, marginTop: 6 }}>{money(p.lastRate)}</div>
                </div>
                <div>
                  <Caps>Accepts</Caps>
                  <div className="mono" style={{ fontSize: 15, marginTop: 6 }}>{Math.round(p.acceptance*100)}% · ~{p.avgMin}m</div>
                </div>
                <div className="mono" style={{ fontSize: 12, color: "var(--muted)", textAlign: "right" }}>
                  {checked ? "Selected" : ""}
                </div>
              </button>
            );
          })}
        </div>
      </PageShell>
    );
  }

  /* ──────────────────  STEP 3  ────────────────── */
  function StepReview({ form, onBack, onSend }) {
    const lines = [
      ["Guest", form.guest || "—"],
      ["Confirmation", form.confirmation || "—"],
      ["Party · nights", `${form.party} · ${form.nights}`],
      ["Arrival", form.arrival || "Today"],
      ["Reason", form.reason],
      ["Max days covered", `${form.maxDays} of ${form.nights}`],
      ["Target rate", form.targetRate ? money(form.targetRate) : "Open"],
      ["Strategy", form.strategy === "preference" ? "By partner preference" : "By best rate"],
      ["Escalation", form.urgent ? "URGENT — broadcast simultaneously" : `${form.timer} min per partner`],
      ["Partners", form.partners.length + " selected"],
    ];
    return (
      <PageShell step={2}
        title="Confirm and broadcast."
        sub="Once sent, the receiving hotel sees your request immediately and the escalation timer begins."
        footer={
          <>
            <Btn kind="ghost" onClick={onBack}>← Back</Btn>
            <Btn onClick={onSend}>Send walk request</Btn>
          </>
        }>
        <div style={{ display: "grid", gridTemplateColumns: "1.2fr 1fr", gap: 56 }} className="review-cols">
          <div>
            <Caps>Walk envelope</Caps>
            <div style={{ marginTop: 18, borderTop: "1px solid var(--ink)" }}>
              {lines.map(([k, v], i) => (
                <div key={i} style={{
                  display: "grid", gridTemplateColumns: "180px 1fr",
                  padding: "16px 0", borderBottom: "1px solid var(--rule)",
                  alignItems: "baseline", gap: 24,
                }}>
                  <Caps>{k}</Caps>
                  <div style={{ fontSize: 15 }}>{v}</div>
                </div>
              ))}
            </div>
          </div>
          <div>
            <Caps>Partners · in order</Caps>
            <ol style={{ listStyle: "none", padding: 0, margin: "18px 0 0", borderTop: "1px solid var(--ink)" }}>
              {form.partners.map((id, i) => {
                const h = HOTEL_BY_ID[id];
                return (
                  <li key={id} style={{
                    padding: "16px 0", borderBottom: "1px solid var(--rule)",
                    display: "flex", justifyContent: "space-between", alignItems: "baseline",
                  }}>
                    <div style={{ display: "flex", alignItems: "baseline", gap: 14 }}>
                      <span className="mono" style={{ fontSize: 12, color: "var(--muted)" }}>{String(i+1).padStart(2,"0")}</span>
                      <span className="row-name" style={{ fontSize: 15 }}>{h.name}</span>
                    </div>
                    <Caps>{form.urgent ? "Now" : `+${i * form.timer}m`}</Caps>
                  </li>
                );
              })}
            </ol>

            <div style={{ marginTop: 32, padding: 24, border: "1px solid var(--rule)", background: "var(--bone-2)" }}>
              <Caps>Estimated cost · to {ME.property.name}</Caps>
              <div style={{ display: "flex", justifyContent: "space-between", marginTop: 14, alignItems: "baseline" }}>
                <div className="serif-i" style={{ fontSize: 28 }}>$4.00 + 10%</div>
                <div className="mono" style={{ fontSize: 13, color: "var(--muted)" }}>per walked guest</div>
              </div>
            </div>
          </div>
        </div>
      </PageShell>
    );
  }

  /* ──────────────────  STEP 4 — Live broadcast  ────────────────── */
  function StepBroadcast({ form, onDone }) {
    // Simulate partner responses over time.
    const [responses, setResponses] = useState(
      form.partners.map(id => ({ id, state: "pending" }))
    );
    const [elapsed, setElapsed] = useState(0);
    const acceptedIdx = responses.findIndex(r => r.state === "accepted");

    useEffect(() => {
      const tick = setInterval(() => setElapsed(e => e + 1), 1000);
      return () => clearInterval(tick);
    }, []);

    useEffect(() => {
      // Fake response timeline based on partner stats
      const timers = form.partners.map((id, i) => {
        const p = PARTNERS.find(pp => pp.id === id);
        const accepts = Math.random() < (p.acceptance);
        const wait = (form.urgent ? 0 : i * 1.2) + (p.avgMin * 0.4); // seconds
        return setTimeout(() => {
          setResponses(prev => prev.map(r => r.id === id ? {...r, state: accepts ? (prev.some(x => x.state === "accepted") ? "passed" : "accepted") : "passed"} : r));
        }, wait * 1000);
      });
      return () => timers.forEach(clearTimeout);
    }, []);

    const accepted = responses.find(r => r.state === "accepted");
    const acceptedHotel = accepted ? HOTEL_BY_ID[accepted.id] : null;

    return (
      <PageShell step={3}
        title={accepted ? "Re-housed." : "Broadcasting…"}
        sub={accepted
          ? `${acceptedHotel.name} accepted at ${money(form.targetRate || acceptedHotel.rate)}. Generate the walk letter to finalise.`
          : `Sent to ${form.partners.length} partners ${form.urgent ? "simultaneously" : `in sequence, ${form.timer}m apart`}.`
        }
        footer={
          accepted ? (
            <>
              <Btn kind="ghost" onClick={onDone}>← Back to today</Btn>
              <a href={`#/app/letter/W-77413`} style={{ textDecoration: "none" }}>
                <Btn>Generate walk letter →</Btn>
              </a>
            </>
          ) : (
            <>
              <Btn kind="danger" onClick={() => { if(confirm("Cancel this walk?")) onDone(); }}>Cancel broadcast</Btn>
              <Caps>Elapsed · {elapsed}s</Caps>
            </>
          )
        }>
        <div style={{ display: "grid", gridTemplateColumns: "minmax(0, 1.2fr) minmax(0, 1fr)", gap: 56 }} className="review-cols">
          <div>
            <Caps>Partner responses</Caps>
            <div style={{ marginTop: 18, borderTop: "1px solid var(--ink)" }}>
              {responses.map((r, i) => {
                const h = HOTEL_BY_ID[r.id];
                const isAccepted = r.state === "accepted";
                const isPassed = r.state === "passed";
                const isPending = r.state === "pending";
                return (
                  <div key={r.id} style={{
                    padding: "20px 0",
                    borderBottom: "1px solid var(--rule)",
                    display: "grid", gridTemplateColumns: "40px 1fr 160px 120px",
                    gap: 16, alignItems: "center",
                  }}>
                    <span className="mono" style={{ fontSize: 12, color: "var(--muted)" }}>{String(i+1).padStart(2,"0")}</span>
                    <div>
                      <div className="row-name" style={{ fontSize: 17, opacity: isPassed ? 0.4 : 1 }}>{h.name}</div>
                      <div className="row-sub" style={{ marginTop: 4 }}>{h.area}</div>
                    </div>
                    <div>
                      {isPending && <Pill tone="muted">Waiting…</Pill>}
                      {isAccepted && <Pill tone="good">Accepted</Pill>}
                      {isPassed && <Pill tone="muted">Passed</Pill>}
                    </div>
                    <div className="mono" style={{ fontSize: 13, textAlign: "right" }}>
                      {isAccepted ? money(form.targetRate || h.rate) : isPending ? "—" : "—"}
                    </div>
                  </div>
                );
              })}
            </div>
          </div>

          <div>
            {accepted ? (
              <div style={{ background: "var(--ink)", color: "var(--bone)", padding: 32, minHeight: 320 }}>
                <Caps color="rgba(244,238,221,0.55)">Accepted</Caps>
                <div className="serif-i" style={{ fontSize: 38, lineHeight: 1.05, marginTop: 18, marginBottom: 12 }}>
                  {acceptedHotel.name}
                </div>
                <div style={{ color: "rgba(244,238,221,0.6)", fontSize: 14 }}>{acceptedHotel.area}</div>
                <Hr tone="strong" style={{ margin: "24px 0", borderTopColor: "rgba(244,238,221,0.2)" }} />
                <Row k="Rate"          v={money(form.targetRate || acceptedHotel.rate)} dark />
                <Row k="Rooms"         v={form.party >= 3 ? "1" : "1"} dark />
                <Row k="Confirmation"  v="—" dark />
                <Row k="Serial"        v="pending" dark mono />
              </div>
            ) : (
              <div style={{ background: "var(--bone-2)", padding: 32, minHeight: 320 }}>
                <Caps>Live status</Caps>
                <div className="serif-i" style={{ fontSize: 28, marginTop: 18 }}>
                  Waiting for the first accept.
                </div>
                <p style={{ color: "var(--muted)", marginTop: 14, fontSize: 14, lineHeight: 1.6 }}>
                  {form.urgent
                    ? "All partners notified simultaneously. The first to accept wins the rooms."
                    : `If the top partner doesn't respond in ${form.timer} minutes, the next one is offered.`}
                </p>
                <div style={{ marginTop: 28, display: "flex", gap: 24, flexWrap: "wrap" }}>
                  <Stat label="Elapsed" value={`${elapsed}s`} />
                  <Stat label="Pending" value={String(responses.filter(r=>r.state==="pending").length)} />
                  <Stat label="Passed" value={String(responses.filter(r=>r.state==="passed").length)} />
                </div>
              </div>
            )}
          </div>
        </div>
      </PageShell>
    );
  }

  function Stat({ label, value }) {
    return (
      <div>
        <Caps>{label}</Caps>
        <div className="serif-i" style={{ fontSize: 30, marginTop: 6, lineHeight: 1 }}>{value}</div>
      </div>
    );
  }

  function Row({ k, v, dark, mono }) {
    return (
      <div style={{
        display: "flex", justifyContent: "space-between",
        padding: "10px 0",
        borderBottom: dark ? "1px solid rgba(244,238,221,0.14)" : "1px solid var(--rule)",
      }}>
        <Caps color={dark ? "rgba(244,238,221,0.55)" : undefined}>{k}</Caps>
        <div className={mono ? "mono" : ""} style={{ fontSize: 14 }}>{v}</div>
      </div>
    );
  }

  /* ──────────────────  Root  ────────────────── */
  function SendWalk() {
    const [step, setStep] = useState(0);
    const [form, setForm] = useState({
      guest: "Maya Klein",
      confirmation: "WY-882103",
      party: 2,
      nights: 1,
      maxDays: 1,
      arrival: "2026-05-21",
      reason: "Oversold",
      note: "Late arrival, ETA 10pm",
      targetRate: "425",
      strategy: "preference",
      timer: 30,
      urgent: false,
      partners: ["1HBB","HOXBK","PNHST","WMBG"],
    });

    if (step === 0) return <StepGuest form={form} setForm={setForm} onNext={() => setStep(1)} />;
    if (step === 1) return <StepRouting form={form} setForm={setForm} onNext={() => setStep(2)} onBack={() => setStep(0)} />;
    if (step === 2) return <StepReview form={form} onBack={() => setStep(1)} onSend={() => setStep(3)} />;
    if (step === 3) return <StepBroadcast form={form} onDone={() => window.HWgo("/app")} />;
    return null;
  }

  const responsiveCSS = `
    @media (max-width: 880px) {
      .form-cols, .route-controls, .review-cols { grid-template-columns: 1fr !important; gap: 32px !important; }
      .partner-row { grid-template-columns: 24px 30px 1fr !important; gap: 12px !important; }
      .partner-row > *:nth-child(n+4) { display: none; }
    }
    @media (max-width: 720px) {
      .page-title { font-size: 36px !important; }
      .send-footer { padding: 14px 18px !important; }
      .send-footer > * { flex: 1; }
      .send-footer button, .send-footer a > * { width: 100%; }
    }
  `;

  function WrappedSendWalk() {
    return (
      <>
        <style>{responsiveCSS}</style>
        <SendWalk />
      </>
    );
  }

  window.Screens = window.Screens || {};
  window.Screens.SendWalk = WrappedSendWalk;
})();
