// Woodbury Operator — Screening. Registers window.ScreeningScreen.
(function () {
  const NS = window.WoodburyPropertiesDesignSystem_7290ca;
  const { Card, CardHeader, Button, Badge, Avatar, StatCard, ProgressBar, Modal, Input, Select } = NS;

  const CHECKS = [
    { label: "Identity Verification", done: true },
  ];

  function ScreeningScreen() {
    const D = window.WB_DATA;
    const pending = D.applicants.filter((a) => a.status === "Pending");
    const [modal, setModal] = React.useState(null); // 'invite' | applicant
    const close = () => setModal(null);
    const approve = (a) => {
      const site = window.WB_SITES.find((s) => a.asset.indexOf(s.split(" ")[0]) !== -1) || window.WB_SITES[0];
      const vacant = window.WBunitsFor(site, true)[0] || "Unit TBD";
      window.WBadd("tenants", { name: a.name, email: a.email, phone: a.phone, avatar: a.avatar, property: site, unit: vacant, lease: "Applicant", leaseTone: "neutral", leaseSub: "Move-in pending", maint: "—", maintTone: "neutral" });
      window.WBadd("moves", { id: "MV-" + Math.floor(3100 + Math.random() * 800), type: "Move-in", tenant: a.name, avatar: a.avatar, property: site, unit: vacant, date: "TBD", step: 0 });
      window.WBToast("Approved — " + a.name + " added to Tenants & Move-in started");
    };
    React.useEffect(() => { const f = window.WBFocus; if (f && f.kind === "invite-applicant") { setModal("invite"); window.WBFocus = null; } else if (f && f.kind === "applicant") { const a = D.applicants.find((x) => x.name === f.key); if (a) setModal(a); window.WBFocus = null; } }, []);

    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 28, padding: "36px 40px", maxWidth: 1440 }}>
        <window.WBPageHeader eyebrow="Applicant Pipeline" title="Screening"
          sub="Review background checks and approve incoming tenancy applications."
          actions={<Button variant="primary" icon="user-plus" onClick={() => setModal("invite")}>Invite Applicant</Button>} />
        <div style={{ display: "flex", gap: 20 }}>
          <StatCard onClick={()=>window.WBNavigate&&window.WBNavigate("Screening")} label="In Review" value="3" icon="search-check" iconTone="brand" />
          <StatCard onClick={()=>window.WBNavigate&&window.WBNavigate("Screening")} label="Verified" value="3" icon="shield-check" iconTone="success" emphasis="success" />
          <StatCard onClick={()=>window.WBNavigate&&window.WBNavigate("Screening")} label="Flagged" value="1" icon="flag" iconTone="danger" emphasis="danger" />
          <StatCard onClick={()=>window.WBNavigate&&window.WBNavigate("Screening")} label="Avg. Turnaround" value="2.1d" icon="clock" iconTone="accent" />
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 24, alignItems: "start" }}>
          <Card>
            <CardHeader title="Applicants In Review" />
            {D.applicants.map((a, i) => (
              <div key={a.name} style={{ display: "flex", gap: 14, alignItems: "center", padding: "18px 24px", borderTop: i ? "1px solid var(--border)" : "none" }}>
                <Avatar src={a.avatar} name={a.name} size={44} />
                <div style={{ flex: 1 }}><div style={{ fontWeight: 700, fontSize: 15, color: "var(--text-heading)" }}>{a.name}</div><div style={{ fontSize: 12, color: "var(--text-muted)" }}>{a.asset}</div></div>
                {a.status === "Verified" ? <Badge tone="success">Verified</Badge> : <Badge tone="warning">Pending</Badge>}
                <Button variant="secondary" size="sm" onClick={() => setModal(a)}>Review</Button>
              </div>
            ))}
          </Card>
          <Card style={{ padding: 28 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 14, marginBottom: 6 }}>
              <Avatar src={pending[0].avatar} name={pending[0].name} size={52} />
              <div><div style={{ fontFamily: "var(--font-serif)", fontWeight: 700, fontSize: 20, color: "var(--text-heading)" }}>{pending[0].name}</div><div style={{ fontSize: 13, color: "var(--text-muted)" }}>{pending[0].asset}</div></div>
            </div>
            <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12, color: "var(--text-muted)", margin: "18px 0 6px" }}><span>Identity verification</span><span style={{ fontWeight: 600, color: "var(--success)" }}>Verified</span></div>
            <ProgressBar value={100} tone="success" style={{ marginBottom: 20 }} />
            <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
              {CHECKS.map((c) => (
                <div key={c.label} style={{ display: "flex", alignItems: "center", gap: 12 }}>
                  <span style={{ width: 22, height: 22, borderRadius: 9999, display: "flex", alignItems: "center", justifyContent: "center", background: c.done ? "var(--success-bg)" : "var(--cream-100)", color: c.done ? "var(--success)" : "var(--text-muted)", fontWeight: 700, fontSize: 12 }}>{c.done ? "✓" : "•"}</span>
                  <span style={{ fontSize: 14, color: c.done ? "var(--text-heading)" : "var(--text-body)" }}>{c.label}</span>
                </div>
              ))}
            </div>
            <div style={{ display: "flex", gap: 12, marginTop: 24 }}>
              <Button variant="danger" size="sm" onClick={() => window.WBToast("Application rejected", "danger")}>Reject</Button>
              <Button variant="primary" size="sm" full onClick={() => approve(pending[0])}>Approve Tenancy</Button>
            </div>
          </Card>
        </div>

        {/* Invite modal */}
        <Modal open={modal === "invite"} onClose={close} icon="user-plus" title="Invite Applicant" subtitle="Send a screening application link."
          footer={<React.Fragment><Button variant="secondary" onClick={close}>Cancel</Button><Button variant="primary" icon="send" onClick={() => { close(); window.WBToast("Screening invite sent"); }}>Send Invite</Button></React.Fragment>}>
          <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
            <Input label="Applicant name" placeholder="e.g. Adjoa Mensah" />
            <Input label="Email" icon="mail" placeholder="name@email.com" />
            <Select label="Applying for" options={window.WB_SITES} />
          </div>
        </Modal>

        {/* Review modal */}
        <Modal open={modal && typeof modal === "object"} onClose={close} icon="search-check" title={modal && modal.name} subtitle={modal && `Screening — ${modal.asset}`} width={560}
          footer={<React.Fragment><Button variant="danger" onClick={() => { close(); window.WBToast("Application rejected", "danger"); }}>Reject</Button><Button variant="primary" icon="check" onClick={() => { const a = modal; close(); approve(a); }}>Approve</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={52} />
                <div><div style={{ fontSize: 13, color: "var(--text-muted)" }}>{modal.email} · {modal.phone}</div></div>
              </div>
              <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
                {CHECKS.map((c) => (
                  <div key={c.label} style={{ display: "flex", alignItems: "center", gap: 12 }}>
                    <span style={{ width: 22, height: 22, borderRadius: 9999, display: "flex", alignItems: "center", justifyContent: "center", background: c.done ? "var(--success-bg)" : "var(--cream-100)", color: c.done ? "var(--success)" : "var(--text-muted)", fontWeight: 700, fontSize: 12 }}>{c.done ? "✓" : "•"}</span>
                    <span style={{ fontSize: 14, color: "var(--text-heading)" }}>{c.label}</span>
                    <span style={{ marginLeft: "auto", fontSize: 12, color: c.done ? "var(--success)" : "var(--text-muted)" }}>{c.done ? "Cleared" : "Awaiting"}</span>
                  </div>
                ))}
              </div>
            </div>
          )}
        </Modal>
      </div>
    );
  }
  window.ScreeningScreen = ScreeningScreen;
})();
