// Hotel Contacts — live, read-only directory synced from the RDB Google Sheet.
// Confirmed headers: City | Hotel | Email | Phone | Address  (grouped by State).
// Data + fetch live in HotelData.jsx (useHotels / groupHotelsByState).

const HOTELS_PER_PAGE = 25;

function HotelContactsPage() {
  const { rows, status } = useHotels();
  const [stateFilter, setStateFilter] = React.useState("All");
  const [search, setSearch] = React.useState("");
  const [collapsed, setCollapsed] = React.useState({});
  const [page, setPage] = React.useState(1);

  const q = search.trim().toLowerCase();
  const filtered = rows.filter(h =>
    (stateFilter === "All" || h.state === stateFilter) &&
    (q === "" || h.hotel.toLowerCase().includes(q) || h.city.toLowerCase().includes(q) || (h.state || "").toLowerCase().includes(q))
  );

  // Pagination — only ~25 rows ever mount at once. Rendering the full national
  // directory at once locked the main thread ("Page Unresponsive"). We paginate
  // the filtered list, then group ONLY the current page's slice by state.
  const pages = Math.max(1, Math.ceil(filtered.length / HOTELS_PER_PAGE));
  // Reset to page 1 whenever the search/filter narrows the set (keeps page in range).
  React.useEffect(() => { setPage(1); }, [q, stateFilter]);
  const safePage = Math.min(page, pages);
  const start = (safePage - 1) * HOTELS_PER_PAGE;
  const pageRows = filtered.slice(start, start + HOTELS_PER_PAGE);

  const groups = groupHotelsByState(pageRows);
  const states = React.useMemo(() => Array.from(new Set(rows.map(h => h.state).filter(Boolean))), [rows]);
  const cities = React.useMemo(() => new Set(rows.map(h => h.city).filter(Boolean)).size, [rows]);

  function toggle(state) { setCollapsed(s => ({ ...s, [state]: !s[state] })); }

  return (
    <div style={{ padding: "48px 64px 96px", maxWidth: 1320, margin: "0 auto" }}>
      <PageHeader
        eyebrow="Backstage · Directory"
        title="Hotel Contacts"
        intro="Partner properties nationwide, grouped by state — reservation emails, direct lines, and addresses, kept current by RDB operations."
      />

      <StatStrip stats={[
        { label: "Properties", value: status === "live" ? String(rows.length) : (status === "loading" ? "…" : String(rows.length)), note: status === "live" ? "Up to date" : status === "sample" ? "Offline sample" : "Syncing…" },
        { label: "States",     value: String(states.length), note: "Coverage" },
        { label: "Cities",     value: String(cities), note: "Markets" },
        { label: "Access",     value: "Read-only", note: "Members only" },
      ]} />

      {/* Controls: sync status · search · state filter */}
      <div style={{ display: "flex", alignItems: "center", gap: 16, marginBottom: 18, flexWrap: "wrap" }}>
        <SyncBadge status={status} />
        <div style={{ marginLeft: "auto", display: "flex", alignItems: "center", gap: 16 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8, borderBottom: "1px solid var(--ink-4)", paddingBottom: 6 }}>
            <Icon name="search" size={15} color="var(--ink-6)" />
            <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Search hotel, city, or state" style={{ background: "transparent", border: "none", outline: "none", color: "var(--fg-1)", fontFamily: "var(--font-body)", fontSize: 13, width: 240 }} />
          </div>
          <select value={stateFilter} onChange={e => setStateFilter(e.target.value)} style={{ background: "transparent", border: "1px solid var(--ink-3)", color: "var(--fg-1)", padding: "9px 12px", fontFamily: "var(--font-body)", fontSize: 12, letterSpacing: "0.04em", borderRadius: 2, cursor: "pointer", outline: "none" }}>
            <option value="All">All states</option>
            {states.map(s => <option key={s} value={s}>{s}</option>)}
          </select>
        </div>
      </div>

      <div style={{ border: "1px solid var(--ink-3)" }}>
        <div style={{ overflowX: "auto" }}>
        <table style={{ width: "100%", borderCollapse: "collapse", minWidth: 980 }}>
          <thead>
            <tr style={{ borderBottom: "1px solid var(--ink-3)", background: "var(--ink-1)" }}>
              <Th style={{ width: 150 }}>City</Th>
              <Th sortable active>Hotel</Th>
              <Th>Email</Th>
              <Th>Phone</Th>
              <Th style={{ minWidth: 240 }}>Address</Th>
            </tr>
          </thead>
          <tbody>
            {groups.length === 0 && (
              <tr><td colSpan={5} style={{ padding: "40px 16px", textAlign: "center", fontFamily: "var(--font-body)", fontSize: 13, color: "var(--ink-6)" }}>No properties match your search.</td></tr>
            )}
            {groups.map(g => (
              <React.Fragment key={g.state}>
                <StateGroupRow state={g.state} count={g.rows.length} open={!collapsed[g.state]} onToggle={() => toggle(g.state)} />
                {!collapsed[g.state] && g.rows.map((h, i) => (
                  <HotelRow key={h.hotel + h.city + i} h={h} last={i === g.rows.length - 1} />
                ))}
              </React.Fragment>
            ))}
          </tbody>
        </table>
        </div>
        <TableFooter
          shown={pageRows.length}
          total={filtered.length}
          page={safePage}
          pages={pages}
          onPrev={() => setPage(p => Math.max(1, p - 1))}
          onNext={() => setPage(p => Math.min(pages, p + 1))}
        />
      </div>
    </div>
  );
}

