/* PrimaDelta — admin app. Exports to window. */
const { Logo, Btn, Status, Badge, Field, Input, Textarea, Select, Modal, Empty, Ic } = window;
const { useStore, fmt } = window;

/* ============================================================
   LOGIN
   ============================================================ */
function Login() {
  const { login, nav } = useStore();
  const [email, setEmail] = React.useState("a.reyes@primadelta.com");
  const [pw, setPw] = React.useState("demo");
  const [busy, setBusy] = React.useState(false);
  const submit = (e) => {
    e.preventDefault();
    setBusy(true);
    setTimeout(() => { login(); nav("dashboard"); }, 450);
  };
  return (
    <div className="login-wrap">
      <div className="login-art">
        <div style={{ position: "relative", zIndex: 2 }}>
          <Logo light size={32} onClick={() => nav("home")} />
        </div>
        <div style={{ position: "relative", zIndex: 2 }}>
          <div className="eyebrow muted">Operations Platform</div>
          <h2 className="serif" style={{ fontSize: 40, fontWeight: 500, color: "#fff", marginTop: 14, lineHeight: 1.1 }}>
            Manage the<br />portfolio with<br />one source of truth.
          </h2>
          <p className="muted" style={{ marginTop: 18, fontSize: 15.5, maxWidth: 380, lineHeight: 1.6 }}>
            Asset register, maintenance, documents and enquiries — secured behind a single admin login.
          </p>
        </div>
        <div style={{ position: "absolute", inset: 0, opacity: .5 }}>
          <div className="ph dark" style={{ position: "absolute", inset: 0 }}></div>
        </div>
        <div className="flex gap-24" style={{ position: "relative", zIndex: 2 }}>
          {[["6", "Managed assets"], ["1.1M", "Sq ft"], ["94%", "Occupancy"]].map(([n, l]) => (
            <div key={l}><div className="serif" style={{ fontSize: 28, fontWeight: 500, color: "#fff" }}>{n}</div><div className="muted" style={{ fontSize: 12.5 }}>{l}</div></div>
          ))}
        </div>
      </div>
      <div className="login-form-side">
        <div className="login-card">
          <div style={{ display: "none" }}><Logo onClick={() => nav("home")} /></div>
          <div className="eyebrow">Admin access</div>
          <h1 className="serif" style={{ fontSize: 34, fontWeight: 500, marginTop: 12 }}>Sign in</h1>
          <p className="muted" style={{ fontSize: 14.5, marginTop: 8 }}>Use the pre-filled demo credentials to enter.</p>
          <form onSubmit={submit} style={{ marginTop: 28, display: "flex", flexDirection: "column", gap: 16 }}>
            <Field label="Work email"><Input type="email" value={email} onChange={(e) => setEmail(e.target.value)} /></Field>
            <Field label="Password"><Input type="password" value={pw} onChange={(e) => setPw(e.target.value)} /></Field>
            <div className="flex between items-center" style={{ fontSize: 13.5 }}>
              <label className="flex items-center gap-8" style={{ color: "var(--ink-soft)", cursor: "pointer" }}><input type="checkbox" defaultChecked /> Remember me</label>
              <a className="link" style={{ fontSize: 13.5 }}>Forgot password?</a>
            </div>
            <Btn variant="primary" size="lg" block type="submit" disabled={busy}>{busy ? "Signing in…" : "Sign in to dashboard"}</Btn>
          </form>
          <div style={{ marginTop: 22, padding: 14, background: "var(--clay-tint)", borderRadius: 10, fontSize: 13, color: "var(--ink-soft)" }}>
            <strong style={{ color: "var(--clay)" }}>Demo:</strong> credentials are pre-filled — just click sign in. This is a prototype; no real authentication.
          </div>
          <div className="center" style={{ marginTop: 22 }}>
            <a className="link" style={{ color: "var(--muted)" }} onClick={() => nav("home")}><Ic.arrowL s={15} /> Back to website</a>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ============================================================
   ADMIN SHELL
   ============================================================ */
function AdminShell({ children }) {
  const { route, nav, logout, data } = useStore();
  const openMaint = data.maintenance.filter((m) => m.status !== "Completed").length;
  const unread = data.inbox.filter((c) => !c.read).length;
  const NAV = [
    { sec: "Overview" },
    { v: "dashboard", l: "Dashboard", i: <Ic.dashboard s={18} /> },
    { sec: "Operations" },
    { v: "assets", l: "Asset Register", i: <Ic.layers s={18} />, count: data.assets.length },
    { v: "maintenance", l: "Maintenance", i: <Ic.wrench s={18} />, count: openMaint },
    { v: "vault", l: "Document Vault", i: <Ic.folder s={18} /> },
    { v: "inbox", l: "Enquiries", i: <Ic.mail s={18} />, count: unread || null },
  ];
  const titles = { dashboard: "Dashboard", assets: "Asset Register", maintenance: "Maintenance", vault: "Document Vault", inbox: "Enquiries" };
  return (
    <div className="admin">
      <aside className="sidebar">
        <div className="sidebar-top"><Logo light size={26} onClick={() => nav("dashboard")} /></div>
        <nav className="sidebar-nav">
          {NAV.map((n, i) => n.sec
            ? <div key={i} className="sidebar-sec">{n.sec}</div>
            : <a key={n.v} className={"snav" + (route.view === n.v ? " active" : "")} onClick={() => nav(n.v)}>
                {n.i}<span>{n.l}</span>{n.count != null && <span className="count">{n.count}</span>}
              </a>
          )}
        </nav>
        <div className="sidebar-foot">
          <a className="snav" onClick={() => nav("home")} style={{ marginBottom: 4 }}><Ic.building s={18} /><span>View website</span></a>
          <div className="user-chip">
            <div className="avatar">AR</div>
            <div style={{ minWidth: 0, flex: 1 }}>
              <div style={{ fontSize: 13.5, fontWeight: 600, color: "#fff", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>Ana Reyes</div>
              <div style={{ fontSize: 11.5, color: "rgba(255,255,255,.5)" }}>Portfolio Admin</div>
            </div>
            <button className="btn-icon ghost" style={{ color: "rgba(255,255,255,.6)", width: 32, height: 32 }} title="Sign out" onClick={() => { logout(); nav("home"); }}><Ic.logout s={17} /></button>
          </div>
        </div>
      </aside>
      <div className="admin-main">
        <div className="topbar">
          <div style={{ fontWeight: 600, fontSize: 15.5 }}>{titles[route.view] || "Admin"}</div>
          <div className="flex items-center gap-16">
            <div className="search"><Ic.search s={16} /><input placeholder="Search portfolio…" /></div>
            <button className="btn-icon" title="Notifications" style={{ position: "relative" }}>
              <Ic.bell s={18} />
              {unread > 0 && <span style={{ position: "absolute", top: 6, right: 6, width: 7, height: 7, borderRadius: "50%", background: "var(--clay)" }}></span>}
            </button>
          </div>
        </div>
        <div className="admin-content fade-in" key={route.view}>{children}</div>
      </div>
    </div>
  );
}

/* ============================================================
   DASHBOARD
   ============================================================ */
function Dashboard() {
  const { data, nav, estates } = useStore();
  const openMaint = data.maintenance.filter((m) => m.status !== "Completed");
  const highPri = openMaint.filter((m) => m.priority === "High").length;
  const portfolioVal = estates.reduce((s, e) => s + parseFloat(e.value), 0);
  const tiles = [
    { i: <Ic.coins s={16} />, l: "Portfolio value", v: "$" + portfolioVal.toFixed(0) + "M", d: "+4.2% YoY", up: true },
    { i: <Ic.layers s={16} />, l: "Tracked assets", v: data.assets.length, d: "Across 2 properties" },
    { i: <Ic.wrench s={16} />, l: "Open maintenance", v: openMaint.length, d: highPri + " high priority", up: false },
    { i: <Ic.mail s={16} />, l: "New enquiries", v: data.inbox.filter((c) => !c.read).length, d: "Awaiting response" },
  ];
  const months = [["Jan", 58], ["Feb", 62], ["Mar", 55], ["Apr", 71], ["May", 68], ["Jun", 64]];
  const activity = [
    { ic: <Ic.mail s={16} />, t: <span><strong>New enquiry</strong> from Helena Forsythe — investment / JV</span>, m: "Today · 14:22" },
    { ic: <Ic.wrench s={16} />, t: <span>Maintenance <strong>MR-2061</strong> moved to In Progress</span>, m: "Today · 11:08" },
    { ic: <Ic.file s={16} />, t: <span><strong>ESG Report H1 2026</strong> uploaded to vault</span>, m: "Yesterday" },
    { ic: <Ic.check s={16} />, t: <span><strong>MR-2049</strong> fire damper test completed by Sentinel</span>, m: "2 days ago" },
  ];
  return (
    <div>
      <div className="page-head">
        <div>
          <h1>Good morning, Ana</h1>
          <p className="sub">Portfolio status at a glance — Wednesday, 11 June 2026.</p>
        </div>
        <div className="flex gap-12">
          <Btn variant="ghost" icon={<Ic.wrench s={16} />} onClick={() => nav("maintenance")}>Maintenance</Btn>
          <Btn variant="clay" icon={<Ic.plus s={16} />} onClick={() => nav("assets", { create: 1 })}>New asset</Btn>
        </div>
      </div>

      <div className="stat-grid">
        {tiles.map((t) => (
          <div className="stat-tile" key={t.l}>
            <div className="label"><span className="ic">{t.i}</span>{t.l}</div>
            <div className="big">{t.v}</div>
            {t.d && <div className={"delta " + (t.up === true ? "up" : t.up === false ? "down" : "")} style={t.up == null ? { color: "var(--muted)" } : {}}>{t.d}</div>}
          </div>
        ))}
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1.5fr 1fr", gap: 20, marginTop: 20 }}>
        <div className="panel">
          <div className="flex between items-center" style={{ marginBottom: 20 }}>
            <div><h3 style={{ fontSize: 17, fontWeight: 600 }}>Net operating income</h3><p className="muted" style={{ fontSize: 13, marginTop: 2 }}>Managed portfolio · $M / month</p></div>
            <Badge tone="done"><Ic.trend s={13} /> +6.1%</Badge>
          </div>
          <div className="chart">
            {months.map(([m, v], i) => (
              <div className="col" key={m}>
                <div className={"bk" + (i === months.length - 1 ? " alt" : "")} style={{ height: v + "%" }}></div>
                <div className="lab">{m}</div>
              </div>
            ))}
          </div>
        </div>
        <div className="panel">
          <h3 style={{ fontSize: 17, fontWeight: 600, marginBottom: 14 }}>Recent activity</h3>
          <div className="activity">
            {activity.map((a, i) => (
              <div className="act-item" key={i}>
                <div className="act-dot">{a.ic}</div>
                <div><div className="at">{a.t}</div><div className="am">{a.m}</div></div>
              </div>
            ))}
          </div>
        </div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 20, marginTop: 20 }}>
        <div className="panel">
          <div className="flex between items-center" style={{ marginBottom: 16 }}>
            <h3 style={{ fontSize: 17, fontWeight: 600 }}>Priority maintenance</h3>
            <a className="link" style={{ fontSize: 13.5 }} onClick={() => nav("maintenance")}>View all <Ic.arrow s={14} /></a>
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            {openMaint.slice(0, 3).map((m) => (
              <div key={m.id} className="flex between items-center" style={{ padding: "10px 12px", border: "1px solid var(--line)", borderRadius: 10, cursor: "pointer" }} onClick={() => nav("maintenance", { open: m.id })}>
                <div style={{ minWidth: 0 }}>
                  <div style={{ fontSize: 14, fontWeight: 600, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{m.title}</div>
                  <div className="muted" style={{ fontSize: 12.5 }}>{m.id} · {m.property}</div>
                </div>
                <PriPill p={m.priority} />
              </div>
            ))}
          </div>
        </div>
        <div className="panel">
          <h3 style={{ fontSize: 17, fontWeight: 600, marginBottom: 16 }}>Occupancy by asset</h3>
          <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
            {estates.filter((e) => e.kind === "property").map((e) => (
              <div key={e.id}>
                <div className="flex between" style={{ fontSize: 14, marginBottom: 6 }}><span style={{ fontWeight: 600 }}>{e.name}</span><span className="muted">{e.occupancy}%</span></div>
                <div className="bar"><span style={{ width: e.occupancy + "%" }}></span></div>
              </div>
            ))}
            <div style={{ borderTop: "1px solid var(--line)", paddingTop: 14, marginTop: 4 }}>
              <div className="muted" style={{ fontSize: 13 }}>Developments in delivery</div>
              {estates.filter((e) => e.kind === "project").map((e) => (
                <div key={e.id} className="flex between items-center" style={{ marginTop: 10 }}>
                  <span style={{ fontSize: 14, fontWeight: 600 }}>{e.name}</span>
                  <span className="muted" style={{ fontSize: 13 }}>{e.progress}% built</span>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function PriPill({ p }) {
  const map = { High: "open", Medium: "hold", Low: "neutral" };
  return <span className={"badge badge-" + (map[p] || "neutral")}>{p}</span>;
}

/* ============================================================
   ASSET REGISTER
   ============================================================ */
function AssetRegister() {
  const { data, addAsset, toast, route, estates } = useStore();
  const [creating, setCreating] = React.useState(!!route.params.create);
  const [view, setView] = React.useState(null);
  const [q, setQ] = React.useState("");
  const props = estates.map((e) => e.name);
  const filtered = data.assets.filter((a) => (a.name + a.id + a.property + a.category).toLowerCase().includes(q.toLowerCase()));
  const totalVal = data.assets.reduce((s, a) => s + a.value, 0);

  return (
    <div>
      <div className="page-head">
        <div><h1>Asset Register</h1><p className="sub">Physical assets across the managed portfolio — {data.assets.length} records, {fmt.money(totalVal)} book value.</p></div>
        <Btn variant="clay" icon={<Ic.plus s={16} />} onClick={() => setCreating(true)}>New asset record</Btn>
      </div>

      <div className="flex between items-center" style={{ marginBottom: 16, flexWrap: "wrap", gap: 12 }}>
        <div className="search"><Ic.search s={16} /><input placeholder="Search assets…" value={q} onChange={(e) => setQ(e.target.value)} style={{ width: 320 }} /></div>
        <div className="muted" style={{ fontSize: 13.5 }}>{filtered.length} of {data.assets.length} shown</div>
      </div>

      <div className="card" style={{ overflow: "hidden" }}>
        <div className="scrollx">
          <table className="tbl">
            <thead><tr>
              <th>Asset ID</th><th>Name</th><th>Category</th><th>Property</th><th>Acquired</th><th>Condition</th><th>Status</th><th className="num">Value</th>
            </tr></thead>
            <tbody>
              {filtered.map((a) => (
                <tr key={a.id} style={{ cursor: "pointer" }} onClick={() => setView(a)}>
                  <td style={{ fontWeight: 600, fontVariantNumeric: "tabular-nums" }}>{a.id}</td>
                  <td style={{ fontWeight: 600 }}>{a.name}</td>
                  <td className="muted">{a.category}</td>
                  <td>{a.property}</td>
                  <td className="muted num">{fmt.date(a.acquired)}</td>
                  <td><CondPill c={a.condition} /></td>
                  <td><Status label={a.status} /></td>
                  <td className="num" style={{ fontWeight: 600, textAlign: "right" }}>{fmt.money(a.value)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        {filtered.length === 0 && <Empty icon={<Ic.layers s={26} />} title="No matching assets" sub="Adjust your search or add a new asset record." />}
      </div>

      {creating && <AssetForm props={props} onClose={() => setCreating(false)} onSave={(a) => { const id = addAsset(a); setCreating(false); toast("Asset created", id + " added to the register.", <Ic.layers s={18} />); }} />}
      {view && <AssetView a={view} onClose={() => setView(null)} />}
    </div>
  );
}

function CondPill({ c }) {
  const map = { Excellent: "done", Good: "prog", Fair: "hold", Poor: "open" };
  return <span className={"badge badge-" + (map[c] || "neutral")}><span className="dot"></span>{c}</span>;
}

function AssetForm({ props, onClose, onSave }) {
  const [f, setF] = React.useState({ name: "", category: "HVAC Plant", property: props[3] || props[0], acquired: "2026-06-11", value: "", condition: "Good", status: "In Service" });
  const set = (k) => (e) => setF((s) => ({ ...s, [k]: e.target.value }));
  const valid = f.name.trim() && f.value;
  const cats = ["HVAC Plant", "Vertical Transport", "Renewables", "Fire & Life Safety", "Controls", "Power", "Building Fabric", "Other"];
  return (
    <Modal title="New asset record" sub="Add a physical asset to the register." onClose={onClose}
      footer={<><Btn variant="ghost" onClick={onClose}>Cancel</Btn><Btn variant="clay" disabled={!valid} icon={<Ic.check s={16} />} onClick={() => onSave({ ...f, value: parseInt(f.value, 10) || 0 })}>Create record</Btn></>}>
      <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
        <Field label="Asset name" req><Input value={f.name} onChange={set("name")} placeholder="e.g. Chiller Plant — Unit B" autoFocus /></Field>
        <div className="field-row">
          <Field label="Category"><Select value={f.category} onChange={set("category")}>{cats.map((c) => <option key={c}>{c}</option>)}</Select></Field>
          <Field label="Property"><Select value={f.property} onChange={set("property")}>{props.map((p) => <option key={p}>{p}</option>)}</Select></Field>
        </div>
        <div className="field-row">
          <Field label="Acquisition date"><Input type="date" value={f.acquired} onChange={set("acquired")} /></Field>
          <Field label="Book value (USD)" req><Input type="number" value={f.value} onChange={set("value")} placeholder="250000" /></Field>
        </div>
        <div className="field-row">
          <Field label="Condition"><Select value={f.condition} onChange={set("condition")}>{["Excellent", "Good", "Fair", "Poor"].map((c) => <option key={c}>{c}</option>)}</Select></Field>
          <Field label="Status"><Select value={f.status} onChange={set("status")}>{["In Service", "Under Review", "Out of Service"].map((c) => <option key={c}>{c}</option>)}</Select></Field>
        </div>
      </div>
    </Modal>
  );
}

function AssetView({ a, onClose }) {
  return (
    <Modal title={a.name} sub={a.id + " · " + a.category} onClose={onClose}
      footer={<Btn variant="ghost" onClick={onClose}>Close</Btn>}>
      <div className="spec">
        {[["Property", a.property], ["Category", a.category], ["Acquired", fmt.date(a.acquired)], ["Book value", fmt.money(a.value)], ["Condition", a.condition], ["Status", a.status]].map(([k, v]) => (
          <div className="cell" key={k}><div className="k">{k}</div><div className="v" style={{ fontSize: 16 }}>{v}</div></div>
        ))}
      </div>
    </Modal>
  );
}

/* ============================================================
   MAINTENANCE
   ============================================================ */
function Maintenance() {
  const { data, vendors, addMaintenance, updateMaintenance, toast, route, estates } = useStore();
  const [creating, setCreating] = React.useState(false);
  const [open, setOpen] = React.useState(route.params.open || null);
  const [filter, setFilter] = React.useState("active");
  const props = estates.map((e) => e.name);

  const list = data.maintenance.filter((m) => {
    if (filter === "active") return m.status !== "Completed";
    if (filter === "completed") return m.status === "Completed";
    return true;
  });
  const openItem = data.maintenance.find((m) => m.id === open);

  return (
    <div>
      <div className="page-head">
        <div><h1>Maintenance</h1><p className="sub">Create requests, assign vendors and track status across the portfolio.</p></div>
        <Btn variant="clay" icon={<Ic.plus s={16} />} onClick={() => setCreating(true)}>New request</Btn>
      </div>

      <div className="flex between items-center" style={{ marginBottom: 16, flexWrap: "wrap", gap: 12 }}>
        <div className="tabs">
          {[["active", "Active"], ["completed", "Completed"], ["all", "All"]].map(([k, l]) => (
            <button key={k} className={"tab" + (filter === k ? " active" : "")} onClick={() => setFilter(k)}>{l}
              {k === "active" && <span style={{ marginLeft: 6, opacity: .7 }}>{data.maintenance.filter((m) => m.status !== "Completed").length}</span>}
            </button>
          ))}
        </div>
      </div>

      <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
        {list.map((m) => {
          const v = vendors.find((x) => x.id === m.vendor);
          return (
            <div key={m.id} className="card" style={{ padding: 18, cursor: "pointer", display: "flex", gap: 18, alignItems: "center" }} onClick={() => setOpen(m.id)}>
              <div style={{ minWidth: 0, flex: 1 }}>
                <div className="flex items-center gap-12" style={{ marginBottom: 6, flexWrap: "wrap" }}>
                  <span style={{ fontWeight: 600, fontSize: 15.5 }}>{m.title}</span>
                  <PriPill p={m.priority} />
                </div>
                <div className="muted" style={{ fontSize: 13 }}>{m.id} · {m.property} · reported {fmt.rel(m.reported)}{v ? " · " + v.name : ""}</div>
              </div>
              <Status label={m.status} />
              <Ic.chevR s={18} style={{ color: "var(--muted-2)" }} />
            </div>
          );
        })}
        {list.length === 0 && <div className="card"><Empty icon={<Ic.wrench s={26} />} title="Nothing here" sub="No requests match this filter." /></div>}
      </div>

      {creating && <MaintForm props={props} vendors={vendors} onClose={() => setCreating(false)}
        onSave={(m) => { const id = addMaintenance(m); setCreating(false); toast("Request logged", id + (m.vendor ? " created and assigned." : " created."), <Ic.wrench s={18} />); }} />}
      {openItem && <MaintDetail m={openItem} vendors={vendors}
        onClose={() => setOpen(null)}
        onUpdate={(patch, msg) => { updateMaintenance(openItem.id, patch); if (msg) toast(msg.t, msg.s, <Ic.check s={18} />); }} />}
    </div>
  );
}

function MaintForm({ props, vendors, onClose, onSave }) {
  const [f, setF] = React.useState({ title: "", property: props[3] || props[0], priority: "Medium", vendor: "", desc: "", reported: "2026-06-11" });
  const set = (k) => (e) => setF((s) => ({ ...s, [k]: e.target.value }));
  const valid = f.title.trim() && f.desc.trim();
  return (
    <Modal title="New maintenance request" sub="Log an issue and optionally assign a vendor now." onClose={onClose}
      footer={<><Btn variant="ghost" onClick={onClose}>Cancel</Btn><Btn variant="clay" disabled={!valid} icon={<Ic.check s={16} />} onClick={() => onSave({ ...f, vendor: f.vendor || null, asset: null })}>Create request</Btn></>}>
      <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
        <Field label="Title" req><Input value={f.title} onChange={set("title")} placeholder="e.g. Lobby HVAC — uneven cooling" autoFocus /></Field>
        <div className="field-row">
          <Field label="Property"><Select value={f.property} onChange={set("property")}>{props.map((p) => <option key={p}>{p}</option>)}</Select></Field>
          <Field label="Priority"><Select value={f.priority} onChange={set("priority")}>{["High", "Medium", "Low"].map((p) => <option key={p}>{p}</option>)}</Select></Field>
        </div>
        <Field label="Assign vendor" hint="Leave blank to triage later — status will be 'Open'.">
          <Select value={f.vendor} onChange={set("vendor")}>
            <option value="">— Unassigned —</option>
            {vendors.map((v) => <option key={v.id} value={v.id}>{v.name} · {v.trade}</option>)}
          </Select>
        </Field>
        <Field label="Description" req><Textarea value={f.desc} onChange={set("desc")} placeholder="Describe the fault, location and any access notes…" /></Field>
      </div>
    </Modal>
  );
}

const FLOW = ["Open", "Assigned", "In Progress", "Completed"];
function MaintDetail({ m, vendors, onClose, onUpdate }) {
  const [vsel, setVsel] = React.useState(m.vendor || "");
  const vendor = vendors.find((x) => x.id === m.vendor);
  const stepIdx = FLOW.indexOf(m.status);
  const next = FLOW[stepIdx + 1];

  const assign = () => {
    if (!vsel) return;
    const v = vendors.find((x) => x.id === vsel);
    onUpdate({ vendor: vsel, status: m.status === "Open" ? "Assigned" : m.status }, { t: "Vendor assigned", s: v.name + " assigned to " + m.id });
  };
  const advance = () => {
    if (!next) return;
    onUpdate({ status: next }, { t: "Status updated", s: m.id + " → " + next });
  };

  return (
    <Modal wide title={m.title} sub={m.id + " · " + m.property} onClose={onClose}
      footer={<>
        <Btn variant="ghost" onClick={onClose}>Close</Btn>
        {next && <Btn variant="primary" icon={<Ic.arrow s={16} />} onClick={advance}>Mark as {next}</Btn>}
        {!next && <Badge tone="done"><Ic.check s={14} /> Completed</Badge>}
      </>}>
      <div className="flex gap-12" style={{ marginBottom: 18, flexWrap: "wrap" }}>
        <Status label={m.status} /><PriPill p={m.priority} />
        <span className="muted" style={{ fontSize: 13, alignSelf: "center" }}>Reported {fmt.date(m.reported)} by {m.reporter}</span>
      </div>

      {/* status stepper */}
      <div style={{ display: "flex", alignItems: "center", marginBottom: 22 }}>
        {FLOW.map((s, i) => (
          <React.Fragment key={s}>
            <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 6 }}>
              <div style={{ width: 28, height: 28, borderRadius: "50%", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 13, fontWeight: 700,
                background: i <= stepIdx ? "var(--clay)" : "var(--paper-2)", color: i <= stepIdx ? "#fff" : "var(--muted)" }}>
                {i < stepIdx ? <Ic.check s={15} /> : i + 1}
              </div>
              <span style={{ fontSize: 11.5, fontWeight: 600, color: i <= stepIdx ? "var(--ink)" : "var(--muted)" }}>{s}</span>
            </div>
            {i < FLOW.length - 1 && <div style={{ flex: 1, height: 2, background: i < stepIdx ? "var(--clay)" : "var(--line)", margin: "0 8px", marginBottom: 18 }}></div>}
          </React.Fragment>
        ))}
      </div>

      <div className="panel" style={{ marginBottom: 16 }}>
        <div className="muted" style={{ fontSize: 12, fontWeight: 700, textTransform: "uppercase", letterSpacing: ".06em" }}>Description</div>
        <p style={{ fontSize: 14.5, lineHeight: 1.6, marginTop: 8 }}>{m.desc}</p>
      </div>

      <div className="panel">
        <div className="flex between items-center" style={{ marginBottom: 12 }}>
          <div className="muted" style={{ fontSize: 12, fontWeight: 700, textTransform: "uppercase", letterSpacing: ".06em" }}>Vendor assignment</div>
          {vendor && <Badge tone="prog">Assigned</Badge>}
        </div>
        {vendor ? (
          <div className="flex between items-center">
            <div className="flex items-center gap-12">
              <div className="avatar" style={{ background: "var(--ink)" }}>{vendor.name.split(" ").map((w) => w[0]).slice(0, 2).join("")}</div>
              <div>
                <div style={{ fontWeight: 600, fontSize: 14.5 }}>{vendor.name}</div>
                <div className="muted" style={{ fontSize: 13 }}>{vendor.trade} · ★ {vendor.rating} · {vendor.jobs} jobs</div>
              </div>
            </div>
            {m.status !== "Completed" && <Btn variant="soft" size="sm" onClick={() => onUpdate({ vendor: null, status: "Open" }, { t: "Vendor removed", s: m.id + " returned to Open" })}>Unassign</Btn>}
          </div>
        ) : (
          <div className="flex gap-12" style={{ alignItems: "flex-end" }}>
            <div style={{ flex: 1 }}>
              <Field label="Select a vendor">
                <Select value={vsel} onChange={(e) => setVsel(e.target.value)}>
                  <option value="">— Choose vendor —</option>
                  {vendors.map((v) => <option key={v.id} value={v.id}>{v.name} · {v.trade} · ★{v.rating}</option>)}
                </Select>
              </Field>
            </div>
            <Btn variant="clay" disabled={!vsel} onClick={assign}>Assign</Btn>
          </div>
        )}
      </div>
    </Modal>
  );
}

Object.assign(window, { Login, AdminShell, Dashboard, AssetRegister, Maintenance });
