// Woodbury Operator — Maintenance board. Registers window.MaintenanceScreen.
(function () {
  const NS = window.WoodburyPropertiesDesignSystem_7290ca;
  const { Card, CardHeader, Button, Badge, StatCard, IconTile, Modal, Input, Select, Textarea } = NS;

  const TICKETS = [
    { unit: "House 1 — AC Leak", asset: "Lashibi Townhouses", meta: "Reported 2 hours ago · HVAC team notified", icon: "wind", tone: "danger", badge: "Urgent", badgeTone: "danger", vendor: "AirCool HVAC Services" },
    { unit: "Villa 7 — Roof Tile Repair", asset: "Cantonments City", meta: "Scheduled for tomorrow · Roofer assigned", icon: "home", tone: "accent", badge: "Medium", badgeTone: "warning", vendor: "Kojo Roofing & Works" },
    { unit: "Flat 2B — Geyser Fault", asset: "Mirage", 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", asset: "Lashibi Townhouses", meta: "Low priority · Backlog", icon: "door-closed", tone: "sunken", badge: "Backlog", badgeTone: "neutral", vendor: "Unassigned" },
    { unit: "Unit 8 — Water Pressure", asset: "Onehive Tse Addo", meta: "Resident follow-up requested", icon: "droplet", tone: "sunken", badge: "Medium", badgeTone: "warning", vendor: "Mensah Plumbing Co." },
  ];

  function MaintenanceScreen() {
    const [modal, setModal] = React.useState(null); // 'new' | {type:'view'|'assign', ticket}
    const [ntProp, setNtProp] = React.useState(window.WB_SITES[0]);
    const [ntUnit, setNtUnit] = React.useState("");
    const close = () => setModal(null);
    const vendorNames = window.WB_DATA.vendors.map((v) => v.name);
    // Requests submitted from the resident portal (same-origin localStorage bridge).
    const portal = window.WBreadPortalRequests().map((p) => ({
      unit: (p.unit || "Unit") + " — " + p.title, asset: p.property || "", meta: "From resident portal · " + (p.resident || "Resident") + " · " + (p.reported || "just now"),
      icon: { "Plumbing": "droplet", "HVAC / Cooling": "wind", "Electrical": "zap", "Appliances": "wifi", "Structural": "home", "General": "wrench" }[p.cat] || "wrench",
      tone: p.priority === "Urgent" ? "danger" : p.priority === "Medium" ? "accent" : "sunken",
      badge: p.priority === "Urgent" ? "Urgent" : p.priority === "Medium" ? "Medium" : "Low", badgeTone: p.priority === "Urgent" ? "danger" : p.priority === "Medium" ? "warning" : "neutral",
      vendor: "Unassigned", fromPortal: true,
    }));
    const QUEUE = [...portal, ...TICKETS];
    const openNew = () => { const p = window.WB_SITES[0]; setNtProp(p); setNtUnit(window.WBunitsFor(p, false)[0] || ""); setModal({ type: "new" }); };
    React.useEffect(() => { const f = window.WBFocus; if (f && f.kind === "ticket") { const t = TICKETS.find((x) => x.unit === f.key); if (t) { window.WB_ACTIVE_TICKET = { unit: t.unit, asset: t.asset, icon: t.icon, badge: t.badge, badgeTone: t.badgeTone, vendor: t.vendor, vendorTrade: (window.WB_DATA.vendors.find((v) => v.name === t.vendor) || {}).trade || "Contractor", vendorPhone: (window.WB_DATA.vendors.find((v) => v.name === t.vendor) || {}).phone || "+233 …", tenant: "Kofi Mensah", tenantUnit: t.unit.split(" — ")[0], reported: "18 Aug 2026 · 09:12", reportDate: "20 Aug 2026", priority: t.badge, stageIndex: t.badge === "In Progress" ? 3 : t.vendor === "Unassigned" ? 0 : 1, description: t.meta }; window.WBNavigate && window.WBNavigate("TicketDetail"); } window.WBFocus = null; } else if (f && f.kind === "new-ticket") { setModal({ type: "new" }); window.WBFocus = null; } }, []);

    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 28, padding: "36px 40px", maxWidth: 1440 }}>
        <window.WBPageHeader eyebrow="Facilities" title="Maintenance"
          sub="Track and dispatch repair tickets across the portfolio."
          actions={<Button variant="primary" icon="plus" onClick={openNew}>New Ticket</Button>} />
        <div style={{ display: "flex", gap: 20 }}>
          <StatCard onClick={()=>window.WBNavigate&&window.WBNavigate("Maintenance")} label="Open Tickets" value="8" icon="wrench" iconTone="brand" />
          <StatCard onClick={()=>window.WBNavigate&&window.WBNavigate("Maintenance")} label="Urgent" value="3" icon="triangle-alert" iconTone="danger" emphasis="danger" />
          <StatCard onClick={()=>window.WBNavigate&&window.WBNavigate("Reports")} label="Avg. Resolution" value="1.4d" icon="clock" iconTone="success" emphasis="success" />
          <StatCard onClick={()=>window.WBNavigate&&window.WBNavigate("Vendors")} label="Vendors Active" value="5" icon="hard-hat" iconTone="accent" />
        </div>
        <Card>
          <CardHeader title="Ticket Queue" action={<Button variant="ghost" size="sm" icon="filter">Filter</Button>} />
          {QUEUE.map((t, i) => (
            <div key={t.unit} style={{ display: "flex", gap: 16, padding: 24, borderTop: i ? "1px solid var(--border)" : "none", alignItems: "center" }}>
              <IconTile icon={t.icon} tone={t.tone} size={48} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 12 }}><span style={{ fontWeight: 700, fontSize: 15, color: "var(--text-heading)" }}>{t.unit}</span><Badge tone={t.badgeTone} dot={t.badgeTone === "success"}>{t.badge}</Badge></div>
                <div style={{ fontSize: 13, color: "var(--text-body)", marginTop: 3 }}>{t.meta}</div>
              </div>
              <div style={{ textAlign: "right", minWidth: 160 }}>
                <div style={{ fontSize: 11, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--text-muted)" }}>{t.asset}</div>
                <div style={{ fontSize: 13, fontWeight: 600, color: t.vendor === "Unassigned" ? "var(--terracotta-600)" : "var(--text-heading)", marginTop: 2 }}>{t.vendor}</div>
              </div>
              {t.vendor === "Unassigned"
                ? <Button variant="primary" size="sm" onClick={() => setModal({ type: "assign", ticket: t })}>Assign Vendor</Button>
                : <Button variant="secondary" size="sm" onClick={() => { window.WB_ACTIVE_TICKET = { unit: t.unit, asset: t.asset, icon: t.icon, badge: t.badge, badgeTone: t.badgeTone, vendor: t.vendor, vendorTrade: (window.WB_DATA.vendors.find((v) => v.name === t.vendor) || {}).trade || "Contractor", vendorPhone: (window.WB_DATA.vendors.find((v) => v.name === t.vendor) || {}).phone || "+233 …", tenant: "Kofi Mensah", tenantUnit: t.unit.split(" — ")[0], reported: "18 Aug 2026 · 09:12", reportDate: "20 Aug 2026", priority: t.badge, stageIndex: t.badge === "In Progress" ? 3 : t.vendor === "Unassigned" ? 0 : 1, description: t.meta }; window.WBNavigate && window.WBNavigate("TicketDetail"); }}>View</Button>}
            </div>
          ))}
        </Card>

        {/* New ticket */}
        <Modal open={modal && modal.type === "new"} onClose={close} icon="wrench" title="New Maintenance Ticket" subtitle="Log a repair request."
          footer={<React.Fragment><Button variant="secondary" onClick={close}>Cancel</Button><Button variant="primary" icon="check" onClick={() => { close(); window.WBToast("Ticket created"); }}>Create Ticket</Button></React.Fragment>}>
          <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
            <div style={{ display: "flex", gap: 14 }}>
              <Select label="Property" value={ntProp} onChange={(e) => { setNtProp(e.target.value); setNtUnit(window.WBunitsFor(e.target.value, false)[0] || ""); }} options={window.WB_SITES} containerStyle={{ flex: 1 }} />
              <Select label="Unit" value={ntUnit} onChange={(e) => setNtUnit(e.target.value)} options={window.WBunitsFor(ntProp, false).length ? window.WBunitsFor(ntProp, false) : ["No units listed"]} containerStyle={{ flex: 1 }} />
            </div>
            <Input label="Issue title" placeholder="e.g. AC not cooling" />
            <div style={{ display: "flex", gap: 14 }}>
              <Select label="Priority" options={["Urgent", "Medium", "Low"]} containerStyle={{ flex: 1 }} />
              <Select label="Assign vendor" options={["Unassigned", ...vendorNames]} containerStyle={{ flex: 1 }} />
            </div>
            <Textarea label="Description" placeholder="Describe the issue…" />
          </div>
        </Modal>

        {/* View ticket */}
        <Modal open={modal && modal.type === "view"} onClose={close} icon="wrench" title={modal && modal.ticket && modal.ticket.unit} subtitle={modal && modal.ticket && modal.ticket.asset} width={540}
          footer={<React.Fragment><Button variant="secondary" onClick={close}>Close</Button><Button variant="primary" icon="check-check" onClick={() => { close(); window.WBToast("Ticket marked resolved"); }}>Mark Resolved</Button></React.Fragment>}>
          {modal && modal.ticket && (
            <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
              <div><Badge tone={modal.ticket.badgeTone} dot={modal.ticket.badgeTone === "success"}>{modal.ticket.badge}</Badge></div>
              {[["Status update", modal.ticket.meta], ["Assigned vendor", modal.ticket.vendor], ["Location", modal.ticket.asset]].map(([k, v]) => (
                <div key={k} style={{ display: "flex", justifyContent: "space-between", gap: 20, padding: "10px 0", borderBottom: "1px solid var(--border)" }}>
                  <span style={{ fontSize: 13, color: "var(--text-muted)", flexShrink: 0 }}>{k}</span><span style={{ fontSize: 14, fontWeight: 600, color: "var(--text-heading)", textAlign: "right" }}>{v}</span>
                </div>
              ))}
              <Button variant="secondary" size="sm" icon="refresh-cw" onClick={() => { close(); setModal({ type: "assign", ticket: modal.ticket }); }} style={{ marginTop: 4 }}>Reassign Vendor</Button>
            </div>
          )}
        </Modal>

        {/* Assign vendor */}
        <Modal open={modal && modal.type === "assign"} onClose={close} icon="hard-hat" title="Assign Vendor" subtitle={modal && modal.ticket && modal.ticket.unit}
          footer={<React.Fragment><Button variant="secondary" onClick={close}>Cancel</Button><Button variant="primary" icon="check" onClick={() => { close(); window.WBToast("Vendor dispatched to " + modal.ticket.unit); }}>Dispatch</Button></React.Fragment>}>
          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            {window.WB_DATA.vendors.map((v, i) => (
              <label key={v.name} style={{ display: "flex", alignItems: "center", gap: 12, padding: 12, borderRadius: "var(--radius-md)", border: "1px solid var(--border)", cursor: "pointer" }}>
                <input type="radio" name="vendor" defaultChecked={i === 0} style={{ accentColor: "var(--brand)", width: 16, height: 16 }} />
                <div style={{ width: 36, height: 36, borderRadius: "var(--radius-md)", background: "var(--walnut-100)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
                  <span className="wb-ico" style={{ width: 18, height: 18, color: "var(--walnut-700)" }}><i data-lucide={v.icon}></i></span>
                </div>
                <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} · {v.jobs} jobs</div></div>
                <Badge tone={v.rating === "Preferred" ? "success" : v.rating === "On-site" ? "accent" : "neutral"}>{v.rating}</Badge>
              </label>
            ))}
          </div>
        </Modal>
      </div>
    );
  }
  window.MaintenanceScreen = MaintenanceScreen;
})();