// Live / syncing / offline indicator.
function SyncBadge({ status }) {
  const map = {
    live:    { color: "var(--success)", text: "Live · read-only" },
    loading: { color: "var(--rdb-gold)", text: "Syncing…" },
    sample:  { color: "var(--ink-6)",   text: "Offline sample · live sync resumes online" },
  };
  const m = map[status] || map.sample;
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 9 }}>
      <span style={{ width: 8, height: 8, borderRadius: "50%", background: m.color, display: "inline-block", animation: status === "loading" ? "rdbpulse 1s ease-in-out infinite" : "none" }} />
      <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--fg-2)", letterSpacing: "0.02em" }}>{m.text}</span>
    </div>
  );
}

// Collapsible state header.
function StateGroupRow({ state, count, open, onToggle }) {
  const [hover, setHover] = React.useState(false);
  return (
    <tr
      onClick={onToggle}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{ background: hover ? "var(--ink-2)" : "var(--ink-1)", cursor: "pointer", borderTop: "1px solid var(--ink-3)", borderBottom: "1px solid var(--ink-3)", transition: "background 160ms" }}
    >
      <td colSpan={5} style={{ padding: "11px 16px" }}>
        <span style={{ display: "inline-flex", alignItems: "center", gap: 10 }}>
          <Icon name={open ? "chevron-down" : "chevron-right"} size={14} color="var(--rdb-gold)" />
          <span style={{ fontFamily: "var(--font-body)", fontWeight: 600, fontSize: 11, letterSpacing: "0.24em", textTransform: "uppercase", color: "var(--rdb-gold)" }}>{state}</span>
          <span style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--ink-6)" }}>{count} {count === 1 ? "property" : "properties"}</span>
        </span>
      </td>
    </tr>
  );
}

function HotelRow({ h, last }) {
  const [hover, setHover] = React.useState(false);
  const isEmail = h.email && h.email.indexOf("@") !== -1;
  return (
    <tr
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        borderBottom: last ? "none" : "1px solid var(--ink-2)",
        background: hover ? "var(--ink-1)" : "transparent",
        transition: "background 160ms cubic-bezier(.22,1,.36,1)",
      }}
    >
      <Td><span style={{ color: "var(--fg-3)", fontSize: 12, whiteSpace: "nowrap" }}>{h.city}</span></Td>
      <Td>
        <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
          <div style={{ width: 32, height: 32, background: "var(--ink-2)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
            <Icon name="bed-double" size={16} color="var(--rdb-gold)" />
          </div>
          <span style={{ fontWeight: 600, color: "var(--fg-1)" }}>{h.hotel}</span>
        </div>
      </Td>
      <Td>{isEmail ? <CopyEmail email={h.email} /> : <span style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--ink-6)" }}>{h.email || "—"}</span>}</Td>
      <Td><span style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--fg-2)", whiteSpace: "nowrap" }}>{h.phone || "—"}</span></Td>
      <Td><span style={{ color: "var(--fg-3)", fontSize: 12, lineHeight: 1.5 }}>{h.address || "—"}</span></Td>
    </tr>
  );
}

Object.assign(window, { HotelContactsPage, SyncBadge });
