/* ============================================================
   FacilityOS — Facilities screen (card grid)
   ============================================================ */
window.Screens = window.Screens || {};

const FAC_TYPE_TOKEN = { HOA: "--c-done", School: "--c-info", Hospital: "--c-critical", Apartment: "--c-violet", "Multi-family": "--c-medium" };

Screens.Facilities = function Facilities({ go, search }) {
  const DB = window.DB;
  const { Card, Button, IconButton } = UI;
  const [type, setType] = useState("all");
  const q = (search || "").toLowerCase();

  const types = ["all", ...Array.from(new Set(DB.facilities.map((f) => f.type)))];
  const list = DB.facilities.filter((f) =>
    (type === "all" || f.type === type) &&
    (!q || f.name.toLowerCase().includes(q) || f.address.toLowerCase().includes(q))
  );

  const openWO = (fid) => DB.workOrders.filter((w) => w.facility === fid && w.status !== "completed").length;
  const assetCount = (fid) => DB.assets.filter((a) => a.facility === fid).length;
  const critical = (fid) => DB.workOrders.filter((w) => w.facility === fid && w.priority === "critical" && w.status !== "completed").length;

  return (
    <div className="page fade-up">
      {/* filter chips + add */}
      <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 18, flexWrap: "wrap" }}>
        <div style={{ display: "flex", gap: 7, flexWrap: "wrap" }}>
          {types.map((t) => {
            const on = type === t;
            const tok = t === "all" ? "--accent" : FAC_TYPE_TOKEN[t];
            return (
              <button key={t} onClick={() => setType(t)} style={{
                display: "inline-flex", alignItems: "center", gap: 7, padding: "7px 13px", borderRadius: 999, cursor: "pointer",
                fontSize: 13, fontWeight: 600, transition: "all .15s ease",
                color: on ? `var(${tok})` : "var(--text-muted)",
                background: on ? UI.tint(tok, 13) : "var(--surface)",
                border: `1px solid ${on ? UI.tint(tok, 32) : "var(--border)"}`,
              }}>
                {t !== "all" && <span style={{ width: 7, height: 7, borderRadius: 99, background: `var(${tok})` }} />}
                {t === "all" ? "All facilities" : t}
              </button>
            );
          })}
        </div>
        <Button variant="primary" icon="plus" style={{ marginLeft: "auto" }}>Add Facility</Button>
      </div>

      <div className="fac-grid" style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(316px, 1fr))", gap: 18 }}>
        {list.map((f) => {
          const tok = FAC_TYPE_TOKEN[f.type];
          const crit = critical(f.id);
          return (
            <Card key={f.id} pad={false} hover onClick={() => go("assets", { facility: f.id })} style={{ overflow: "hidden", display: "flex", flexDirection: "column" }}>
              {/* photo */}
              <div style={{ position: "relative", aspectRatio: "16/8", background: `repeating-linear-gradient(135deg, var(--surface-3), var(--surface-3) 11px, color-mix(in oklch, var(${tok}) 9%, var(--surface-3)) 11px, color-mix(in oklch, var(${tok}) 9%, var(--surface-3)) 22px)`, display: "flex", alignItems: "center", justifyContent: "center" }}>
                <Icon name="building" size={34} style={{ color: `color-mix(in oklch, var(${tok}) 55%, var(--text-faint))`, opacity: 0.6 }} />
                <span style={{ position: "absolute", top: 12, left: 12, display: "inline-flex", alignItems: "center", gap: 6, padding: "4px 10px", borderRadius: 999, fontSize: 11.5, fontWeight: 700, color: `var(${tok})`, background: "var(--surface)", border: `1px solid ${UI.tint(tok, 30)}`, boxShadow: "var(--shadow-xs)" }}>
                  <span style={{ width: 6, height: 6, borderRadius: 99, background: `var(${tok})` }} />{f.type}
                </span>
                <span className="mono" style={{ position: "absolute", bottom: 12, right: 12, fontSize: 10, color: "var(--text-faint)", background: "color-mix(in oklch, var(--surface) 70%, transparent)", padding: "2px 7px", borderRadius: 5 }}>facility photo</span>
              </div>

              <div style={{ padding: "calc(var(--pad) * 1.1)", display: "flex", flexDirection: "column", gap: 14, flex: 1 }}>
                <div>
                  <h3 style={{ margin: 0, fontSize: 16, fontWeight: 700, letterSpacing: "-.01em", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{f.name}</h3>
                  <div style={{ marginTop: 5, display: "flex", alignItems: "center", gap: 6, fontSize: 12.5, color: "var(--text-faint)" }}>
                    <Icon name="mapPin2" size={14} /><span style={{ whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{f.address}</span>
                  </div>
                </div>

                <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 1, background: "var(--border)", borderRadius: "var(--radius-sm)", overflow: "hidden", marginTop: "auto" }}>
                  {[
                    { label: "Locations", val: f.locations, icon: "layers", tone: "--text-muted" },
                    { label: "Open WOs", val: openWO(f.id), icon: "wrench", tone: openWO(f.id) > 6 ? "--c-high" : "--text-muted" },
                    { label: "Assets", val: assetCount(f.id), icon: "box", tone: "--text-muted" },
                  ].map((s) => (
                    <div key={s.label} style={{ background: "var(--surface-2)", padding: "11px 12px" }}>
                      <div className="tnum" style={{ fontSize: 19, fontWeight: 700, color: `var(${s.tone})` }}>{s.val}</div>
                      <div style={{ fontSize: 11, color: "var(--text-faint)", fontWeight: 500, marginTop: 1 }}>{s.label}</div>
                    </div>
                  ))}
                </div>

                <div style={{ display: "flex", alignItems: "center", gap: 8, minHeight: 22 }}>
                  {crit > 0 ? (
                    <span style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 12, fontWeight: 600, color: "var(--c-critical)", background: UI.tint("--c-critical", 12), padding: "3px 9px", borderRadius: 999 }}>
                      <Icon name="alert" size={13} />{crit} critical open
                    </span>
                  ) : (
                    <span style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 12, fontWeight: 600, color: "var(--c-done)" }}>
                      <Icon name="check" size={14} stroke={2.5} />All clear
                    </span>
                  )}
                  <Icon name="chevRight" size={17} style={{ marginLeft: "auto", color: "var(--text-faint)" }} />
                </div>
              </div>
            </Card>
          );
        })}
      </div>
    </div>
  );
};
window.FAC_TYPE_TOKEN = FAC_TYPE_TOKEN;
