// Woodbury Operator — Properties (asset grid). Registers window.PropertiesScreen.
(function () {
  const NS = window.WoodburyPropertiesDesignSystem_7290ca;
  const { Card, Button, Badge, Input, ProgressBar, Modal, Select } = NS;

  function PropertyCard({ p, onManage }) {
    const tone = p.status === "Flagship" ? "accent" : p.status === "Premium" ? "brand" : "neutral";
    return (
      <Card pad={16} style={{ display: "flex", flexDirection: "column" }}>
        <div style={{ position: "relative" }}>
          <img src={p.img} alt={p.name} style={{ width: "100%", height: 170, objectFit: "cover", borderRadius: "var(--radius-md)" }} />
          <div style={{ position: "absolute", top: 12, left: 12 }}><Badge tone={tone}>{p.status}</Badge></div>
        </div>
        <h3 style={{ margin: "16px 4px 2px", fontFamily: "var(--font-serif)", fontWeight: 700, fontSize: 20, color: "var(--text-heading)" }}>{p.name}</h3>
        <p style={{ margin: "0 4px 14px", fontSize: 13, color: "var(--text-body)" }}>{p.type} · {p.units} units</p>
        <div style={{ padding: "0 4px" }}>
          <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12, color: "var(--text-muted)", marginBottom: 6 }}><span>Occupancy</span><span style={{ fontWeight: 600, color: "var(--text-heading)" }}>{p.occ}%</span></div>
          <ProgressBar value={p.occ} tone={p.occ >= 95 ? "success" : "brand"} />
        </div>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 16, paddingTop: 14, borderTop: "1px solid var(--border)" }}>
          <span style={{ fontSize: 13, color: p.vacant ? "var(--terracotta-600)" : "var(--success)", fontWeight: 600 }}>{p.vacant ? `${p.vacant} vacant` : "Fully occupied"}</span>
          <Button variant="ghost" size="sm" iconTrailing="arrow-right" onClick={() => onManage(p)}>Manage</Button>
        </div>
      </Card>
    );
  }

  function PropertiesScreen() {
    const D = window.WB_DATA;
    const all = D.properties;
    const [modal, setModal] = React.useState(null); // 'map' | 'add' | property
    const [q, setQ] = React.useState("");
    const [addUnit, setAddUnit] = React.useState(false);
    const [editP, setEditP] = React.useState(false);
    const [pDraft, setPDraft] = React.useState(null);
    const [unitDraft, setUnitDraft] = React.useState({ label: "", status: "Vacant" });
    const [, force] = React.useReducer((x) => x + 1, 0);
    const close = () => setModal(null);
    React.useEffect(() => { const f = window.WBFocus; if (f && f.kind === "property") { const p = all.find((x) => x.name === f.key); if (p) setModal(p); window.WBFocus = null; } }, []);
    const shown = all.filter((p) => !q || (p.name + p.type).toLowerCase().includes(q.toLowerCase()));

    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 28, padding: "36px 40px", maxWidth: 1440 }}>
        <window.WBPageHeader eyebrow="Asset Management" title="Properties"
          sub="124 units across 6 estates in Accra's prime residential locations."
          actions={<React.Fragment><Button variant="secondary" icon="map" onClick={() => setModal("map")}>Map View</Button><Button variant="primary" icon="plus" onClick={() => setModal("add")}>Add Property</Button></React.Fragment>} />
        <div style={{ display: "flex", gap: 20, alignItems: "stretch" }}>
          <Input icon="search" placeholder="Search estates or units..." size="lg" value={q} onChange={(e) => setQ(e.target.value)} containerStyle={{ flex: 1 }} />
          <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "0 20px", background: "var(--surface)", borderRadius: "var(--radius-md)", boxShadow: "var(--shadow-card)", fontSize: 15, color: "var(--text-heading)" }}>All Types <span style={{ color: "var(--text-muted)" }}>▾</span></div>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 24 }}>
          {shown.map((p) => <PropertyCard key={p.name} p={p} onManage={setModal} />)}
        </div>
        {shown.length === 0 && <div style={{ padding: 40, textAlign: "center", color: "var(--text-muted)", fontSize: 14, background: "var(--surface)", borderRadius: "var(--radius-lg)", boxShadow: "var(--shadow-card)" }}>No estates match “{q}”.</div>}

        {/* Map view modal */}
        <Modal open={modal === "map"} onClose={close} icon="map" title="Portfolio Map" subtitle="Estate locations across Greater Accra." width={720}>
          <div style={{ position: "relative", borderRadius: "var(--radius-lg)", overflow: "hidden", height: 380, background: "var(--cream-100)", boxShadow: "inset 0 0 0 1px var(--border)" }}>
            <div style={{ position: "absolute", inset: 0, backgroundImage: "linear-gradient(var(--cream-200) 1px, transparent 1px), linear-gradient(90deg, var(--cream-200) 1px, transparent 1px)", backgroundSize: "40px 40px", opacity: 0.7 }} />
            <div style={{ position: "absolute", left: "12%", top: "18%", width: "44%", height: "10%", background: "var(--sage-100)", borderRadius: 8, opacity: 0.7 }} />
            <div style={{ position: "absolute", left: "8%", bottom: "14%", right: "12%", height: 6, background: "var(--walnut-200)", borderRadius: 9999 }} />
            {[
              { l: "22%", t: "30%", n: "Lashibi Townhouses" }, { l: "58%", t: "22%", n: "Cantonments City" },
              { l: "70%", t: "58%", n: "Mirage" }, { l: "34%", t: "64%", n: "Onehive Tse Addo" },
              { l: "48%", t: "44%", n: "Hamlet" },
            ].map((pin) => (
              <div key={pin.n} style={{ position: "absolute", left: pin.l, top: pin.t, transform: "translate(-50%,-100%)", display: "flex", flexDirection: "column", alignItems: "center", gap: 4 }}>
                <span style={{ background: "var(--surface)", boxShadow: "var(--shadow-md)", padding: "4px 10px", borderRadius: 9999, fontSize: 11, fontWeight: 700, color: "var(--text-heading)", whiteSpace: "nowrap" }}>{pin.n}</span>
                <span style={{ width: 14, height: 14, borderRadius: "50% 50% 50% 0", background: "var(--brand)", transform: "rotate(45deg)", boxShadow: "var(--shadow-xs)" }} />
              </div>
            ))}
            <div style={{ position: "absolute", right: 14, bottom: 14, background: "var(--surface)", padding: "6px 12px", borderRadius: 9999, fontSize: 11, color: "var(--text-muted)", boxShadow: "var(--shadow-xs)" }}>Greater Accra · schematic</div>
          </div>
        </Modal>

        {/* 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>

        {/* Manage property modal */}
        <Modal open={modal && typeof modal === "object"} onClose={close} icon="building-2" title={modal && modal.name} subtitle={modal && `${modal.type} · ${modal.units} units`} width={560}
          footer={<React.Fragment><Button variant="secondary" onClick={close}>Close</Button><Button variant="primary" icon="pencil" onClick={() => { setPDraft({ ...modal }); setEditP(true); }}>Edit Details</Button></React.Fragment>}>
          {modal && typeof modal === "object" && (
            <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
              <img src={modal.img} alt={modal.name} style={{ width: "100%", height: 180, objectFit: "cover", borderRadius: "var(--radius-md)" }} />
              <div style={{ display: "flex", gap: 12 }}>
                {[["Units", modal.units], ["Occupancy", modal.occ + "%"], ["Vacant", modal.vacant]].map(([k, v]) => (
                  <div key={k} style={{ flex: 1, background: "var(--cream-50)", borderRadius: "var(--radius-md)", padding: "14px 16px" }}>
                    <div style={{ fontSize: 10, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--text-muted)" }}>{k}</div>
                    <div style={{ fontFamily: "var(--font-serif)", fontWeight: 700, fontSize: 22, color: "var(--text-heading)", marginTop: 2 }}>{v}</div>
                  </div>
                ))}
              </div>
              <div style={{ display: "flex", gap: 10 }}>
                <Button variant="secondary" size="sm" icon="users" onClick={() => { close(); window.WBFocus = null; window.WBNavigate && window.WBNavigate("Tenants"); window.WBToast("Residents · " + modal.name); }}>Residents</Button>
                <Button variant="secondary" size="sm" icon="wrench" onClick={() => { close(); window.WBNavigate && window.WBNavigate("Maintenance"); window.WBToast("Maintenance · " + modal.name); }}>Maintenance</Button>
                <Button variant="secondary" size="sm" icon="file-text" onClick={() => { close(); window.WBNavigate && window.WBNavigate("Documents"); window.WBToast("Documents · " + modal.name); }}>Documents</Button>
              </div>
              <div style={{ borderTop: "1px solid var(--border)", paddingTop: 16 }}>
                <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 10 }}>
                  <span style={{ fontSize: 11, fontWeight: 700, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--text-muted)" }}>Units ({(window.WB_UNITS[modal.name] || []).length})</span>
                  <Button variant="ghost" size="sm" icon="plus" onClick={() => { setUnitDraft({ label: "", status: "Vacant" }); setAddUnit(true); }}>Add Unit</Button>
                </div>
                <div style={{ display: "flex", flexDirection: "column", gap: 8, maxHeight: 180, overflowY: "auto" }}>
                  {(window.WB_UNITS[modal.name] || []).map((u) => (
                    <div key={u.label} style={{ display: "flex", alignItems: "center", gap: 12, padding: "10px 12px", borderRadius: "var(--radius-md)", background: "var(--cream-50)" }}>
                      <span className="wb-ico" style={{ width: 16, height: 16, color: "var(--text-muted)" }}><i data-lucide="door-open"></i></span>
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ fontWeight: 600, fontSize: 14, color: "var(--text-heading)" }}>{u.label}</div>
                        {u.tenant && <div style={{ fontSize: 12, color: "var(--text-muted)" }}>{u.tenant}</div>}
                      </div>
                      <Badge tone={u.status === "Vacant" ? "warning" : "success"} dot={u.status !== "Vacant"}>{u.status}</Badge>
                    </div>
                  ))}
                  {(window.WB_UNITS[modal.name] || []).length === 0 && <div style={{ padding: 12, textAlign: "center", fontSize: 13, color: "var(--text-muted)" }}>No units listed yet.</div>}
                </div>
              </div>
            </div>
          )}
        </Modal>

        {/* Add unit modal */}
        <Modal open={addUnit} onClose={() => setAddUnit(false)} icon="door-open" title="Add Unit" subtitle={modal && typeof modal === "object" ? modal.name : ""} width={440}
          footer={<React.Fragment><Button variant="secondary" onClick={() => setAddUnit(false)}>Cancel</Button><Button variant="primary" icon="check" disabled={!unitDraft.label.trim()} onClick={() => {
            const name = modal.name;
            if (!window.WB_UNITS[name]) window.WB_UNITS[name] = [];
            const occupied = unitDraft.status === "Occupied" && unitDraft.tenant;
            window.WB_UNITS[name].push({ label: unitDraft.label.trim(), status: occupied ? "Occupied" : "Vacant", tenant: occupied ? unitDraft.tenant : undefined });
            modal.units = (modal.units || 0) + 1;
            if (!occupied) modal.vacant = (modal.vacant || 0) + 1;
            setAddUnit(false); force(); window.WBToast(unitDraft.label.trim() + " added to " + name);
          }}>Add Unit</Button></React.Fragment>}>
          <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
            <Input label="Unit label" placeholder="e.g. House 17" value={unitDraft.label} onChange={(e) => setUnitDraft((d) => ({ ...d, label: e.target.value }))} />
            <Select label="Status" value={unitDraft.status} onChange={(e) => setUnitDraft((d) => ({ ...d, status: e.target.value, tenant: e.target.value === "Vacant" ? "" : d.tenant }))} options={["Vacant", "Occupied"]} />
            {unitDraft.status === "Occupied" && (
              <Select label="Assign tenant" value={unitDraft.tenant || ""} onChange={(e) => setUnitDraft((d) => ({ ...d, tenant: e.target.value }))} options={["Select a tenant…", ...window.WB_TENANT_NAMES]} />
            )}
          </div>
        </Modal>
        {/* Edit property modal */}
        <Modal open={editP} onClose={() => setEditP(false)} icon="pencil" title="Edit Property" subtitle={pDraft && pDraft.name} width={480}
          footer={<React.Fragment><Button variant="secondary" onClick={() => setEditP(false)}>Cancel</Button><Button variant="primary" icon="check" onClick={() => { Object.assign(modal, pDraft); setEditP(false); force(); window.WBToast("Property updated"); }}>Save Changes</Button></React.Fragment>}>
          {pDraft && (
            <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
              <Input label="Property name" value={pDraft.name} onChange={(e) => setPDraft((d) => ({ ...d, name: e.target.value }))} />
              <div style={{ display: "flex", gap: 14 }}>
                <Select label="Type" value={pDraft.type} onChange={(e) => setPDraft((d) => ({ ...d, type: e.target.value }))} options={["Townhouses", "Villas", "Apartments", "Lofts"]} containerStyle={{ flex: 1 }} />
                <Select label="Status" value={pDraft.status} onChange={(e) => setPDraft((d) => ({ ...d, status: e.target.value }))} options={["Standard", "Premium", "Flagship"]} containerStyle={{ flex: 1 }} />
              </div>
              <window.WBImageUpload label="Replace photos" />
            </div>
          )}
        </Modal>
      </div>
    );
  }
  window.PropertiesScreen = PropertiesScreen;
})();
