// Hotel Walks — Incoming opportunities (receiving hotel side).
// IncomingList: a queue with quick accept/pass.
// IncomingDetail: full opportunity with revise rate / rooms, accept, pass.

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

  function ListHead() {
    return (
      <div className="pad-lg" style={{ padding: "44px 48px 24px" }}>
        <Caps>Inbound queue</Caps>
        <div className="serif-i page-title" style={{ fontSize: 52, lineHeight: 1, marginTop: 12 }}>
          {INCOMING.length} opportunities waiting on you.
        </div>
        <p className="page-intro" style={{ marginTop: 14, color: "var(--muted)", fontSize: 15 }}>
          Each row shows a request from a partner. Accept, pass, or open to negotiate the rate or rooms.
        </p>
      </div>
    );
  }

  function IncomingList() {
    return (
      <div data-screen-label="Incoming queue" style={{ background: "var(--paper)" }}>
        <ListHead />
        <div className="pad-md" style={{ padding: "32px 48px" }}>
          <div className="incoming-grid hw-row-header" style={{
            display: "grid",
            gridTemplateColumns: "110px 1.5fr 110px 110px 110px 1.2fr 220px",
            padding: "14px 0",
            borderTop: "1px solid var(--ink)",
            borderBottom: "1px solid var(--rule)",
          }}>
            {["When","From","Rooms","Target","Your rate","Note","Decision"].map((h, i) => (
              <div key={i}><Caps>{h}</Caps></div>
            ))}
          </div>

          {INCOMING.map(op => (
            <div key={op.id} className="incoming-grid hw-row" style={{
              display: "grid",
              gridTemplateColumns: "110px 1.5fr 110px 110px 110px 1.2fr 220px",
              padding: "24px 0",
              borderBottom: "1px solid var(--rule)",
              alignItems: "center",
              gap: 12,
            }}>
              <div>
                <Caps>{op.when}</Caps>
                <div style={{ marginTop: 8 }}>
                  {op.urgent
                    ? <Pill tone="warn">Urgent · {op.expiresIn}m</Pill>
                    : <span className="mono" style={{ fontSize: 12, color: "var(--muted)" }}>Expires in {op.expiresIn}m</span>}
                </div>
              </div>
              <div>
                <div className="row-name">{op.from.name}</div>
                <div className="row-sub" style={{ marginTop: 4 }}>{op.from.area}</div>
              </div>
              <div className="mono" style={{ fontSize: 14 }}>{op.rooms} × {op.nights}n</div>
              <div className="mono" style={{ fontSize: 14 }}>{op.targetRate ? money(op.targetRate) : "—"}</div>
              <div className="mono" style={{ fontSize: 14 }}>{money(op.myRate)}</div>
              <div style={{ fontSize: 14, color: "var(--muted)", lineHeight: 1.5 }}>{op.notes}</div>
              <div style={{ display: "flex", gap: 6, justifyContent: "flex-end" }}>
                <a href={`#/app/incoming/${op.id}`} style={{ textDecoration: "none" }}>
                  <Btn size="sm">Open →</Btn>
                </a>
                <Btn size="sm" kind="ghost" onClick={() => alert("Passed (demo)")}>Pass</Btn>
              </div>
            </div>
          ))}
        </div>
      </div>
    );
  }

  /* ──────────────────────────────────────────── */

  function IncomingDetail({ id }) {
    const op = INCOMING.find(o => o.id === id);
    if (!op) return (
      <div style={{ padding: 60 }}>
        <Caps>Opportunity not found</Caps>
        <div className="serif-i" style={{ fontSize: 30, marginTop: 16 }}>This request has expired or been withdrawn.</div>
        <div style={{ marginTop: 24 }}>
          <a href="#/app/incoming" style={{ textDecoration: "none" }}><Btn>Back to queue</Btn></a>
        </div>
      </div>
    );

    const [decision, setDecision] = useState(null); // null | "accept" | "revise" | "pass" | "done"
    const [revisedRooms, setRevisedRooms] = useState(op.rooms);
    const [revisedRate, setRevisedRate] = useState(String(op.targetRate || op.myRate));
    const [confirmation, setConfirmation] = useState("");

    if (decision === "done") {
      return (
        <div style={{ padding: "80px 48px", maxWidth: 760 }} data-screen-label="Incoming · confirmed">
          <Caps>Sent</Caps>
          <div className="serif-i" style={{ fontSize: 56, lineHeight: 1.02, marginTop: 16 }}>
            Confirmation returned to {op.from.name}.
          </div>
          <p style={{ marginTop: 18, color: "var(--muted)", fontSize: 15, maxWidth: "60ch" }}>
            We're holding {revisedRooms} room{revisedRooms>1?"s":""} at {money(revisedRate)} per night for the arrival of {op.arrival}.
            Confirmation number {confirmation || "WY-PENDING"}.
          </p>
          <div style={{ marginTop: 36, display: "flex", gap: 12 }}>
            <a href="#/app/incoming" style={{ textDecoration: "none" }}><Btn>Back to queue</Btn></a>
            <a href="#/app" style={{ textDecoration: "none" }}><Btn kind="ghost">Today</Btn></a>
          </div>
        </div>
      );
    }

    return (
      <div data-screen-label="Incoming · detail" style={{ background: "var(--paper)" }}>
        <div style={{ padding: "40px 48px 28px", borderBottom: "1px solid var(--rule)" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 14 }}>
            <a href="#/app/incoming" style={{ textDecoration: "none", color: "inherit" }}>
              <Caps>← Incoming</Caps>
            </a>
            <span style={{ color: "var(--muted)" }}>·</span>
            <Caps>{op.id}</Caps>
            {op.urgent && <Pill tone="warn">Urgent · {op.expiresIn}m</Pill>}
          </div>
          <div style={{ display: "flex", alignItems: "baseline", gap: 16, flexWrap: "wrap" }}>
            <div className="serif-i" style={{ fontSize: 56, lineHeight: 1 }}>{op.from.name}</div>
            <Caps>requests {op.rooms} room{op.rooms>1?"s":""}</Caps>
          </div>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 0, alignItems: "stretch" }} className="detail-cols">
          {/* LEFT — request envelope */}
          <div style={{ padding: "48px 48px", borderRight: "1px solid var(--rule)" }}>
            <Caps>The request</Caps>
            <div style={{ borderTop: "1px solid var(--ink)", marginTop: 18 }}>
              <Row k="Arrival"        v={op.arrival} />
              <Row k="Nights"         v={`${op.nights} night${op.nights>1?"s":""}`} />
              <Row k="Rooms"          v={`${op.rooms}`} />
              <Row k="Target rate"    v={op.targetRate ? money(op.targetRate) : "Open"} />
              <Row k="Your rate"      v={money(op.myRate)} />
              <Row k="From"           v={`${op.from.name} · ${op.from.area}`} />
            </div>

            <div style={{ marginTop: 28 }}>
              <Caps>Note from sender</Caps>
              <div className="serif-i" style={{ fontSize: 22, marginTop: 12, lineHeight: 1.4, color: "var(--ink)" }}>
                "{op.notes}"
              </div>
            </div>

            <div style={{ marginTop: 36, padding: 22, background: "var(--bone-2)", border: "1px solid var(--rule)" }}>
              <Caps>What you'll receive</Caps>
              <div style={{ display: "flex", justifyContent: "space-between", marginTop: 12, alignItems: "baseline" }}>
                <div className="serif-i" style={{ fontSize: 26 }}>
                  {money((Number(op.targetRate || op.myRate) * op.rooms * op.nights))}
                </div>
                <div className="mono" style={{ fontSize: 12, color: "var(--muted)" }}>gross · before $4 + 10%</div>
              </div>
            </div>
          </div>

          {/* RIGHT — decision panel */}
          <div style={{ padding: "48px 48px", background: "var(--bone-2)" }}>
            <Caps>Your decision</Caps>

            {/* Decision tabs */}
            <div style={{ display: "flex", marginTop: 18, marginBottom: 24, border: "1px solid var(--ink)" }}>
              {[
                ["accept", "Accept as-is"],
                ["revise", "Counter"],
                ["pass",   "Pass"],
              ].map(([k, label], i) => (
                <button key={k} onClick={() => setDecision(k)} style={{
                  flex: 1,
                  background: decision === k ? "var(--ink)" : "transparent",
                  color: decision === k ? "var(--bone)" : "var(--ink)",
                  border: "none",
                  borderRight: i < 2 ? "1px solid var(--ink)" : undefined,
                  padding: "14px 12px", fontSize: 11, cursor: "pointer",
                  fontFamily: "'JetBrains Mono', monospace", letterSpacing: "0.12em", textTransform: "uppercase",
                }}>{label}</button>
              ))}
            </div>

            {/* Accept */}
            {decision === "accept" && (
              <div style={{ display: "flex", flexDirection: "column", gap: 24 }}>
                <Field label="Confirmation number" suffix={`${ME.property.name} PMS`} hint="Required to finalise the walk letter.">
                  <Input mono value={confirmation} onChange={e => setConfirmation(e.target.value)} placeholder="WY-882190" />
                </Field>
                <p style={{ fontSize: 13, color: "var(--muted)", lineHeight: 1.6, margin: 0 }}>
                  You're confirming {op.rooms} room{op.rooms>1?"s":""} × {op.nights} night{op.nights>1?"s":""} at {money(op.targetRate || op.myRate)} per night,
                  arriving {op.arrival}.
                </p>
                <Btn full size="lg" disabled={!confirmation} onClick={() => setDecision("done")}>
                  Confirm & return
                </Btn>
              </div>
            )}

            {/* Revise */}
            {decision === "revise" && (
              <div style={{ display: "flex", flexDirection: "column", gap: 24 }}>
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 18 }}>
                  <Field label="Rooms we'll hold">
                    <Stepper value={revisedRooms} onChange={setRevisedRooms} min={1} max={op.rooms} width="100%" />
                  </Field>
                  <Field label="Revised rate">
                    <Input mono value={revisedRate} onChange={e => setRevisedRate(e.target.value.replace(/[^0-9]/g,""))} />
                  </Field>
                </div>
                <Field label="Confirmation number" suffix="Returned with counter">
                  <Input mono value={confirmation} onChange={e => setConfirmation(e.target.value)} placeholder="WY-882190" />
                </Field>
                <p style={{ fontSize: 13, color: "var(--muted)", lineHeight: 1.6, margin: 0 }}>
                  Sender will see the counter immediately. If they accept, the walk letter is generated with these terms.
                </p>
                <Btn full size="lg" disabled={!confirmation} onClick={() => setDecision("done")}>
                  Return counter
                </Btn>
              </div>
            )}

            {/* Pass */}
            {decision === "pass" && (
              <div style={{ display: "flex", flexDirection: "column", gap: 24 }}>
                <p style={{ fontSize: 14, color: "var(--ink)", lineHeight: 1.6, margin: 0 }}>
                  Passing this opportunity tells {op.from.name} we can't accept. They'll route to the next partner.
                </p>
                <div>
                  <Caps style={{ marginBottom: 12 }}>Reason (optional)</Caps>
                  <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                    {["Sold out","Rate too low","Wrong date","Other"].map(r => (
                      <button key={r} style={{
                        textAlign: "left", padding: "12px 16px",
                        background: "transparent", border: "1px solid var(--ink)",
                        fontSize: 13, cursor: "pointer", color: "var(--ink)",
                      }}>{r}</button>
                    ))}
                  </div>
                </div>
                <Btn full size="lg" kind="danger" onClick={() => setDecision("done")}>
                  Pass on this walk
                </Btn>
              </div>
            )}

            {/* Initial state — nudge */}
            {!decision && (
              <div style={{ padding: "40px 24px", textAlign: "center", border: "1px dashed var(--rule-strong)" }}>
                <Caps>Pick one above</Caps>
                <div className="serif-i" style={{ fontSize: 24, marginTop: 14, color: "var(--muted)" }}>
                  Accept as offered, counter with new terms, or pass.
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
    );
  }

  function Row({ k, v }) {
    return (
      <div style={{
        display: "grid", gridTemplateColumns: "160px 1fr",
        padding: "16px 0",
        borderBottom: "1px solid var(--rule)",
        alignItems: "baseline", gap: 16,
      }}>
        <Caps>{k}</Caps>
        <div style={{ fontSize: 16 }}>{v}</div>
      </div>
    );
  }

  const responsiveCSS = `
    @media (max-width: 1000px) {
      .incoming-grid { grid-template-columns: 1fr !important; gap: 8px !important; padding: 20px 0 !important; }
      .detail-cols { grid-template-columns: 1fr !important; }
      .detail-cols > *:first-child { border-right: none !important; border-bottom: 1px solid var(--rule); }
    }
  `;

  function WrappedList() {
    return (<><style>{responsiveCSS}</style><IncomingList /></>);
  }
  function WrappedDetail(props) {
    return (<><style>{responsiveCSS}</style><IncomingDetail {...props} /></>);
  }

  window.Screens = window.Screens || {};
  window.Screens.IncomingList = WrappedList;
  window.Screens.IncomingDetail = WrappedDetail;
})();
