// Hotel Walks — Invoice dashboard.
// Listing (sending) vs Accepts (receiving) rows. No-show toggle ONLY appears
// on receiving lines. Period switcher, status filter, totals.

(function() {
  const { useState, useMemo } = React;
  const { Caps, Btn, Pill, Toggle, Hr, money } = window.UI;
  const { INVOICE_ROWS, INVOICE_PERIOD, HOTEL_BY_ID, ME } = window.HW_DATA;

  function Invoices() {
    const [rows, setRows] = useState(INVOICE_ROWS);
    const [filter, setFilter] = useState("all"); // all | listing | accepts | open

    const filtered = useMemo(() => {
      if (filter === "all")     return rows;
      if (filter === "listing") return rows.filter(r => r.side === "Listing");
      if (filter === "accepts") return rows.filter(r => r.side === "Accepts");
      if (filter === "open")    return rows.filter(r => r.status === "open");
      return rows;
    }, [rows, filter]);

    const totals = useMemo(() => {
      let listed = 0, accepted = 0, fees = 0, commission = 0;
      rows.forEach(r => {
        const due = r.fee + (r.noShow ? 0 : r.commission); // no-show waives commission, not the $4 fee
        if (r.side === "Listing") listed += due;
        else accepted += due;
        fees += r.fee;
        if (!r.noShow) commission += r.commission;
      });
      return { listed, accepted, fees, commission, gross: listed + accepted };
    }, [rows]);

    const toggleNoShow = (id) => {
      setRows(prev => prev.map(r => r.id === id ? { ...r, noShow: !r.noShow } : r));
    };

    return (
      <div data-screen-label="Invoices" style={{ background: "var(--paper)" }}>
        <div>
          <div className="pad-lg" style={{ padding: "44px 48px 28px", borderBottom: "1px solid var(--rule)" }}>
            <div className="inv-head" style={{ display: "grid", gridTemplateColumns: "1fr auto", gap: 24, alignItems: "end" }}>
              <div>
                <Caps>Invoices · period {INVOICE_PERIOD.id}</Caps>
                <div className="serif-i page-title" style={{ fontSize: 52, lineHeight: 1, marginTop: 12 }}>
                  {INVOICE_PERIOD.label}
                </div>
                <p className="page-intro" style={{ marginTop: 14, color: "var(--muted)", fontSize: 15 }}>
                  $4 + 10% per side. No-shows can only be marked on the receiving line — sending hotels cannot dispute attendance.
                </p>
              </div>
              <div className="inv-head-ctas" style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
                <Btn kind="ghost" size="sm">Export CSV</Btn>
                <Btn size="sm">Settle period</Btn>
              </div>
            </div>
          </div>

          {/* Stat strip — content inset to page padding so cells align with the head */}
          <div style={{ borderBottom: "1px solid var(--rule)" }} className="invoice-stats-wrap">
            <div className="invoice-stats" style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", padding: "0 48px" }}>
              <StatCell label="As listing · owed by us" value={money(totals.listed)} idx={0} count={4} />
              <StatCell label="As accepts · owed to us" value={money(totals.accepted)} positive idx={1} count={4} />
              <StatCell label="Platform fees ($4 ×)" value={money(totals.fees)} idx={2} count={4} />
              <StatCell label="Net commissions" value={money(totals.commission)} idx={3} count={4} />
            </div>
          </div>
        </div>

        {/* Filters */}
        <div className="pad-md inv-filters" style={{ padding: "24px 48px", display: "flex", gap: 16, alignItems: "center", justifyContent: "space-between", flexWrap: "wrap" }}>
          <div style={{ display: "flex", gap: 4, flexWrap: "wrap" }}>
            {[
              ["all",     "All"],
              ["listing", "Listing (sent)"],
              ["accepts", "Accepts (received)"],
              ["open",    "Open only"],
            ].map(([k, l]) => (
              <button key={k} onClick={() => setFilter(k)} style={{
                background: filter === k ? "var(--ink)" : "transparent",
                color: filter === 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>
            ))}
          </div>
          <Caps>{filtered.length} rows</Caps>
        </div>

        {/* Table */}
        <div className="pad-md" style={{ padding: "0 48px 48px" }}>
          <div className="inv-grid hw-row-header" style={{
            display: "grid",
            gridTemplateColumns: "70px 90px 90px 1.2fr 1.4fr 90px 100px 110px 130px",
            padding: "12px 0",
            borderTop: "1px solid var(--ink)",
            borderBottom: "1px solid var(--rule)",
          }}>
            {["Date","Invoice","Side","Guest","Partner","Rate","Fee","Commission","Status / No-show"].map((h, i) => (
              <div key={i}><Caps>{h}</Caps></div>
            ))}
          </div>

          {filtered.map(r => {
            const partner = HOTEL_BY_ID[r.to || r.from];
            const isAccepts = r.side === "Accepts";
            const commission = r.noShow ? 0 : r.commission;
            return (
              <div key={r.id} className="inv-grid hw-row" style={{
                display: "grid",
                gridTemplateColumns: "70px 90px 90px 1.2fr 1.4fr 90px 100px 110px 130px",
                padding: "18px 0",
                borderBottom: "1px solid var(--rule)",
                alignItems: "center", gap: 8,
              }}>
                <div className="mono" style={{ fontSize: 12 }}>{r.date}</div>
                <div className="mono" style={{ fontSize: 11, color: "var(--muted)" }}>{r.id.replace("INV-","")}</div>
                <div>
                  <Pill tone={isAccepts ? "good" : "neutral"}>{r.side}</Pill>
                </div>
                <div>
                  <div style={{ fontSize: 15 }}>{r.guest}</div>
                  <div className="mono" style={{ fontSize: 11, color: "var(--muted)", marginTop: 4 }}>{r.serial}</div>
                </div>
                <div>
                  <div className="row-name" style={{ fontSize: 15 }}>{partner.name}</div>
                  <div className="row-sub" style={{ fontSize: 12, marginTop: 2 }}>{isAccepts ? "from" : "to"} · {partner.area}</div>
                </div>
                <div className="mono" style={{ fontSize: 14 }}>{money(r.rate)}</div>
                <div className="mono" style={{ fontSize: 14 }}>{money(r.fee)}</div>
                <div className="mono" style={{ fontSize: 14, textDecoration: r.noShow ? "line-through" : "none", color: r.noShow ? "var(--muted)" : "var(--ink)" }}>
                  {money(commission)}
                </div>
                <div style={{ display: "flex", flexDirection: "column", gap: 6, alignItems: "flex-start" }}>
                  {r.status === "paid"
                    ? <Pill tone="muted">Paid</Pill>
                    : <Pill tone="warn">Open</Pill>}
                  {isAccepts && (
                    <Toggle
                      on={r.noShow}
                      onChange={() => toggleNoShow(r.id)}
                      label={<span style={{ fontSize: 11, fontFamily: "'JetBrains Mono', monospace", letterSpacing: "0.12em", textTransform: "uppercase" }}>{r.noShow ? "No-show" : "Mark no-show"}</span>}
                    />
                  )}
                </div>
              </div>
            );
          })}

          {/* Footer totals row */}
          <div className="inv-grid hw-row-header" style={{
            display: "grid",
            gridTemplateColumns: "70px 90px 90px 1.2fr 1.4fr 90px 100px 110px 130px",
            padding: "24px 0",
            borderTop: "1px solid var(--ink)",
            alignItems: "baseline",
            gap: 8,
          }}>
            <div />
            <div />
            <div />
            <div />
            <div style={{ textAlign: "right" }}><Caps>Period gross</Caps></div>
            <div />
            <div className="mono" style={{ fontSize: 14 }}>{money(totals.fees)}</div>
            <div className="mono" style={{ fontSize: 14 }}>{money(totals.commission)}</div>
            <div className="serif-i" style={{ fontSize: 24 }}>{money(totals.gross)}</div>
          </div>
        </div>
      </div>
    );
  }

  function StatCell({ label, value, positive, idx = 0, count = 1 }) {
    const isFirst = idx === 0;
    const isLast = idx === count - 1;
    return (
      <div style={{
        padding: `28px ${isLast ? 0 : 32}px 32px ${isFirst ? 0 : 32}px`,
        borderRight: !isLast ? "1px solid var(--rule)" : undefined,
      }}>
        <Caps>{label}</Caps>
        <div className="serif-i" style={{
          fontSize: 36, marginTop: 14, lineHeight: 1,
          color: positive ? "var(--good)" : "var(--ink)",
        }}>{value}</div>
      </div>
    );
  }

  const responsiveCSS = `
    @media (max-width: 1100px) {
      .invoice-stats { grid-template-columns: 1fr 1fr !important; }
      .invoice-stats > div:nth-child(2) { border-right: none !important; }
      .invoice-stats > div:nth-child(n+3) { border-top: 1px solid var(--rule); }
    }
    @media (max-width: 900px) {
      .inv-grid { grid-template-columns: 1fr !important; gap: 8px !important; padding: 18px 0 !important; }
    }
    @media (max-width: 720px) {
      .inv-head { grid-template-columns: 1fr !important; gap: 16px !important; }
      .inv-head .page-title { font-size: 36px !important; }
      .inv-head-ctas { width: 100%; }
      .inv-head-ctas > * { flex: 1; }
      .invoice-stats { padding: 0 20px !important; grid-template-columns: 1fr 1fr !important; }
      .invoice-stats > div { padding: 18px 0 !important; border-right: none !important; }
      .invoice-stats > div:nth-child(odd) { padding-right: 12px !important; border-right: 1px solid var(--rule) !important; }
      .invoice-stats > div:nth-child(even) { padding-left: 12px !important; }
      .invoice-stats > div .serif-i { font-size: 24px !important; }
      .inv-filters { padding: 16px 20px !important; }
    }
  `;

  function Wrapped() {
    return (<><style>{responsiveCSS}</style><Invoices /></>);
  }

  window.Screens = window.Screens || {};
  window.Screens.Invoices = Wrapped;
})();
