/* ============================================================
   FacilityOS — Requests inbox screen
   ============================================================ */
window.Screens = window.Screens || {};

const REQ_STATUS = {
  new:       { label: "New",        token: "--c-info" },
  triaged:   { label: "Triaged",    token: "--c-medium" },
  converted: { label: "Converted",  token: "--c-done" },
};

Screens.Requests = function Requests({ go, search }) {
  const DB = window.DB;
  const { Card, Button, PriorityPill, Avatar, SectionHead } = UI;
  const [filter, setFilter] = useState("all");
  const q = (search || "").toLowerCase();
  const list = DB.requests.filter((r) =>
    (filter === "all" || r.status === filter) &&
    (!q || r.title.toLowerCase().includes(q) || r.id.toLowerCase().includes(q))
  );
  const [activeId, setActiveId] = useState(DB.requests[0].id);
  const active = DB.requests.find((r) => r.id === activeId) || list[0];

  const counts = { all: DB.requests.length, new: DB.requests.filter(r=>r.status==="new").length, triaged: DB.requests.filter(r=>r.status==="triaged").length, converted: DB.requests.filter(r=>r.status==="converted").length };

  return (
    <div className="page fade-up">
      <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 16, flexWrap: "wrap" }}>
        <UI.Segmented value={filter} onChange={setFilter} counts={counts}
          options={[{ key: "all", label: "All" }, { key: "new", label: "New" }, { key: "triaged", label: "Triaged" }, { key: "converted", label: "Converted" }]} />
        <Button variant="primary" icon="plus" style={{ marginLeft: "auto" }}>New Request</Button>
      </div>

      <div className="req-grid" style={{ display: "grid", gridTemplateColumns: "minmax(0,1fr) minmax(0,1.4fr)", gap: 18, alignItems: "start" }}>
        {/* list */}
        <Card pad={false} className="req-list" style={{ overflow: "hidden" }}>
          <div style={{ display: "flex", flexDirection: "column" }}>
            {list.map((r, i) => {
              const f = DB.facById(r.facility);
              const on = r.id === activeId;
              const rs = REQ_STATUS[r.status];
              return (
                <button key={r.id} onClick={() => setActiveId(r.id)} style={{
                  textAlign: "left", display: "flex", gap: 12, padding: "14px 16px", cursor: "pointer",
                  background: on ? UI.tint("--accent", 9) : "transparent", border: "none",
                  borderBottom: i < list.length-1 ? "1px solid var(--border)" : "none",
                  borderLeft: `3px solid ${on ? "var(--accent)" : "transparent"}`, transition: "background .12s",
                }}
                  onMouseEnter={(e)=>{ if(!on) e.currentTarget.style.background="var(--surface-2)"; }}
                  onMouseLeave={(e)=>{ if(!on) e.currentTarget.style.background="transparent"; }}>
                  <span style={{ width: 36, height: 36, borderRadius: "var(--radius-sm)", flex: "0 0 auto", display: "flex", alignItems: "center", justifyContent: "center", background: UI.tint(DB.PRIORITY[r.priority].token, 14), color: `var(${DB.PRIORITY[r.priority].token})` }}>
                    <Icon name={catIcon(r.category)} size={18} />
                  </span>
                  <div style={{ minWidth: 0, flex: 1 }}>
                    <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                      {r.status === "new" && <span style={{ width: 7, height: 7, borderRadius: 99, background: "var(--c-info)", flex: "0 0 auto" }} />}
                      <span style={{ fontSize: 13.5, fontWeight: 650, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{r.title}</span>
                    </div>
                    <div style={{ fontSize: 12, color: "var(--text-faint)", marginTop: 2, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{r.unit}</div>
                    <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 7 }}>
                      <PriorityPill priority={r.priority} />
                      <span style={{ fontSize: 11.5, color: "var(--text-faint)", marginLeft: "auto" }}>{r.submitted}</span>
                    </div>
                  </div>
                </button>
              );
            })}
            {list.length === 0 && <div style={{ padding: 40, textAlign: "center", color: "var(--text-faint)", fontSize: 13 }}>No requests in this view.</div>}
          </div>
        </Card>

        {/* detail */}
        {active && (
          <Card key={active.id} className="req-detail" style={{ animation: "fadeIn .2s ease" }}>
            <div style={{ display: "flex", alignItems: "flex-start", gap: 12, marginBottom: 18 }}>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 9, marginBottom: 7, flexWrap: "wrap" }}>
                  <span className="mono" style={{ fontSize: 12, fontWeight: 600, color: "var(--text-faint)" }}>{active.id}</span>
                  <span style={{ display: "inline-flex", alignItems: "center", gap: 5, fontSize: 11.5, fontWeight: 600, padding: "2px 9px", borderRadius: 99, color: `var(${REQ_STATUS[active.status].token})`, background: UI.tint(REQ_STATUS[active.status].token, 14) }}>{REQ_STATUS[active.status].label}</span>
                  <PriorityPill priority={active.priority} />
                </div>
                <h2 style={{ margin: 0, fontSize: 20, fontWeight: 700, letterSpacing: "-.02em", lineHeight: 1.25 }}>{active.title}</h2>
              </div>
            </div>

            <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(150px,1fr))", gap: 1, background: "var(--border)", borderRadius: "var(--radius-sm)", overflow: "hidden", marginBottom: 18 }}>
              {[
                { icon: "user", label: "Submitted by", val: active.name },
                { icon: "pin", label: "Location", val: active.unit },
                { icon: "box", label: "Category", val: active.category },
                { icon: "clock", label: "Submitted", val: active.submitted },
              ].map((m) => (
                <div key={m.label} style={{ background: "var(--surface-2)", padding: "12px 14px" }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 6, fontSize: 11.5, color: "var(--text-faint)", fontWeight: 500, marginBottom: 4 }}><Icon name={m.icon} size={13} />{m.label}</div>
                  <div style={{ fontSize: 13, fontWeight: 600, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{m.val}</div>
                </div>
              ))}
            </div>

            <SectionHead title="Description" />
            <p style={{ margin: "0 0 8px", fontSize: 14, lineHeight: 1.65, color: "var(--text-muted)", textWrap: "pretty" }}>{active.desc}</p>

            {/* submitted photo placeholder */}
            <div style={{ marginTop: 14, display: "flex", gap: 12 }}>
              <div style={{ width: 130, aspectRatio: "4/3", borderRadius: "var(--radius-sm)", border: "1px solid var(--border)", background: `repeating-linear-gradient(135deg, var(--surface-3), var(--surface-3) 9px, color-mix(in oklch, var(--accent) 8%, var(--surface-3)) 9px, color-mix(in oklch, var(--accent) 8%, var(--surface-3)) 18px)`, display: "flex", flexDirection: "column", gap: 4, alignItems: "center", justifyContent: "center", color: "var(--text-faint)" }}>
                <Icon name="photo" size={22} />
                <span className="mono" style={{ fontSize: 10 }}>tenant photo</span>
              </div>
            </div>

            {/* triage actions */}
            <div style={{ marginTop: 22, paddingTop: 18, borderTop: "1px solid var(--border)", display: "flex", gap: 10, flexWrap: "wrap" }}>
              <Button variant="primary" icon="wrench" onClick={() => go("work-orders")}>Convert to Work Order</Button>
              <Button variant="default" icon="user">Assign tech</Button>
              <Button variant="soft" icon="note">Reply</Button>
              <Button variant="ghost" icon="x" style={{ marginLeft: "auto" }}>Dismiss</Button>
            </div>
          </Card>
        )}
      </div>
    </div>
  );
};

function catIcon(cat) {
  return ({ HVAC: "gauge", Plumbing: "drop", Electrical: "zap", "Access Control": "shield", Structural: "building", Landscape: "pin", "Fire Safety": "flame", Refrigeration: "box", Janitorial: "clipboard" })[cat] || "wrench";
}
window.catIcon = catIcon;
