// Hotel Walks — the Walk Letter document.
// Three copies (Guest / Hotel / Emailed). First print is clean; subsequent
// prints are watermarked DUPLICATE COPY. Includes:
//   - sending hotel letterhead
//   - guest details + receiving hotel
//   - negotiated rate (on the emailed copy only)
//   - serial number  [arrival]-[guest initial]-[sending]-[receiving]-[global #]
//   - agent + authorized signatures
//
// LettersList is a thin index that lists the walks that have letters.

(function() {
  const { useState, useEffect } = React;
  const { Caps, Btn, Pill, Hr, money } = window.UI;
  const { SmartKey, Lockup } = window.HW;
  const { SENT, HOTEL_BY_ID, ME } = window.HW_DATA;

  const COPY_LABELS = {
    guest:   "Guest copy",
    hotel:   "Hotel copy",
    emailed: "Emailed copy",
  };
  // Only the emailed copy explicitly includes the negotiated rate.
  const showsRate = (kind) => kind === "emailed" || kind === "hotel";

  /* ───────── Letters list ───────── */
  function LettersList() {
    return (
      <div data-screen-label="Letters" style={{ background: "var(--paper)" }}>
        <div style={{ padding: "44px 48px 24px" }}>
          <Caps>Walk letters</Caps>
          <div className="serif-i" style={{ fontSize: 52, lineHeight: 1, marginTop: 12 }}>Documents generated.</div>
          <p className="page-intro" style={{ marginTop: 14, color: "var(--muted)", fontSize: 15 }}>
            One serial per walk. Reprints are watermarked DUPLICATE COPY and the certificate cannot be redeemed twice.
          </p>
        </div>
        <div style={{ padding: "32px 48px" }}>
          <div className="hw-row-header" style={{ borderTop: "1px solid var(--ink)" }}>
            {SENT.filter(w => w.status === "letter_sent" || w.status === "accepted").map(w => (
              <a key={w.id} href={`#/app/letter/${w.id}`} style={{
                display: "grid", gridTemplateColumns: "1.4fr 1.4fr 130px 220px 110px",
                padding: "24px 0", borderBottom: "1px solid var(--rule)",
                textDecoration: "none", color: "inherit",
                alignItems: "center", gap: 16,
              }} className="letters-row hw-row">
                <div>
                  <div className="row-name">{w.guest.name}</div>
                  <div className="mono" style={{ fontSize: 12, color: "var(--muted)", marginTop: 4 }}>{w.guest.confirmation}</div>
                </div>
                <div>
                  <div className="row-name" style={{ fontSize: 15 }}>{w.to?.name || "—"}</div>
                  <div className="row-sub" style={{ fontSize: 12, marginTop: 2 }}>{w.to?.area}</div>
                </div>
                <div className="mono" style={{ fontSize: 14 }}>{w.rate ? money(w.rate) : "—"}</div>
                <div className="mono" style={{ fontSize: 11, color: "var(--muted)" }}>{w.serial || "pending"}</div>
                <div style={{ textAlign: "right" }}>
                  {w.status === "letter_sent" ? <Pill tone="filled">Sent</Pill> : <Pill tone="muted">Draft</Pill>}
                </div>
              </a>
            ))}
          </div>
        </div>
      </div>
    );
  }

  /* ───────── The document ───────── */
  function WalkLetter({ id }) {
    const walk = SENT.find(w => w.id === id) || SENT[1]; // fallback to accepted demo
    const [copyKind, setCopyKind] = useState("guest");
    // Per-walk print count → triggers DUPLICATE watermark after first print.
    const printKey = "hw_letter_prints_" + walk.id;
    const [printCount, setPrintCount] = useState(() => Number(localStorage.getItem(printKey) || 0));
    const isDuplicate = printCount > 0;

    const onPrint = () => {
      const n = printCount + 1;
      setPrintCount(n);
      localStorage.setItem(printKey, String(n));
      setTimeout(() => window.print(), 100);
    };

    return (
      <div data-screen-label="Walk letter">
        {/* Toolbar */}
        <div className="no-print letter-toolbar" style={{
          padding: "20px 48px",
          borderBottom: "1px solid var(--rule)",
          display: "flex", alignItems: "center", justifyContent: "space-between", gap: 16,
          background: "var(--bone-2)",
          flexWrap: "wrap",
        }}>
          <div style={{ display: "flex", alignItems: "center", gap: 16, flexWrap: "wrap" }}>
            <a href="#/app/letters" style={{ textDecoration: "none", color: "inherit" }}><Caps>← Letters</Caps></a>
            <span style={{ color: "var(--muted)" }}>·</span>
            <Caps>{walk.id}</Caps>
            {isDuplicate && <Pill tone="warn">Duplicate · {printCount}×</Pill>}
          </div>
          <div className="letter-toolbar-actions" style={{ display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap" }}>
            {Object.entries(COPY_LABELS).map(([k, l]) => (
              <button key={k} onClick={() => setCopyKind(k)} style={{
                background: copyKind === k ? "var(--ink)" : "transparent",
                color: copyKind === k ? "var(--bone)" : "var(--ink)",
                border: "1px solid var(--ink)",
                padding: "9px 14px", fontSize: 11, cursor: "pointer",
                fontFamily: "'JetBrains Mono', monospace", letterSpacing: "0.12em", textTransform: "uppercase",
                whiteSpace: "nowrap",
              }}>{l}</button>
            ))}
            <a href={`#/guest/${walk.id}`} target="_blank" style={{ textDecoration: "none" }}>
              <Btn size="sm" kind="ghost">Guest view ↗</Btn>
            </a>
            <Btn size="sm" kind="ghost" onClick={() => { localStorage.removeItem(printKey); setPrintCount(0); }}>Reset</Btn>
            <Btn size="sm" onClick={onPrint}>Print →</Btn>
          </div>
        </div>

        {/* Document */}
        <div style={{ padding: "48px 0", background: "var(--bone-2)" }} className="letter-stage">
          <Letter walk={walk} copyKind={copyKind} isDuplicate={isDuplicate} />
        </div>
      </div>
    );
  }

  function Letter({ walk, copyKind, isDuplicate }) {
    const { guest, to: receiver, serial, rate, rateOffered } = walk;
    const me = ME.property;

    return (
      <article style={{
        width: "min(820px, calc(100vw - 64px))",
        margin: "0 auto",
        background: "white",
        color: "#0d0d0d",
        padding: "64px 72px 56px",
        boxShadow: "0 30px 80px rgba(0,0,0,0.18)",
        position: "relative",
        overflow: "hidden",
      }}>
        {/* DUPLICATE watermark */}
        {isDuplicate && (
          <div style={{
            position: "absolute", top: 0, left: 0, right: 0, bottom: 0,
            display: "flex", alignItems: "center", justifyContent: "center",
            pointerEvents: "none", zIndex: 1,
          }}>
            <div style={{
              transform: "rotate(-22deg)",
              fontFamily: "'JetBrains Mono', monospace",
              fontSize: 110, letterSpacing: "0.18em",
              color: "rgba(184,70,42,0.13)",
              fontWeight: 500, whiteSpace: "nowrap",
            }}>DUPLICATE COPY</div>
          </div>
        )}

        <div style={{ position: "relative", zIndex: 2 }}>
          {/* Letterhead */}
          <header style={{ display: "flex", alignItems: "center", justifyContent: "space-between", paddingBottom: 28, borderBottom: "1px solid rgba(13,13,13,0.18)" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 16 }}>
              <SmartKey size={56} fg="#f4eedd" bg="#0d0d0d" />
              <div style={{ lineHeight: 1.1 }}>
                <div className="serif-i" style={{ fontSize: 28, color: "#0d0d0d" }}>{me.name}</div>
                <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 10, letterSpacing: "0.16em", textTransform: "uppercase", color: "#807a6d", marginTop: 6 }}>{me.area}</div>
              </div>
            </div>
            <div style={{ textAlign: "right" }}>
              <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 10, letterSpacing: "0.16em", textTransform: "uppercase", color: "#807a6d" }}>Walk letter · {COPY_LABELS[copyKind]}</div>
              <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 11, color: "#0d0d0d", marginTop: 8 }}>
                Issued {new Date().toLocaleDateString(undefined, { month: "long", day: "numeric", year: "numeric" })}
              </div>
            </div>
          </header>

          {/* Salutation */}
          <section style={{ padding: "40px 0 28px" }}>
            <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 10, letterSpacing: "0.16em", textTransform: "uppercase", color: "#807a6d" }}>For the guest of</div>
            <div className="serif-i" style={{ fontSize: 48, marginTop: 14, lineHeight: 1, color: "#0d0d0d" }}>{guest.name}</div>
          </section>

          {/* Body copy */}
          <section style={{ fontSize: 14, lineHeight: 1.7, color: "#0d0d0d", paddingBottom: 32 }}>
            {copyKind === "guest" && (
              <p style={{ margin: 0 }}>
                On behalf of {me.name}, please accept our apology for the inconvenience.
                Due to circumstances beyond our control we are unable to honor your reservation tonight.
                We have arranged for accommodations at the receiving property below.
                Please present this letter on arrival.
              </p>
            )}
            {copyKind === "hotel" && (
              <p style={{ margin: 0 }}>
                Internal record of relocation. This certificate represents a single, non-transferable
                obligation. {me.name} will reimburse the receiving property per the rate negotiated below.
              </p>
            )}
            {copyKind === "emailed" && (
              <p style={{ margin: 0 }}>
                To the front office at {receiver?.name || "the receiving property"} — please honor the
                accommodations described below for the named guest. The negotiated nightly rate is
                included for billing reference. Please return a confirmation number to the sending property.
              </p>
            )}
          </section>

          {/* Details grid */}
          <section style={{ borderTop: "1px solid rgba(13,13,13,0.18)", borderBottom: "1px solid rgba(13,13,13,0.18)" }}>
            <Row left={["Re-housed at", receiver?.name || "—"]} right={["Arrival", guest.arrival]} />
            <Row left={["Address", receiver?.area || "—"]} right={["Nights", String(guest.nights)]} />
            <Row left={["Party", `${guest.party} guest${guest.party>1?"s":""}`]} right={["Sending confirmation", guest.confirmation]} />
            {showsRate(copyKind) && (
              <Row
                left={["Negotiated rate", money(rate || rateOffered)]}
                right={["Coverage", "Room + tax · transportation · parking"]}
              />
            )}
            {!showsRate(copyKind) && (
              <Row
                left={["", ""]}
                right={["Coverage", "Room + tax · transportation · parking"]}
              />
            )}
          </section>

          {/* Liability blurb */}
          <section style={{ padding: "24px 0", borderBottom: "1px solid rgba(13,13,13,0.18)" }}>
            <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 10, letterSpacing: "0.16em", textTransform: "uppercase", color: "#807a6d", marginBottom: 12 }}>Liability</div>
            <p style={{ margin: 0, fontSize: 12, lineHeight: 1.6, color: "#807a6d", maxWidth: "62ch" }}>
              Hotel Walks operates strictly as a communication layer between properties. Contract of
              service and liabilities rest between the providing entity / property and the sending entity / property.
            </p>
          </section>

          {/* Signatures */}
          <section style={{ paddingTop: 40, paddingBottom: 24, display: "grid", gridTemplateColumns: "1fr 1fr", gap: 56 }}>
            <Signature label="Agent" name={ME.user.name} sub={`${me.name} · ${ME.user.shift} shift`} />
            <Signature label="Authorized hotel signature" name="J. Reyes" sub="Front Office Manager" />
          </section>

          {/* Serial */}
          <footer style={{ paddingTop: 28, borderTop: "1px solid rgba(13,13,13,0.18)", display: "flex", justifyContent: "space-between", alignItems: "baseline", gap: 16, flexWrap: "wrap" }}>
            <div>
              <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 10, letterSpacing: "0.16em", textTransform: "uppercase", color: "#807a6d" }}>Certificate · serial</div>
              <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 14, letterSpacing: "0.08em", color: "#0d0d0d", marginTop: 8 }}>
                {serial || (() => {
                  const dt = guest.arrival.replace(/-/g,"").slice(2);
                  const init = guest.name.split(" ").slice(-1)[0][0];
                  return `${dt}-${init}-${me.id}-${receiver?.id || "PEND"}-0027841`;
                })()}
              </div>
            </div>
            <div style={{ textAlign: "right" }}>
              <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 10, letterSpacing: "0.16em", textTransform: "uppercase", color: "#807a6d" }}>One-time redemption</div>
              <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 11, color: "#0d0d0d", marginTop: 8 }}>
                Verified · not yet redeemed
              </div>
            </div>
          </footer>
        </div>
      </article>
    );
  }

  function Row({ left, right }) {
    return (
      <div style={{
        display: "grid", gridTemplateColumns: "1fr 1fr",
        gap: 40,
        padding: "18px 0",
        borderBottom: "1px dashed rgba(13,13,13,0.10)",
      }}>
        <Cell k={left[0]} v={left[1]} />
        <Cell k={right[0]} v={right[1]} />
      </div>
    );
  }
  function Cell({ k, v }) {
    if (!k && !v) return <div />;
    return (
      <div>
        <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 10, letterSpacing: "0.16em", textTransform: "uppercase", color: "#807a6d", marginBottom: 6 }}>{k}</div>
        <div className="serif-i" style={{ fontSize: 22, color: "#0d0d0d", lineHeight: 1.2 }}>{v}</div>
      </div>
    );
  }
  function Signature({ label, name, sub }) {
    return (
      <div>
        <div style={{
          height: 56, borderBottom: "1px solid #0d0d0d",
          display: "flex", alignItems: "flex-end", paddingBottom: 6,
        }}>
          <span className="serif-i" style={{ fontSize: 28, color: "#0d0d0d", transform: "rotate(-3deg)" }}>{name}</span>
        </div>
        <div style={{ marginTop: 10, display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
          <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 10, letterSpacing: "0.16em", textTransform: "uppercase", color: "#807a6d" }}>{label}</div>
          <div style={{ fontSize: 12, color: "#807a6d" }}>{sub}</div>
        </div>
      </div>
    );
  }

  const responsiveCSS = `
    @media (max-width: 700px) {
      .letters-row { grid-template-columns: 1fr 1fr !important; gap: 8px !important; }
      .letters-row > *:nth-child(n+3) { grid-column: span 2; }
      .letter-toolbar { padding: 14px 18px !important; }
      .letter-toolbar-actions { width: 100%; justify-content: flex-start; }
      .letter-stage { padding: 28px 0 !important; }
      .letter-stage article { padding: 36px 24px 32px !important; }
      .letter-stage article header { flex-direction: column !important; align-items: flex-start !important; gap: 16px; }
      .letter-stage article header > div:last-child { text-align: left !important; }
      .letter-stage article section[style*="grid-template-columns: 1fr 1fr"] { grid-template-columns: 1fr !important; gap: 24px !important; }
    }
    @media print {
      .letter-stage { background: white !important; padding: 0 !important; }
      .letter-stage article { box-shadow: none !important; width: 100% !important; padding: 24px 32px !important; }
    }
  `;

  function WrappedLetter(props) {
    return (<><style>{responsiveCSS}</style><WalkLetter {...props} /></>);
  }
  function WrappedList() {
    return (<><style>{responsiveCSS}</style><LettersList /></>);
  }

  window.Screens = window.Screens || {};
  window.Screens.WalkLetter = WrappedLetter;
  window.Screens.LettersList = WrappedList;
})();
