// Woodbury Operator — Inspections & Compliance. Registers window.InspectionsScreen.
(function () {
  const NS = window.WoodburyPropertiesDesignSystem_7290ca;
  const { Card, CardHeader, Button, Badge, StatCard, IconTile, Modal, Select, Input, ProgressBar, Checkbox } = NS;

  const typeTone = { "Move-in": "accent", "Move-out": "brand", "Routine": "neutral" };

  function InspectionsScreen() {
    const I = window.WB_INSPECTIONS;
    const C = window.WB_COMPLIANCE;
    const [modal, setModal] = React.useState(null); // 'new' | inspection
    const [checks, setChecks] = React.useState(window.WB_INSPECTION_CHECKLIST.map((c) => c.done));
    const [inProp, setInProp] = React.useState(window.WB_SITES[0]);
    const [inUnit, setInUnit] = React.useState("");
    const close = () => setModal(null);
    const openNew = () => { const p = window.WB_SITES[0]; setInProp(p); setInUnit(window.WBunitsFor(p, false)[0] || ""); setModal("new"); };
    const openChecklist = (insp) => { setChecks(window.WB_INSPECTION_CHECKLIST.map((c) => c.done)); setModal(insp); };
    const doneCount = checks.filter(Boolean).length;
    const pct = Math.round((doneCount / checks.length) * 100);

    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 28, padding: "36px 40px", maxWidth: 1440 }}>
        <window.WBPageHeader eyebrow="Property Condition" title="Inspections & Compliance"
          sub="Move-in/out and routine inspections, plus certificate expiry tracking."
          actions={<Button variant="primary" icon="plus" onClick={openNew}>Schedule Inspection</Button>} />
        <div style={{ display: "flex", gap: 20 }}>
          <StatCard onClick={()=>window.WBNavigate&&window.WBNavigate("Inspections")} label="Scheduled" value="2" icon="calendar-days" iconTone="accent" />
          <StatCard onClick={()=>window.WBNavigate&&window.WBNavigate("Inspections")} label="In Progress" value="1" icon="clipboard-list" iconTone="brand" />
          <StatCard onClick={()=>window.WBNavigate&&window.WBNavigate("Inspections")} label="Completed (30d)" value="6" icon="clipboard-check" iconTone="success" emphasis="success" />
          <StatCard onClick={()=>window.WBNavigate&&window.WBNavigate("Inspections")} label="Compliance Alerts" value="2" icon="shield-alert" iconTone="danger" emphasis="danger" />
        </div>

        {/* Compliance reminders */}
        <Card>
          <CardHeader title="Compliance & Expiry Reminders" action={<Button variant="ghost" size="sm" icon="bell" onClick={() => window.WBToast("Reminders enabled for expiring documents")}>Remind me</Button>} />
          <div style={{ overflowX: "auto" }}>
            <div style={{ minWidth: 620 }}>
              <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1.2fr 1fr 0.8fr 0.6fr", padding: "12px 24px", borderBottom: "1px solid var(--border)" }}>
                {["Document", "Site", "Expires", "Status", ""].map((h, i) => <span key={i} style={{ fontSize: 11, fontWeight: 700, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--text-muted)" }}>{h}</span>)}
              </div>
              {C.map((c, i) => (
                <div key={c.doc} style={{ display: "grid", gridTemplateColumns: "1.4fr 1.2fr 1fr 0.8fr 0.6fr", alignItems: "center", padding: "14px 24px", borderTop: i ? "1px solid var(--border)" : "none" }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 12 }}><IconTile icon="file-badge" tone={c.tone === "danger" ? "danger" : c.tone === "warning" ? "accent" : "success"} size={36} /><span style={{ fontWeight: 600, fontSize: 14, color: "var(--text-heading)" }}>{c.doc}</span></div>
                  <span style={{ fontSize: 14, color: "var(--text-body)" }}>{c.site}</span>
                  <div><div style={{ fontSize: 14, color: "var(--text-heading)" }}>{c.expires}</div><div style={{ fontSize: 12, color: c.days <= 30 ? "var(--danger)" : "var(--text-muted)" }}>{c.days} days</div></div>
                  <div><Badge tone={c.tone}>{c.status}</Badge></div>
                  <div style={{ textAlign: "right" }}><Button variant="ghost" size="sm" icon="rotate-cw" onClick={() => window.WBToast("Renewal requested · " + c.doc)} /></div>
                </div>
              ))}
            </div>
          </div>
        </Card>

        {/* Inspection schedule */}
        <Card>
          <CardHeader title="Inspection Schedule" action={<Button variant="ghost" size="sm" icon="filter">Filter</Button>} />
          {I.map((insp, i) => (
            <div key={insp.unit + insp.date} style={{ display: "flex", gap: 16, alignItems: "center", padding: "18px 24px", borderTop: i ? "1px solid var(--border)" : "none" }}>
              <IconTile icon="clipboard-check" tone={insp.status === "Completed" ? "success" : "brand"} size={44} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap" }}><span style={{ fontWeight: 700, fontSize: 15, color: "var(--text-heading)" }}>{insp.unit}</span><Badge tone={typeTone[insp.type]}>{insp.type}</Badge></div>
                <div style={{ fontSize: 12, color: "var(--text-muted)", marginTop: 3 }}>{insp.tenant} · Inspector: {insp.inspector} · {insp.date}</div>
              </div>
              <Badge tone={insp.tone}>{insp.status}</Badge>
              <Button variant="secondary" size="sm" onClick={() => openChecklist(insp)}>{insp.status === "Completed" ? "View" : "Checklist"}</Button>
            </div>
          ))}
        </Card>

        {/* Schedule modal */}
        <Modal open={modal === "new"} onClose={close} icon="clipboard-check" title="Schedule Inspection" subtitle="Book a property condition inspection."
          footer={<React.Fragment><Button variant="secondary" onClick={close}>Cancel</Button><Button variant="primary" icon="check" onClick={() => { close(); window.WBToast("Inspection scheduled"); }}>Schedule</Button></React.Fragment>}>
          <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
            <Select label="Type" options={["Move-in", "Move-out", "Routine"]} />
            <div style={{ display: "flex", gap: 14 }}>
              <Select label="Property" value={inProp} onChange={(e) => { setInProp(e.target.value); setInUnit(window.WBunitsFor(e.target.value, false)[0] || ""); }} options={window.WB_SITES} containerStyle={{ flex: 1 }} />
              <Select label="Unit" value={inUnit} onChange={(e) => setInUnit(e.target.value)} options={window.WBunitsFor(inProp, false).length ? window.WBunitsFor(inProp, false) : ["No units listed"]} containerStyle={{ flex: 1 }} />
            </div>
            <div style={{ display: "flex", gap: 14 }}>
              <Input label="Date" type="date" containerStyle={{ flex: 1 }} />
              <Select label="Inspector" options={["Adjoa Owusu", "Kwesi Appiah", "Abena Sarpong"]} containerStyle={{ flex: 1 }} />
            </div>
          </div>
        </Modal>

        {/* Checklist modal */}
        <Modal open={modal && typeof modal === "object"} onClose={close} icon="clipboard-list" title={modal && modal.unit} subtitle={modal && `${modal.type} inspection · ${modal.date}`} width={520}
          footer={<React.Fragment><Button variant="secondary" onClick={close}>Close</Button><Button variant="primary" icon="check-check" onClick={() => { close(); window.WBToast("Inspection report saved"); }}>Save Report</Button></React.Fragment>}>
          {modal && typeof modal === "object" && (
            <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
              <div>
                <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12, color: "var(--text-muted)", marginBottom: 6 }}><span>Checklist progress</span><span style={{ fontWeight: 600, color: "var(--text-heading)" }}>{pct}%</span></div>
                <ProgressBar value={pct} tone={pct === 100 ? "success" : "brand"} />
              </div>
              <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
                {window.WB_INSPECTION_CHECKLIST.map((c, idx) => (
                  <Checkbox key={c.area} label={c.area} checked={checks[idx]} onChange={(v) => setChecks((cs) => cs.map((x, j) => j === idx ? v : x))} />
                ))}
              </div>
            </div>
          )}
        </Modal>
      </div>
    );
  }
  window.InspectionsScreen = InspectionsScreen;
})();
