// Woodbury Operator — role-specific dashboards. Registers SiteDashboard,
// OperatorDashboard, AgentDashboard (Super Admin keeps PortfolioScreen).
(function () {
  const NS = window.WoodburyPropertiesDesignSystem_7290ca;
  const { StatCard, Card, CardHeader, Button, Badge, Avatar, ProgressBar, IconTile, Eyebrow, Modal, Select, Input } = NS;

  function TicketRow({ t, i, action }) {
    return (
      <div style={{ display: "flex", gap: 16, padding: "18px 24px", borderTop: i ? "1px solid var(--border)" : "none", alignItems: "center" }}>
        <IconTile icon={t.icon} tone={t.tone} size={44} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}><span style={{ fontWeight: 700, fontSize: 14, color: "var(--text-heading)" }}>{t.unit}</span>{t.badge && <Badge tone={t.badgeTone} dot={t.badgeTone === "success"}>{t.badge}</Badge>}</div>
          <div style={{ fontSize: 12, color: "var(--text-muted)", marginTop: 2 }}>{t.meta}</div>
        </div>
        {action}
      </div>
    );
  }

  function ExpiringLease({ name, avatar, unit, ends, left }) {
    return (
      <div style={{ border: "1px solid var(--border)", borderRadius: "var(--radius-lg)", padding: 18 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 12 }}>
          <Avatar src={avatar} name={name} size={38} />
          <div><div style={{ fontWeight: 700, fontSize: 14, color: "var(--text-heading)" }}>{name} — {unit}</div><div style={{ fontSize: 12, color: "var(--text-muted)" }}>Lease ends {ends}</div></div>
        </div>
        <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12, color: "var(--text-muted)", marginBottom: 6 }}><span style={{ color: left <= 30 ? "var(--danger)" : "var(--text-muted)", fontWeight: 600 }}>{left} days left</span><span>365 total</span></div>
        <ProgressBar value={Math.max(6, (365 - left) / 365 * 100)} tone={left <= 30 ? "danger" : "accent"} style={{ marginBottom: 14 }} />
        <Button variant="primary" size="sm" full onClick={() => window.WBToast("Renewal initiated for " + name)}>Initiate Renewal</Button>
      </div>
    );
  }

  // ---------------- Site Administrator ----------------
  function SiteDashboard({ site = "Lashibi Townhouses" }) {
    const D = window.WB_DATA;
    const [notify, setNotify] = React.useState(false);
    const tickets = [
      { unit: "House 1 — AC Leak", meta: 'Reported by Efua Asante · HVAC notified', icon: "wind", tone: "danger", badge: "Urgent", badgeTone: "danger" },
      { unit: "Villa 12 — Gate Remote Sync", meta: "Low priority · Backlog", icon: "door-closed", tone: "sunken", badge: "Backlog", badgeTone: "neutral" },
    ];
    const siteApplicants = D.applicants.filter((a) => a.asset.startsWith("Cantonments")).slice(0, 3);
    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 28, padding: "36px 40px", maxWidth: 1440 }}>
        <window.WBPageHeader eyebrow={site} title={"Akwaaba,\nAdjoa Owusu"}
          sub={`Managing ${site} — 24 units, day-to-day operations.`}
          actions={<React.Fragment><Button variant="secondary" icon="megaphone" onClick={() => setNotify(true)}>Notify Residents</Button><Button variant="primary" icon="user-plus" onClick={() => { window.WBFocus = { kind: "add-tenant" }; window.WBNavigate && window.WBNavigate("Tenants"); }}>Add Tenant</Button></React.Fragment>} />
        <window.WBNotifyModal open={notify} onClose={() => setNotify(false)} title={"Notify " + site} defaultSite={site} lockSite={true} />
        <div style={{ display: "flex", gap: 20 }}>
          <StatCard onClick={()=>window.WBNavigate&&window.WBNavigate("Properties")} label="Site Units" value="24" icon="home" iconTone="brand" />
          <StatCard onClick={()=>window.WBNavigate&&window.WBNavigate("Properties")} label="Occupancy" value="92%" icon="building-2" iconTone="success" emphasis="success" />
          <StatCard onClick={()=>window.WBNavigate&&window.WBNavigate("Maintenance")} label="Open Tickets" value="2" icon="wrench" iconTone="danger" emphasis="danger" />
          <StatCard onClick={()=>window.WBNavigate&&window.WBNavigate("Screening")} label="Applicants" value="2" icon="user-check" iconTone="accent" />
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "1.6fr 1fr", gap: 24, alignItems: "start" }}>
          <Card>
            <CardHeader title="Site Maintenance" action={<a href="#" onClick={(e) => e.preventDefault()} style={{ fontSize: 12, fontWeight: 700, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--terracotta-600)" }}>View all</a>} />
            {tickets.map((t, i) => <TicketRow key={t.unit} t={t} i={i} action={<Button variant="secondary" size="sm" onClick={() => { window.WBFocus = { kind: "ticket", key: t.unit }; window.WBNavigate && window.WBNavigate("Maintenance"); }}>View</Button>} />)}
            <div style={{ padding: "20px 24px", borderTop: "1px solid var(--border)" }}>
              <Eyebrow>Recent Applicants — {site}</Eyebrow>
              <div style={{ display: "flex", flexDirection: "column", gap: 12, marginTop: 14 }}>
                {siteApplicants.map((a) => (
                  <div key={a.name} style={{ display: "flex", alignItems: "center", gap: 12 }}>
                    <Avatar src={a.avatar} name={a.name} size={36} />
                    <div style={{ flex: 1 }}><div style={{ fontWeight: 600, fontSize: 14, color: "var(--text-heading)" }}>{a.name}</div><div style={{ fontSize: 12, color: "var(--text-muted)" }}>{a.email}</div></div>
                    {a.status === "Verified" ? <Badge tone="success">Verified</Badge> : <Badge tone="warning">Pending</Badge>}
                  </div>
                ))}
              </div>
            </div>
          </Card>
          <div style={{ display: "flex", flexDirection: "column", gap: 24 }}>
            <Card pad={16}>
              <img src="../../assets/images/featured-cantonments.jpg" alt={site} style={{ width: "100%", height: 150, objectFit: "cover", borderRadius: "var(--radius-md)" }} />
              <h3 style={{ margin: "16px 4px 2px", fontFamily: "var(--font-serif)", fontWeight: 700, fontSize: 20, color: "var(--text-heading)" }}>{site}</h3>
              <p style={{ margin: "0 4px", fontSize: 13, color: "var(--text-body)" }}>24 units · 22 occupied</p>
            </Card>
            <Card style={{ padding: 24 }}>
              <h3 style={{ margin: "0 0 16px", fontFamily: "var(--font-serif)", fontWeight: 700, fontSize: 20, color: "var(--text-heading)" }}>Expiring Lease</h3>
              <ExpiringLease name="Kofi Mensah" avatar="../../assets/images/av-kofi.jpg" unit="House 1" ends="28 May 2026" left={28} />
            </Card>
          </div>
        </div>
      </div>
    );
  }

  // ---------------- Site Operator ----------------
  function OperatorDashboard({ site = "Lashibi Townhouses" }) {
    const tickets = [
      { unit: "House 1 — AC Leak", meta: "Urgent · awaiting your dispatch", icon: "wind", tone: "danger", badge: "Urgent", badgeTone: "danger", vendor: "Unassigned" },
      { unit: "Flat 2B — Geyser Fault", meta: "Parts ordered · ETA 3 days", icon: "flame", tone: "sunken", badge: "In Progress", badgeTone: "success", vendor: "Mensah Plumbing Co." },
      { unit: "Villa 12 — Gate Remote Sync", meta: "Low priority · Backlog", icon: "door-closed", tone: "sunken", badge: "Backlog", badgeTone: "neutral", vendor: "Unassigned" },
    ];
    const vendors = window.WB_DATA.vendors.slice(0, 3);
    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 28, padding: "36px 40px", maxWidth: 1440 }}>
        <window.WBPageHeader eyebrow={site + " · Operations"} title={"Akwaaba,\nKwesi Appiah"}
          sub="Your maintenance queue and vendor dispatch for today."
          actions={<Button variant="primary" icon="plus" onClick={() => { window.WBFocus = { kind: "new-ticket" }; window.WBNavigate && window.WBNavigate("Maintenance"); }}>New Ticket</Button>} />
        <div style={{ display: "flex", gap: 20 }}>
          <StatCard onClick={()=>window.WBNavigate&&window.WBNavigate("Maintenance")} label="My Open Tickets" value="5" icon="wrench" iconTone="brand" />
          <StatCard onClick={()=>window.WBNavigate&&window.WBNavigate("Maintenance")} label="Urgent" value="1" icon="triangle-alert" iconTone="danger" emphasis="danger" />
          <StatCard onClick={()=>window.WBNavigate&&window.WBNavigate("Vendors")} label="Awaiting Vendor" value="2" icon="hard-hat" iconTone="accent" />
          <StatCard onClick={()=>window.WBNavigate&&window.WBNavigate("Maintenance")} label="Resolved This Week" value="7" icon="check-check" iconTone="success" emphasis="success" />
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "1.6fr 1fr", gap: 24, alignItems: "start" }}>
          <Card>
            <CardHeader title="Ticket Queue" action={<Button variant="ghost" size="sm" icon="filter">Filter</Button>} />
            {tickets.map((t, i) => <TicketRow key={t.unit} t={t} i={i} action={t.vendor === "Unassigned" ? <Button variant="primary" size="sm" onClick={() => { window.WBFocus = { kind: "ticket", key: t.unit }; window.WBNavigate && window.WBNavigate("Maintenance"); }}>Assign</Button> : <Button variant="secondary" size="sm" onClick={() => { window.WBFocus = { kind: "ticket", key: t.unit }; window.WBNavigate && window.WBNavigate("Maintenance"); }}>View</Button>} />)}
          </Card>
          <Card>
            <CardHeader title="Vendors On Call" />
            {vendors.map((v, i) => (
              <div key={v.name} style={{ display: "flex", alignItems: "center", gap: 12, padding: "16px 24px", borderTop: i ? "1px solid var(--border)" : "none" }}>
                <IconTile icon={v.icon} tone={v.tone} size={38} />
                <div style={{ flex: 1 }}><div style={{ fontWeight: 700, fontSize: 14, color: "var(--text-heading)" }}>{v.name}</div><div style={{ fontSize: 12, color: "var(--text-muted)" }}>{v.trade}</div></div>
                <Button variant="ghost" size="sm" icon="phone-call" onClick={() => window.WBToast("Calling " + v.name)} />
              </div>
            ))}
          </Card>
        </div>
      </div>
    );
  }

  // ---------------- Leasing Agent ----------------
  function AgentDashboard() {
    const D = window.WB_DATA;
    const [tour, setTour] = React.useState(false);
    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 28, padding: "36px 40px", maxWidth: 1440 }}>
        <window.WBPageHeader eyebrow="Leasing · Cantonments City +2" title={"Akwaaba,\nAbena Sarpong"}
          sub="Your applicant pipeline and upcoming lease renewals."
          actions={<React.Fragment><Button variant="secondary" icon="calendar" onClick={() => setTour(true)}>Schedule Tour</Button><Button variant="primary" icon="user-plus" onClick={() => { window.WBFocus = { kind: "invite-applicant" }; window.WBNavigate && window.WBNavigate("Screening"); }}>Invite Applicant</Button></React.Fragment>} />
        <Modal open={tour} onClose={() => setTour(false)} icon="calendar" title="Schedule Tour" subtitle="Book a property viewing for an applicant."
          footer={<React.Fragment><Button variant="secondary" onClick={() => setTour(false)}>Cancel</Button><Button variant="primary" icon="check" onClick={() => { setTour(false); window.WBToast("Tour scheduled"); }}>Schedule Tour</Button></React.Fragment>}>
          <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
            <Select label="Applicant" options={D.applicants.map((a) => a.name)} />
            <Select label="Property" options={window.WB_SITES} />
            <div style={{ display: "flex", gap: 14 }}>
              <Input label="Date" type="date" containerStyle={{ flex: 1 }} />
              <Input label="Time" type="time" containerStyle={{ flex: 1 }} />
            </div>
            <Select label="Tour type" options={["In-person", "Virtual walkthrough"]} />
          </div>
        </Modal>
        <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="Tours This Week" value="4" icon="calendar-days" iconTone="accent" />
          <StatCard onClick={()=>window.WBNavigate&&window.WBNavigate("Leases")} label="Leases Expiring" value="2" icon="calendar-clock" iconTone="danger" emphasis="danger" />
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "1.6fr 1fr", gap: 24, alignItems: "start" }}>
          <Card>
            <CardHeader title="Applicant Pipeline" action={<a href="#" onClick={(e) => e.preventDefault()} style={{ fontSize: 12, fontWeight: 700, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--terracotta-600)" }}>View all</a>} />
            {D.applicants.map((a, i) => (
              <div key={a.name} style={{ display: "flex", gap: 14, alignItems: "center", padding: "16px 24px", borderTop: i ? "1px solid var(--border)" : "none" }}>
                <Avatar src={a.avatar} name={a.name} size={40} />
                <div style={{ flex: 1 }}><div style={{ fontWeight: 700, fontSize: 14, 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={() => { window.WBFocus = { kind: "applicant", key: a.name }; window.WBNavigate && window.WBNavigate("Screening"); }}>Review</Button>
              </div>
            ))}
          </Card>
          <Card style={{ padding: 24 }}>
            <h3 style={{ margin: "0 0 16px", fontFamily: "var(--font-serif)", fontWeight: 700, fontSize: 20, color: "var(--text-heading)" }}>Upcoming Renewals</h3>
            <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
              <ExpiringLease name="Ama Osei" avatar="../../assets/images/av-ama.jpg" unit="Apt 5A" ends="14 Sep 2026" left={137} />
              <ExpiringLease name="Efua Asante" avatar="../../assets/images/av-efua.jpg" unit="House 5" ends="30 Apr 2026" left={12} />
            </div>
          </Card>
        </div>
      </div>
    );
  }

  window.SiteDashboard = SiteDashboard;
  window.OperatorDashboard = OperatorDashboard;
  window.AgentDashboard = AgentDashboard;
})();
