// Woodbury Operator — Portfolio (super-admin dashboard). Registers window.PortfolioScreen.
(function () {
  const NS = window.WoodburyPropertiesDesignSystem_7290ca;
  const { StatCard, Card, Button, Badge, Avatar, ProgressBar, SegmentedControl, Eyebrow, Modal, Input, Select, Textarea } = NS;

  function KPI({ label, delta, deltaTone, value, unit, sub, children, onClick }) {
    return (
      <div onClick={onClick} style={{ flex: 1, minWidth: 0, background: "var(--surface)", borderRadius: "var(--radius-lg)", boxShadow: "var(--shadow-card)", padding: 24, display: "flex", flexDirection: "column", gap: 12, cursor: onClick ? "pointer" : "default", transition: "transform var(--dur-fast) var(--ease-out), box-shadow var(--dur-fast) var(--ease-out)" }}
        onMouseEnter={onClick ? (e) => { e.currentTarget.style.transform = "translateY(-2px)"; e.currentTarget.style.boxShadow = "var(--shadow-md)"; } : undefined}
        onMouseLeave={onClick ? (e) => { e.currentTarget.style.transform = "none"; e.currentTarget.style.boxShadow = "var(--shadow-card)"; } : undefined}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
          <span style={{ fontSize: 11, fontWeight: 700, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--text-muted)" }}>{label}</span>
          <Badge tone={deltaTone === "danger" ? "danger" : "success"} size="sm">{delta}</Badge>
        </div>
        <div style={{ display: "flex", alignItems: "baseline", gap: 6 }}>
          <span style={{ fontFamily: "var(--font-serif)", fontWeight: 700, fontSize: 40, lineHeight: 1, color: "var(--text-heading)" }}>{value}</span>
          {unit && <span style={{ fontSize: 15, color: "var(--text-body)" }}>{unit}</span>}
        </div>
        {children}
        {sub && <span style={{ fontSize: 12, color: "var(--text-muted)" }}>{sub}</span>}
      </div>
    );
  }

  function PortfolioScreen() {
    const D = window.WB_DATA;
    const [modal, setModal] = React.useState(null); // 'alert' | 'add' | applicant obj
    const [filter, setFilter] = React.useState("All");
    const close = () => setModal(null);
    const shown = D.applicants.filter((a) => filter === "All" ? true : filter === "Pending" ? a.status === "Pending" : a.status === "Verified");

    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 28, padding: "36px 40px", maxWidth: 1440 }}>
        <window.WBPageHeader
          eyebrow="Portfolio Overview"
          title={"Akwaaba,\nSuper Administrator"}
          sub="Overseeing 6 estates and 124 units across Ghana's prime residential locations."
          actions={<React.Fragment>
            <Button variant="secondary" icon="megaphone" onClick={() => setModal("alert")}>Send Alert</Button>
            <Button variant="primary" icon="plus" onClick={() => setModal("add")}>Add Property</Button>
          </React.Fragment>}
        />

        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 0.86fr", gap: 24, alignItems: "stretch" }}>
          <div style={{ display: "flex", flexDirection: "column", gap: 24 }}>
            <KPI label="Portfolio Assets" delta="+4" value="124" unit="Units" sub="6 estates · Greater Accra" onClick={()=>window.WBNavigate&&window.WBNavigate('Properties')} />
            <KPI label="Active Maintenance" delta="3 Urgent" deltaTone="danger" value="8" unit="Tickets" sub="Avg. resolution 1.4 days" onClick={()=>window.WBNavigate&&window.WBNavigate('Maintenance')} />
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 24 }}>
            <KPI label="Avg. Occupancy" delta="+1.2%" value="92.0" unit="%" sub="10 vacant · 114 occupied" onClick={()=>window.WBNavigate&&window.WBNavigate('Properties')}>
              <ProgressBar value={92} tone="success" style={{ margin: "2px 0" }} />
            </KPI>
            <KPI label="Applicants" delta="+2" value="3" unit="Pending" sub="Awaiting background checks" onClick={()=>window.WBNavigate&&window.WBNavigate('Screening')} />
          </div>
          <div style={{ position: "relative", borderRadius: "var(--radius-xl)", overflow: "hidden", minHeight: 320, boxShadow: "var(--shadow-card)" }}>
            <img src="../../assets/images/featured-cantonments.jpg" alt="Lashibi Townhouses" style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover" }} />
            <div style={{ position: "absolute", inset: 0, background: "linear-gradient(180deg, rgba(59,39,20,0) 38%, rgba(56,35,16,0.92) 100%)" }} />
            <div style={{ position: "absolute", top: 18, left: 18 }}>
              <span style={{ display: "inline-flex", alignItems: "center", height: 28, padding: "0 14px", borderRadius: 9999, background: "var(--cream-50)", color: "var(--brand)", fontWeight: 700, fontSize: 12 }}>Flagship Property</span>
            </div>
            <div style={{ position: "absolute", left: 24, right: 24, bottom: 22 }}>
              <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: "0.14em", textTransform: "uppercase", color: "rgba(250,249,246,0.7)" }}>Featured Asset</div>
              <div style={{ fontFamily: "var(--font-serif)", fontWeight: 700, fontSize: 30, color: "var(--cream-50)", margin: "4px 0 10px" }}>Lashibi Townhouses</div>
              <div style={{ display: "flex", gap: 22, fontSize: 13, color: "rgba(250,249,246,0.85)" }}>
                <span>92% occupied</span>
                <span style={{ color: "var(--terracotta-300)", fontWeight: 600 }}>Premium Status</span>
              </div>
            </div>
          </div>
        </div>

        <Card>
          <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", padding: "24px 28px 18px" }}>
            <div>
              <Eyebrow>Screening &amp; Tenancy Ledger</Eyebrow>
              <h3 style={{ margin: "8px 0 0", fontFamily: "var(--font-serif)", fontWeight: 700, fontSize: 24, color: "var(--text-heading)" }}>Active Portfolios</h3>
            </div>
            <SegmentedControl options={["All", "Active", "Pending"]} value={filter} onChange={setFilter} />
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "1.5fr 1.1fr 1.1fr 0.8fr 0.5fr", padding: "12px 28px", borderBottom: "1px solid var(--border)" }}>
            {["Applicant", "Phone", "Asset", "Status", "Action"].map((h, i) => (
              <span key={h} style={{ fontSize: 11, fontWeight: 700, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--text-muted)", textAlign: i === 4 ? "right" : "left" }}>{h}</span>
            ))}
          </div>
          {shown.map((a, i) => (
            <div key={a.name} style={{ display: "grid", gridTemplateColumns: "1.5fr 1.1fr 1.1fr 0.8fr 0.5fr", alignItems: "center", padding: "16px 28px", borderTop: i ? "1px solid var(--border)" : "none" }}>
              <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
                <Avatar src={a.avatar} name={a.name} size={40} />
                <div><div style={{ fontWeight: 700, fontSize: 15, color: "var(--text-heading)" }}>{a.name}</div><div style={{ fontSize: 12, color: "var(--text-muted)" }}>{a.email}</div></div>
              </div>
              <span style={{ fontSize: 14, color: "var(--text-body)" }}>{a.phone}</span>
              <span style={{ fontSize: 14, color: "var(--text-heading)" }}>{a.asset}</span>
              <div>{a.status === "Verified" ? <Badge tone="success">Verified</Badge> : <Badge tone="warning">Pending</Badge>}</div>
              <div style={{ textAlign: "right" }}><Button variant="ghost" size="sm" onClick={() => setModal(a)}>View</Button></div>
            </div>
          ))}
          {shown.length === 0 && <div style={{ padding: "28px", textAlign: "center", color: "var(--text-muted)", fontSize: 14 }}>No {filter.toLowerCase()} applicants.</div>}
        </Card>

        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 24, alignItems: "start" }}>
          <Card style={{ padding: 28 }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 20 }}>
              <h3 style={{ margin: 0, fontFamily: "var(--font-serif)", fontWeight: 700, fontSize: 22, color: "var(--text-heading)" }}>Maintenance Action Checklist</h3>
              <span style={{ fontSize: 13, color: "var(--text-muted)" }}>8 open</span>
            </div>
            <div style={{ display: "flex", flexDirection: "column" }}>
              {D.maintenance.map((m, i) => {
                const dot = { danger: "var(--danger)", accent: "var(--terracotta-500)", success: "var(--success)", neutral: "var(--gray-300)" }[m.tone];
                return (
                  <div key={m.unit} onClick={() => { window.WBFocus = { kind: "ticket", key: m.unit }; window.WBNavigate && window.WBNavigate("Maintenance"); }} style={{ display: "flex", gap: 14, padding: "14px 0", borderTop: i ? "1px solid var(--border)" : "none", cursor: "pointer", borderRadius: 8, transition: "background var(--dur-fast)" }} onMouseEnter={(e) => e.currentTarget.style.background = "var(--cream-50)"} onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}>
                    <span style={{ width: 12, height: 12, borderRadius: 9999, background: dot, marginTop: 4, flexShrink: 0, marginLeft: 8 }} />
                    <div style={{ flex: 1 }}>
                      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                        <span style={{ fontWeight: 700, fontSize: 15, color: "var(--text-heading)" }}>{m.unit}</span>
                        {m.badge && <Badge tone="danger">{m.badge}</Badge>}
                      </div>
                      <div style={{ fontSize: 12, color: "var(--text-muted)", marginTop: 2 }}>{m.meta}</div>
                    </div>
                  </div>
                );
              })}
            </div>
          </Card>

          <Card style={{ padding: 28 }}>
            <h3 style={{ margin: "0 0 20px", fontFamily: "var(--font-serif)", fontWeight: 700, fontSize: 22, color: "var(--text-heading)" }}>Expiring Leases Monitor</h3>
            <div style={{ border: "1px solid var(--border)", borderRadius: "var(--radius-lg)", padding: 20 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 14, marginBottom: 16 }}>
                <Avatar src="../../assets/images/av-kofi.jpg" name="Kofi Mensah" size={40} />
                <div><div style={{ fontWeight: 700, fontSize: 15, color: "var(--text-heading)" }}>Kofi Mensah — Lashibi Townhouses</div><div style={{ fontSize: 12, color: "var(--text-muted)" }}>Lease ends 28 May 2026</div></div>
              </div>
              <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12, color: "var(--text-muted)", marginBottom: 6 }}><span style={{ color: "var(--danger)", fontWeight: 600 }}>28 days left</span><span>365 total</span></div>
              <ProgressBar value={8} tone="danger" style={{ marginBottom: 18 }} />
              <Button variant="primary" full onClick={() => window.WBToast("Renewal initiated for Kofi Mensah")}>Initiate Renewal</Button>
            </div>
            <div style={{ marginTop: 22 }}>
              <Eyebrow>Recent Documents</Eyebrow>
              <div style={{ display: "flex", flexDirection: "column", gap: 14, marginTop: 14 }}>
                {D.documents.slice(0, 2).map((d) => (
                  <div key={d.name} onClick={() => window.WBNavigate && window.WBNavigate("Documents")} style={{ display: "flex", alignItems: "center", gap: 14, cursor: "pointer", padding: 6, borderRadius: 8, transition: "background var(--dur-fast)" }} onMouseEnter={(e) => e.currentTarget.style.background = "var(--cream-50)"} onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}>
                    <div style={{ width: 40, height: 40, borderRadius: "var(--radius-md)", background: "var(--walnut-100)", flexShrink: 0, display: "flex", alignItems: "center", justifyContent: "center" }}><span className="wb-ico" style={{ width: 18, height: 18, color: "var(--walnut-700)" }}><i data-lucide="file-text"></i></span></div>
                    <div style={{ flex: 1 }}><div style={{ fontWeight: 600, fontSize: 14, color: "var(--text-heading)" }}>{d.name}</div><div style={{ fontSize: 12, color: "var(--text-muted)" }}>{d.meta}</div></div>
                    <span className="wb-ico" style={{ width: 16, height: 16, color: "var(--text-muted)" }}><i data-lucide="chevron-right"></i></span>
                  </div>
                ))}
              </div>
            </div>
          </Card>
        </div>

        {/* Send Alert modal */}
        <window.WBNotifyModal open={modal === "alert"} onClose={close} title="Send Portfolio Alert" />

        {/* Add Property modal */}
        <Modal open={modal === "add"} onClose={close} icon="building-2" title="Add Property" subtitle="Register a new estate in the portfolio."
          footer={<React.Fragment><Button variant="secondary" onClick={close}>Cancel</Button><Button variant="primary" icon="check" onClick={() => { close(); window.WBToast("Property added to portfolio"); }}>Save Property</Button></React.Fragment>}>
          <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
            <Input label="Property name" placeholder="e.g. Lashibi Executive Houses" />
            <div style={{ display: "flex", gap: 14 }}>
              <Select label="Type" options={["Townhouses", "Villas", "Apartments", "Lofts"]} containerStyle={{ flex: 1 }} />
              <Input label="Total units" type="number" defaultValue="24" containerStyle={{ flex: 1 }} />
            </div>
            <Input label="Location" placeholder="e.g. Ridge, Accra" icon="map-pin" />
            <Select label="Status" options={["Standard", "Premium", "Flagship"]} />
            <window.WBImageUpload label="Property photos" />
          </div>
        </Modal>

        {/* Applicant view modal */}
        <Modal open={modal && typeof modal === "object"} onClose={close} icon="user" title={modal && modal.name} subtitle={modal && modal.asset}
          footer={<React.Fragment><Button variant="secondary" onClick={close}>Close</Button><Button variant="primary" onClick={() => { close(); window.WBToast("Opened full screening record"); }}>Open Screening</Button></React.Fragment>}>
          {modal && typeof modal === "object" && (
            <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
                <Avatar src={modal.avatar} name={modal.name} size={56} />
                <div>{modal.status === "Verified" ? <Badge tone="success">Verified</Badge> : <Badge tone="warning">Pending</Badge>}</div>
              </div>
              <Row label="Email" value={modal.email} />
              <Row label="Phone" value={modal.phone} />
              <Row label="Applied for" value={modal.asset} />
            </div>
          )}
        </Modal>
      </div>
    );
  }

  function Row({ label, value }) {
    return (
      <div style={{ display: "flex", justifyContent: "space-between", padding: "10px 0", borderBottom: "1px solid var(--border)" }}>
        <span style={{ fontSize: 13, color: "var(--text-muted)" }}>{label}</span>
        <span style={{ fontSize: 14, fontWeight: 600, color: "var(--text-heading)" }}>{value}</span>
      </div>
    );
  }

  window.PortfolioScreen = PortfolioScreen;
})();
