// Woodbury Operator — Move-in / Move-out flow. Registers window.MoveScreen.
(function () {
  const NS = window.WoodburyPropertiesDesignSystem_7290ca;
  const { Card, CardHeader, Button, Badge, Avatar, IconTile, Eyebrow, ProgressBar, Modal, Select, Input } = NS;

  const STEPS = {
    "Move-in": [
      { label: "Assign unit", icon: "link", note: "Link the tenant to a vacant unit." },
      { label: "Move-in inspection", icon: "clipboard-check", note: "Document unit condition with photos." },
      { label: "Collect documents", icon: "file-text", note: "Signed tenancy agreement & ID on file." },
      { label: "Activate lease", icon: "file-signature", note: "Lease start date confirmed." },
      { label: "Hand over keys", icon: "key-round", note: "Keys, gate remote & access code issued." },
    ],
    "Move-out": [
      { label: "Notice logged", icon: "calendar-x", note: "Move-out date recorded." },
      { label: "Move-out inspection", icon: "clipboard-check", note: "Condition vs. move-in report." },
      { label: "Condition report", icon: "file-warning", note: "Damages / repairs noted for follow-up." },
      { label: "Unlink unit", icon: "unlink", note: "Free the unit for new applicants." },
      { label: "Close tenancy", icon: "check-check", note: "Archive record & revoke access." },
    ],
  };

  const SEED = [
    { id: "MV-3007", type: "Move-in", tenant: "Adjoa Mensah", avatar: "../../assets/images/av-ama.jpg", property: "Lashibi Townhouses", unit: "House 3", date: "22 Aug 2026", step: 2 },
    { id: "MV-3005", type: "Move-out", tenant: "Nana Adjei", avatar: "../../assets/images/av-nana.jpg", property: "Onehive Tse Addo", unit: "Unit 101", date: "31 Aug 2026", step: 1 },
    { id: "MV-2998", type: "Move-in", tenant: "Kwabena Osei", avatar: "../../assets/images/avatar-1.jpg", property: "Cantonments City", unit: "Apt 5A", date: "05 Aug 2026", step: 5 },
  ];

  function MoveScreen() {
    const loading = window.WBuseLoad();
    const canManage = window.WBCan("move.manage");
    const [moves, setMoves] = React.useState(SEED);
    const fromScreening = window.WBuseNew("moves");
    const allMoves = [...fromScreening.slice().reverse(), ...moves];
    const [sel, setSel] = React.useState(null);
    const [nw, setNw] = React.useState(false);
    const [draft, setDraft] = React.useState({ type: "Move-in", tenant: "", property: window.WB_SITES[0], unit: "", date: "" });
    const current = allMoves.find((m) => m.id === sel);

    const advance = (m) => {
      const steps = STEPS[m.type];
      const inSeed = moves.some((x) => x.id === m.id);
      if (inSeed) {
        setMoves((list) => list.map((x) => x.id === m.id ? { ...x, step: Math.min(steps.length, x.step + 1) } : x));
      } else {
        const it = window.WB_NEW.moves.find((x) => x.id === m.id);
        if (it) { it.step = Math.min(steps.length, it.step + 1); window.WBbus.dispatchEvent(new CustomEvent("moves")); }
      }
      window.WBToast(m.step >= steps.length ? "Move complete" : "Step completed: " + steps[m.step].label);
    };

    if (current) {
      const steps = STEPS[current.type];
      const pct = Math.round((current.step / steps.length) * 100);
      return (
        <div style={{ display: "flex", flexDirection: "column", gap: 24, padding: "36px 40px", maxWidth: 1000 }}>
          <window.WBPageHeader eyebrow={current.type + " · " + current.id} title={current.tenant}
            sub={current.property + " · " + current.unit + " · " + current.date}
            actions={<Button variant="secondary" icon="arrow-left" onClick={() => setSel(null)}>Back</Button>} />
          <Card style={{ padding: 28 }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 14, flexWrap: "wrap", gap: 12 }}>
              <Badge tone={current.type === "Move-in" ? "success" : "warning"}>{current.type}</Badge>
              <span style={{ fontSize: 13, color: "var(--text-muted)" }}>{current.step} of {steps.length} steps · {pct}%</span>
            </div>
            <ProgressBar value={pct} tone={current.type === "Move-in" ? "success" : "accent"} />
          </Card>
          <Card>
            <CardHeader title={current.type + " Checklist"} action={current.step >= steps.length ? <Badge tone="success" dot>Complete</Badge> : null} />
            <div style={{ padding: "8px 0" }}>
              {steps.map((s, i) => {
                const done = i < current.step, active = i === current.step;
                return (
                  <div key={s.label} style={{ display: "flex", gap: 16, alignItems: "center", padding: "16px 28px", borderTop: i ? "1px solid var(--border)" : "none", opacity: !done && !active ? 0.55 : 1 }}>
                    <div style={{ width: 40, height: 40, flexShrink: 0, borderRadius: "var(--radius-md)", background: done ? "var(--success-bg)" : active ? "var(--walnut-100)" : "var(--cream-100)", display: "flex", alignItems: "center", justifyContent: "center" }}>
                      <span className="wb-ico" style={{ width: 18, height: 18, color: done ? "var(--success)" : active ? "var(--walnut-700)" : "var(--text-muted)" }}><i data-lucide={done ? "check" : s.icon}></i></span>
                    </div>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontWeight: 700, fontSize: 15, color: "var(--text-heading)" }}>{s.label}</div>
                      <div style={{ fontSize: 13, color: "var(--text-muted)" }}>{s.note}</div>
                    </div>
                    {done && <Badge tone="success">Done</Badge>}
                    {active && canManage && <Button variant="primary" size="sm" onClick={() => advance(current)}>Mark done</Button>}
                    {active && !canManage && <Badge tone="warning">Pending</Badge>}
                  </div>
                );
              })}
            </div>
          </Card>
        </div>
      );
    }

    const inProg = allMoves.filter((m) => m.step < STEPS[m.type].length);
    const done = allMoves.filter((m) => m.step >= STEPS[m.type].length);
    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 24, padding: "36px 40px", maxWidth: 1200 }}>
        <window.WBPageHeader eyebrow="Tenancy Lifecycle" title="Move-In / Move-Out"
          sub="Guided flows for onboarding and offboarding residents."
          actions={canManage ? <Button variant="primary" icon="plus" onClick={() => setNw(true)}>Start Move</Button> : null} />
        <Card>
          <CardHeader title="In Progress" action={<Badge tone="neutral">{inProg.length}</Badge>} />
          {loading ? <window.WBSkeletonRows rows={3} cols={4} /> : inProg.length === 0 ? (
            <window.WBEmpty icon="truck" title="No moves in progress" message="Start a move-in or move-out to guide it step by step." action={canManage ? <Button variant="primary" size="sm" icon="plus" onClick={() => setNw(true)}>Start Move</Button> : null} />
          ) : inProg.map((m, i) => {
            const steps = STEPS[m.type]; const pct = Math.round((m.step / steps.length) * 100);
            return (
              <div key={m.id} onClick={() => setSel(m.id)} style={{ display: "grid", gridTemplateColumns: "1.5fr 1.3fr 1fr 0.6fr", gap: 20, alignItems: "center", padding: "18px 24px", borderTop: i ? "1px solid var(--border)" : "none", cursor: "pointer" }}>
                <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
                  <Avatar src={m.avatar} name={m.tenant} size={42} />
                  <div><div style={{ fontWeight: 700, fontSize: 15, color: "var(--text-heading)" }}>{m.tenant}</div><div style={{ fontSize: 12, color: "var(--text-muted)" }}>{m.id} · {m.date}</div></div>
                </div>
                <div><div style={{ fontSize: 14, color: "var(--text-heading)" }}>{m.property}</div><div style={{ fontSize: 12, color: "var(--text-muted)" }}>{m.unit}</div></div>
                <div><div style={{ display: "flex", justifyContent: "space-between", fontSize: 11, color: "var(--text-muted)", marginBottom: 5 }}><span>{steps[m.step] ? steps[m.step].label : "Done"}</span><span>{pct}%</span></div><ProgressBar value={pct} tone={m.type === "Move-in" ? "success" : "accent"} /></div>
                <div style={{ textAlign: "right" }}><Badge tone={m.type === "Move-in" ? "success" : "warning"}>{m.type}</Badge></div>
              </div>
            );
          })}
        </Card>
        {!loading && done.length > 0 && (
          <Card>
            <CardHeader title="Completed" action={<Badge tone="neutral">{done.length}</Badge>} />
            {done.map((m, i) => (
              <div key={m.id} onClick={() => setSel(m.id)} style={{ display: "flex", gap: 14, alignItems: "center", padding: "16px 24px", borderTop: i ? "1px solid var(--border)" : "none", cursor: "pointer" }}>
                <Avatar src={m.avatar} name={m.tenant} size={38} />
                <div style={{ flex: 1 }}><div style={{ fontWeight: 700, fontSize: 14, color: "var(--text-heading)" }}>{m.tenant}</div><div style={{ fontSize: 12, color: "var(--text-muted)" }}>{m.property} · {m.unit} · {m.date}</div></div>
                <Badge tone="success" dot>{m.type} complete</Badge>
              </div>
            ))}
          </Card>
        )}

        <Modal open={nw} onClose={() => setNw(false)} icon="truck" title="Start a Move" subtitle="Begin a guided move-in or move-out."
          footer={<React.Fragment><Button variant="secondary" onClick={() => setNw(false)}>Cancel</Button><Button variant="primary" icon="check" onClick={() => {
            const id = "MV-" + Math.floor(3010 + Math.random() * 90);
            setMoves((l) => [{ id, type: draft.type, tenant: draft.tenant || "New Tenant", avatar: "../../assets/images/avatar-1.jpg", property: draft.property, unit: draft.unit || window.WBunitsFor(draft.property, draft.type === "Move-in")[0] || "—", date: draft.date || "TBD", step: 0 }, ...l]);
            setNw(false); window.WBToast(draft.type + " started");
          }}>Start</Button></React.Fragment>}>
          <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
            <Select label="Type" value={draft.type} onChange={(e) => setDraft((d) => ({ ...d, type: e.target.value, unit: "" }))} options={["Move-in", "Move-out"]} />
            <Select label="Tenant" value={draft.tenant} onChange={(e) => setDraft((d) => ({ ...d, tenant: e.target.value }))} options={["Select tenant…", ...window.WB_TENANT_NAMES]} />
            <div style={{ display: "flex", gap: 14 }}>
              <Select label="Property" value={draft.property} onChange={(e) => setDraft((d) => ({ ...d, property: e.target.value, unit: "" }))} options={window.WB_SITES} containerStyle={{ flex: 1 }} />
              <Select label="Unit" value={draft.unit} onChange={(e) => setDraft((d) => ({ ...d, unit: e.target.value }))} options={(draft.type === "Move-in" ? window.WBunitsFor(draft.property, true) : window.WBunitsFor(draft.property, false)).length ? (draft.type === "Move-in" ? window.WBunitsFor(draft.property, true) : window.WBunitsFor(draft.property, false)) : ["No units"]} containerStyle={{ flex: 1 }} />
            </div>
            <Input label="Target date" type="date" value={draft.date} onChange={(e) => setDraft((d) => ({ ...d, date: e.target.value }))} />
          </div>
        </Modal>
      </div>
    );
  }
  window.MoveScreen = MoveScreen;
})();
