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

  const LEASES = [
    { tenant: "Kofi Mensah", avatar: "../../assets/images/av-kofi.jpg", asset: "Lashibi Townhouses · House 1", ends: "28 May 2026", left: 28, total: 365, term: "12 months", tone: "danger" },
    { tenant: "Ama Osei", avatar: "../../assets/images/av-ama.jpg", asset: "Cantonments City · Apt 5A", ends: "14 Sep 2026", left: 137, total: 365, term: "12 months", tone: "accent" },
    { tenant: "Nana Adjei", avatar: "../../assets/images/av-nana.jpg", asset: "Onehive Tse Addo · Unit 101", ends: "02 Jan 2027", left: 247, total: 365, term: "24 months", tone: "success" },
    { tenant: "Efua Asante", avatar: "../../assets/images/av-efua.jpg", asset: "Lashibi Townhouses · House 5", ends: "30 Apr 2026", left: 0, total: 365, term: "12 months", tone: "danger", notice: true },
  ];

  function LeasesScreen() {
    const [modal, setModal] = React.useState(null); // 'new' | {type:'renew'|'view', lease}
    const [nlProp, setNlProp] = React.useState(window.WB_SITES[0]);
    const [nlUnit, setNlUnit] = React.useState("");
    const close = () => setModal(null);
    const openNew = () => { const p = window.WB_SITES[0]; setNlProp(p); const u = window.WBunitsFor(p, true); setNlUnit(u[0] || ""); setModal({ type: "new" }); };

    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 28, padding: "36px 40px", maxWidth: 1440 }}>
        <window.WBPageHeader eyebrow="Tenancy Contracts" title="Leases"
          sub="Monitor active agreements, renewals, and upcoming expirations."
          actions={<React.Fragment><Button variant="secondary" icon="download" onClick={() => window.WBToast("Lease register exported")}>Export</Button><Button variant="primary" icon="file-plus" onClick={openNew}>New Lease</Button></React.Fragment>} />
        <div style={{ display: "flex", gap: 20 }}>
          <StatCard onClick={()=>window.WBNavigate&&window.WBNavigate("Leases")} label="Active Leases" value="114" icon="file-signature" iconTone="brand" />
          <StatCard onClick={()=>window.WBNavigate&&window.WBNavigate("Leases")} label="Expiring < 30d" value="3" icon="calendar-clock" iconTone="danger" emphasis="danger" />
          <StatCard onClick={()=>window.WBNavigate&&window.WBNavigate("Leases")} label="Renewals Pending" value="5" icon="refresh-cw" iconTone="accent" />
          <StatCard onClick={()=>window.WBNavigate&&window.WBNavigate("Leases")} label="Avg. Term" value="14 mo" icon="calendar-days" iconTone="success" />
        </div>
        <Card>
          <CardHeader title="Lease Portfolio" action={<Button variant="ghost" size="sm" icon="filter">Filter</Button>} />
          {LEASES.map((l, i) => (
            <div key={l.tenant} style={{ display: "grid", gridTemplateColumns: "1.4fr 1.6fr 0.8fr 0.7fr", gap: 20, alignItems: "center", padding: "20px 24px", borderTop: i ? "1px solid var(--border)" : "none" }}>
              <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
                <Avatar src={l.avatar} name={l.tenant} size={44} />
                <div><div style={{ fontWeight: 700, fontSize: 15, color: "var(--text-heading)" }}>{l.tenant}</div><div style={{ fontSize: 12, color: "var(--text-muted)" }}>{l.asset}</div></div>
              </div>
              <div>
                <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12, marginBottom: 5 }}><span style={{ color: l.left <= 30 ? "var(--danger)" : "var(--text-muted)", fontWeight: 600 }}>{l.notice ? "Notice given" : `${l.left} days left`}</span><span style={{ color: "var(--text-muted)" }}>Ends {l.ends}</span></div>
                <ProgressBar value={Math.max(4, (l.total - l.left) / l.total * 100)} tone={l.tone} />
              </div>
              <span style={{ fontSize: 14, color: "var(--text-heading)" }}>{l.term}</span>
              <div style={{ textAlign: "right", display: "flex", gap: 6, justifyContent: "flex-end" }}>
                <Button variant="ghost" size="sm" onClick={() => setModal({ type: "view", lease: l })}>View</Button>
                {l.left <= 30 && <Button variant="primary" size="sm" onClick={() => setModal({ type: "renew", lease: l })}>Renew</Button>}
              </div>
            </div>
          ))}
        </Card>

        {/* New lease */}
        <Modal open={modal && modal.type === "new"} onClose={close} icon="file-plus" title="New Lease" subtitle="Draft a tenancy agreement."
          footer={<React.Fragment><Button variant="secondary" onClick={close}>Cancel</Button><Button variant="primary" icon="check" onClick={() => { close(); window.WBToast("Lease drafted — sent for signature"); }}>Create Lease</Button></React.Fragment>}>
          <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
            <Select label="Tenant" options={LEASES.map((l) => l.tenant)} />
            <div style={{ display: "flex", gap: 14 }}>
              <Select label="Property" value={nlProp} onChange={(e) => { setNlProp(e.target.value); const u = window.WBunitsFor(e.target.value, true); setNlUnit(u[0] || ""); }} options={window.WB_SITES} containerStyle={{ flex: 1 }} />
              <Select label="Unit (vacant)" value={nlUnit} onChange={(e) => setNlUnit(e.target.value)} options={window.WBunitsFor(nlProp, true).length ? window.WBunitsFor(nlProp, true) : ["No vacant units"]} containerStyle={{ flex: 1 }} />
            </div>
            <div style={{ display: "flex", gap: 14 }}>
              <Select label="Term" options={["12 months", "24 months", "6 months"]} containerStyle={{ flex: 1 }} />
              <Input label="Start date" type="date" containerStyle={{ flex: 1 }} />
            </div>
          </div>
        </Modal>

        {/* Renew */}
        <Modal open={modal && modal.type === "renew"} onClose={close} icon="refresh-cw" title="Renew Lease" subtitle={modal && modal.lease && `${modal.lease.tenant} — ${modal.lease.asset}`}
          footer={<React.Fragment><Button variant="secondary" onClick={close}>Cancel</Button><Button variant="primary" icon="check" onClick={() => { close(); window.WBToast("Renewal sent to " + modal.lease.tenant); }}>Send Renewal</Button></React.Fragment>}>
          {modal && modal.lease && (
            <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
              <div style={{ background: "var(--cream-50)", borderRadius: "var(--radius-md)", padding: 16, fontSize: 13, color: "var(--text-body)" }}>Current lease ends <strong style={{ color: "var(--text-heading)" }}>{modal.lease.ends}</strong>.</div>
              <Select label="New term" options={["12 months", "24 months", "6 months"]} />
              <Input label="New start date" type="date" />
            </div>
          )}
        </Modal>

        {/* View */}
        <Modal open={modal && modal.type === "view"} onClose={close} icon="file-signature" title={modal && modal.lease && modal.lease.tenant} subtitle={modal && modal.lease && modal.lease.asset} width={540}
          footer={<React.Fragment><Button variant="secondary" onClick={close}>Close</Button><Button variant="primary" icon="download" onClick={() => { close(); window.WBToast("Lease PDF downloaded"); }}>Download PDF</Button></React.Fragment>}>
          {modal && modal.lease && (
            <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
              {[["Status", modal.lease.notice ? "Notice given" : "Active"], ["Term", modal.lease.term], ["Ends", modal.lease.ends], ["Days remaining", modal.lease.notice ? "—" : modal.lease.left]].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>
          )}
        </Modal>
      </div>
    );
  }
  window.LeasesScreen = LeasesScreen;
})();
