// Woodbury Operator — Tenants list. Registers window.TenantsScreen.
(function () {
  const NS = window.WoodburyPropertiesDesignSystem_7290ca;
  const { Card, Button, Badge, Avatar, Input, Modal, Select } = NS;

  const TENANTS = [
    { name: "Kofi Mensah", email: "kofi.mensah@yahoo.com", phone: "+233 20 887 3341", avatar: "../../assets/images/av-kofi.jpg", property: "Lashibi Townhouses", unit: "House 1", lease: "Active", leaseTone: "success", leaseSub: "Expires May 2026", maint: "1 Urgent", maintTone: "danger" },
    { name: "Ama Osei", email: "ama.osei@outlook.com", phone: "+233 55 120 9987", avatar: "../../assets/images/av-ama.jpg", property: "Cantonments City", unit: "Apt 5A", lease: "Active", leaseTone: "success", leaseSub: "Expires Sep 2026", maint: "No Issues", maintTone: "success" },
    { name: "Efua Asante", email: "efua.asante@gmail.com", phone: "+233 24 411 9283", avatar: "../../assets/images/av-efua.jpg", property: "Lashibi Townhouses", unit: "House 5", lease: "Notice Given", leaseTone: "warning", leaseSub: "Move out: Apr 30", maint: "1 Urgent", maintTone: "danger" },
    { name: "Nana Adjei", email: "nana.adjei@ghana.com", phone: "+233 50 445 2210", avatar: "../../assets/images/av-nana.jpg", property: "Onehive Tse Addo", unit: "Unit 101", lease: "Active", leaseTone: "success", leaseSub: "Expires Jan 2027", maint: "No Issues", maintTone: "success" },
    { name: "Yaw Boateng", email: "yboateng@gmail.com", phone: "+233 24 330 7765", avatar: "../../assets/images/av-yaw.jpg", property: "Mirage", unit: "Apartment B3", lease: "Applicant", leaseTone: "neutral", leaseSub: "Pending screening", maint: "—", maintTone: "neutral" },
  ];
  const FILTERS = ["All Statuses", "Active", "Notice Given", "Applicant"];

  function leaseDot(tone) {
    const c = tone === "success" ? "var(--success)" : tone === "warning" ? "var(--terracotta-500)" : "var(--gray-400)";
    return <span style={{ width: 8, height: 8, borderRadius: 9999, background: c, flexShrink: 0 }} />;
  }

  function TenantsScreen() {
    const [q, setQ] = React.useState("");
    const [status, setStatus] = React.useState("All Statuses");
    const [modal, setModal] = React.useState(null); // 'add' | tenant
    const [addProp, setAddProp] = React.useState(window.WB_SITES[0]);
    const close = () => setModal(null);

    React.useEffect(() => { const f = window.WBFocus; if (f && f.kind === "tenant") { const t = TENANTS.find((x) => x.name === f.key); if (t) setModal(t); window.WBFocus = null; } else if (f && f.kind === "add-tenant") { setModal("add"); window.WBFocus = null; } }, []);

    const added = window.WBuseNew("tenants");
    const ALL = [...added.slice().reverse(), ...TENANTS];
    const rows = ALL.filter((t) => {
      const okStatus = status === "All Statuses" || t.lease === status;
      const okQ = !q || (t.name + t.email + t.property + t.unit).toLowerCase().includes(q.toLowerCase());
      return okStatus && okQ;
    });
    const loading = window.WBuseLoad();
    const canAdd = window.WBCan("tenant.add");

    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 28, padding: "36px 40px", maxWidth: 1440 }}>
        <window.WBPageHeader eyebrow="Resident Relations" title="Tenants"
          sub="Manage resident profiles, communication, and occupancy across your portfolio."
          actions={<React.Fragment><Button variant="secondary" icon="download" onClick={() => window.WBToast("Tenant list exported (CSV)")}>Export List</Button>{canAdd && <Button variant="primary" icon="user-plus" onClick={() => setModal("add")}>Add New Tenant</Button>}</React.Fragment>} />
        <div style={{ display: "flex", gap: 20, alignItems: "stretch" }}>
          <Input icon="search" placeholder="Search by name, property, or email..." size="lg" value={q} onChange={(e) => setQ(e.target.value)} containerStyle={{ flex: 1 }} />
          <Select value={status} onChange={(e) => setStatus(e.target.value)} options={FILTERS} size="lg" containerStyle={{ width: 220 }} />
          <div style={{ padding: "12px 24px", background: "var(--sage-100)", borderRadius: "var(--radius-md)", display: "flex", flexDirection: "column", justifyContent: "center" }}>
            <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--success-fg)" }}>Total Active</div>
            <div style={{ fontFamily: "var(--font-serif)", fontWeight: 700, fontSize: 24, color: "var(--text-heading)" }}>142 Residents</div>
          </div>
        </div>
        <Card>
          <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1.2fr 1.2fr 1fr 0.7fr", padding: "18px 24px", borderBottom: "1px solid var(--border)" }}>
            {["Resident", "Property & Unit", "Lease Status", "Maintenance", "Actions"].map((h) => (<span key={h} style={{ fontSize: 11, fontWeight: 700, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--text-muted)" }}>{h}</span>))}
          </div>
          {loading ? <window.WBSkeletonRows rows={5} cols={5} /> : rows.map((t, i) => (
            <div key={t.name} style={{ display: "grid", gridTemplateColumns: "1.4fr 1.2fr 1.2fr 1fr 0.7fr", alignItems: "center", padding: "18px 24px", borderTop: i ? "1px solid var(--border)" : "none" }}>
              <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
                <Avatar src={t.avatar} name={t.name} size={44} />
                <div><div style={{ fontWeight: 700, fontSize: 15, color: "var(--text-heading)" }}>{t.name}</div><div style={{ fontSize: 12, color: "var(--text-muted)" }}>{t.email}</div></div>
              </div>
              <div><div style={{ fontWeight: 700, fontSize: 15, color: "var(--text-heading)" }}>{t.property}</div><div style={{ fontSize: 12, color: "var(--text-muted)" }}>{t.unit}</div></div>
              <div style={{ display: "flex", alignItems: "center", gap: 8 }}>{leaseDot(t.leaseTone)}<span style={{ fontWeight: 600, fontSize: 14, color: "var(--text-heading)" }}>{t.lease}</span></div>
              <div><Badge tone={t.maintTone}>{t.maint}</Badge></div>
              <div><Button variant="secondary" size="sm" onClick={() => setModal(t)}>Manage</Button></div>
            </div>
          ))}
          {!loading && rows.length === 0 && <window.WBEmpty icon="users" title="No residents found" message={q || status !== "All Statuses" ? "No residents match your search or filters. Try clearing them." : "Add your first resident to get started."} action={canAdd && !q && status === "All Statuses" ? <Button variant="primary" size="sm" icon="user-plus" onClick={() => setModal("add")}>Add New Tenant</Button> : null} />}
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "16px 24px", borderTop: "1px solid var(--border)" }}>
            <span style={{ fontSize: 13, color: "var(--text-muted)" }}>Showing {rows.length} of 142 residents</span>
            <div style={{ display: "flex", gap: 10 }}><Button variant="secondary" size="sm">Prev</Button><Button variant="secondary" size="sm">Next</Button></div>
          </div>
        </Card>

        {/* Add tenant modal */}
        <Modal open={modal === "add"} onClose={close} icon="user-plus" title="Add New Tenant" subtitle="Create a resident profile and assign a unit."
          footer={<React.Fragment><Button variant="secondary" onClick={close}>Cancel</Button><Button variant="primary" icon="check" onClick={() => { close(); window.WBToast("New tenant added"); }}>Add Tenant</Button></React.Fragment>}>
          <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
            <Input label="Full name" placeholder="e.g. Adjoa Mensah" />
            <div style={{ display: "flex", gap: 14 }}>
              <Input label="Email" icon="mail" placeholder="name@email.com" containerStyle={{ flex: 1 }} />
              <Input label="Phone" placeholder="+233 …" containerStyle={{ flex: 1 }} />
            </div>
            <div style={{ display: "flex", gap: 14 }}>
              <Input label="National ID" placeholder="GHA-000000000-0" containerStyle={{ flex: 1 }} />
              <Input label="Emergency contact" placeholder="Name · +233 …" containerStyle={{ flex: 1 }} />
            </div>
            <div style={{ display: "flex", gap: 14 }}>
              <Select label="Property" value={addProp} onChange={(e) => setAddProp(e.target.value)} options={window.WB_SITES} containerStyle={{ flex: 1 }} />
              <Select label="Unit (vacant)" options={window.WBunitsFor(addProp, true).length ? window.WBunitsFor(addProp, true) : ["No vacant units"]} containerStyle={{ flex: 1 }} />
            </div>
            <div style={{ display: "flex", gap: 14 }}>
              <Select label="Lease status" options={["Active", "Applicant", "Notice Given"]} containerStyle={{ flex: 1 }} />
              <Input label="Move-in date" type="date" containerStyle={{ flex: 1 }} />
            </div>
            <div style={{ borderTop: "1px solid var(--border)", paddingTop: 16 }}>
              <window.WBImageUpload label="Signed tenancy agreement (optional)" />
              <p style={{ margin: "10px 0 0", fontSize: 12, color: "var(--text-muted)" }}>Files here are saved to Documents → Tenancy Agreements and linked to this tenant's profile.</p>
            </div>
          </div>
        </Modal>

        {/* Manage tenant modal */}
        <Modal open={modal && typeof modal === "object"} onClose={close} icon="user" title={modal && modal.name} subtitle={modal && `${modal.property} · ${modal.unit}`} width={540}
          footer={<React.Fragment><Button variant="secondary" onClick={close}>Close</Button><Button variant="primary" icon="pencil" onClick={() => { close(); window.WBFocus = { kind: "edit-tenant" }; window.WBNavigate && window.WBNavigate("TenantProfile"); }}>Edit Profile</Button></React.Fragment>}>
          {modal && typeof modal === "object" && (
            <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
                <Avatar src={modal.avatar} name={modal.name} size={56} />
                <div style={{ display: "flex", gap: 8 }}>{leaseDot(modal.leaseTone)}<span style={{ fontWeight: 600, color: "var(--text-heading)" }}>{modal.lease}</span></div>
              </div>
              {[["Email", modal.email], ["Phone", modal.phone], ["Lease", modal.leaseSub], ["Maintenance", modal.maint]].map(([k, v]) => (
                <div key={k} style={{ display: "flex", justifyContent: "space-between", padding: "10px 0", borderBottom: "1px solid var(--border)" }}>
                  <span style={{ fontSize: 13, color: "var(--text-muted)" }}>{k}</span><span style={{ fontSize: 14, fontWeight: 600, color: "var(--text-heading)" }}>{v}</span>
                </div>
              ))}
              <div style={{ display: "flex", gap: 10 }}>
                <Button variant="secondary" size="sm" icon="message-square" onClick={() => { close(); window.WBToast("Opening chat with " + modal.name); }}>Message</Button>
                <Button variant="secondary" size="sm" icon="user" onClick={() => { close(); window.WBNavigate && window.WBNavigate("TenantProfile"); }}>Full Profile</Button>
              </div>
            </div>
          )}
        </Modal>
      </div>
    );
  }
  window.TenantsScreen = TenantsScreen;
})();
