// screens/maintenance.jsx — Maintenance kanban + filters
function Maintenance({ ctx }) {
  const { data, setTicket, nav } = ctx;
  const tt = ctx.tt;
  const [aptFilter, setAptFilter] = React.useState("all");
  const [priFilter, setPriFilter] = React.useState("all");

  const filtered = data.tickets.filter((t) => {
    if (aptFilter !== "all" && t.aptId !== aptFilter) return false;
    if (priFilter !== "all" && t.priority !== priFilter) return false;
    return true;
  });

  const cols = [
    { key: "open", title: tt("mt.col.open"), subtitle: tt("mt.col.open.sub"), items: filtered.filter((t) => t.status === "open") },
    { key: "in-progress", title: tt("mt.col.inProg"), subtitle: tt("mt.col.inProg.sub"), items: filtered.filter((t) => t.status === "in-progress") },
    { key: "resolved", title: tt("mt.col.resolved"), subtitle: tt("mt.col.resolved.sub"), items: filtered.filter((t) => t.status === "resolved") },
  ];

  return (
    <>
      <div className="main-top">
        <div className="title">
          <h1 className="display">{tt("mt.title")}</h1>
          <div className="sub">{tt("mt.sub", { open: filtered.filter((t) => t.status !== "resolved").length, high: filtered.filter((t) => t.priority === "high" && t.status !== "resolved").length })}</div>
        </div>
        <div className="actions">
          <HeaderTools ctx={ctx} />
          <button className="btn primary"><Icon name="plus" size={14} /> {tt("btn.newTicket")}</button>
        </div>
      </div>

      <div className="main-scroll">
        <div className="flex center gap-2" style={{ marginBottom: 20, flexWrap: "wrap" }}>
          <FilterPills value={aptFilter} onChange={setAptFilter}
                       options={[{ value: "all", label: tt("fin.allFlats") }, ...data.apartments.map((a) => ({ value: a.id, label: a.name }))]} />
          <div style={{ width: 1, height: 22, background: "var(--ef-line)" }} />
          <FilterPills value={priFilter} onChange={setPriFilter}
                       options={[{ value: "all", label: tt("mt.anyPriority") }, { value: "high", label: tt("mt.high") }, { value: "med", label: tt("mt.med") }, { value: "low", label: tt("mt.low") }]} />
        </div>

        <div className="kanban">
          {cols.map((col) => (
            <div key={col.key} className="kanban-col">
              <h4>
                <span>{col.title}</span>
                <Pill>{col.items.length}</Pill>
                <span className="muted txt-xs" style={{ marginLeft: "auto", letterSpacing: 0, textTransform: "none", fontWeight: 400 }}>{col.subtitle}</span>
              </h4>
              {col.items.map((t) => {
                const apt = data.byId.apt(t.aptId);
                const tn = t.tenantId && data.byId.tenant(t.tenantId);
                return (
                  <div className="kanban-card" key={t.id}>
                    <div className="flex between">
                      <Pill tone={t.priority === "high" ? "danger" : t.priority === "med" ? "warn" : "default"}>
                        <span className="dot" /> {t.priority === "high" ? tt("mt.high") : t.priority === "med" ? tt("mt.med") : tt("mt.low")}
                      </Pill>
                      <span className="muted txt-xs">{relTime(t.openedAt)}</span>
                    </div>
                    <h5>{t.title}</h5>
                    {t.note && <div className="muted txt-xs" style={{ lineHeight: 1.4 }}>{t.note}</div>}
                    <div className="meta flex center gap-2" style={{ paddingTop: 6, borderTop: "1px solid var(--ef-line)" }}>
                      <Icon name="building" size={12} className="muted" />
                      <Link onClick={() => nav("apartment", apt.id)} className="muted-2 txt-xs">{apt.name}{t.room ? ` · ${tt("ad.room")} ${t.room}` : ""}</Link>
                    </div>
                    {tn && (
                      <div className="flex center gap-2" style={{ fontSize: 12 }}>
                        <div className="avatar sm">{initials(tn.name)}</div>
                        <Link onClick={() => nav("tenant", tn.id)}>{tn.name}</Link>
                      </div>
                    )}
                    <div className="flex gap-2" style={{ paddingTop: 6, borderTop: "1px solid var(--ef-line)", alignItems: "center" }}>
                      {col.key === "open" && (
                        <button className="btn sm" onClick={() => setTicket(t.id, "in-progress")}>
                          {tt("btn.start") || "Empezar"}
                        </button>
                      )}
                      {col.key === "in-progress" && (
                        <button className="btn sm" onClick={() => setTicket(t.id, "resolved")}>
                          <Icon name="check" size={12} /> {tt("btn.resolve") || "Resolver"}
                        </button>
                      )}
                      {col.key === "resolved" && (
                        <button className="btn sm ghost" onClick={() => setTicket(t.id, "open")}>
                          {tt("mt.reopen") || "Reabrir"}
                        </button>
                      )}
                      <span style={{ marginLeft: "auto" }}>
                        <RowMenu items={[
                          ...(col.key !== "resolved" ? [
                            { icon: "check", label: tt("btn.resolve") || "Marcar como resuelto", onClick: () => setTicket(t.id, "resolved") },
                          ] : [
                            { icon: "wrench", label: tt("mt.reopen") || "Reabrir incidencia", onClick: () => setTicket(t.id, "open") },
                          ]),
                          { icon: "users", label: tt("mt.assign") || "Reasignar", onClick: () => ctx.showToast && ctx.showToast("Reasignar (mock)") },
                          { icon: "settings", label: tt("mt.editPriority") || "Editar prioridad", onClick: () => ctx.showToast && ctx.showToast("Editar prioridad (mock)") },
                          { icon: "eye", label: tt("mt.viewProperty") || "Ver piso", onClick: () => { const apt = data.byId.apt(t.aptId); if (apt) nav("apartment", apt.id); } },
                          { divider: true },
                          { icon: "x", label: tt("mt.delete") || "Eliminar incidencia", danger: true, onClick: () => ctx.confirm && ctx.confirm({
                              title: (tt("mt.delete") || "Eliminar incidencia"),
                              body: tt("mt.deleteConfirm") || "Esta incidencia desaparecerá del tablero. No se puede deshacer.",
                              confirmLabel: tt("mt.delete") || "Eliminar",
                              danger: true,
                              onConfirm: () => ctx.showToast && ctx.showToast(tt("toast.ticketDeleted") || "Incidencia eliminada"),
                            }) },
                        ]} />
                      </span>
                    </div>
                  </div>
                );
              })}
              {col.items.length === 0 && <Empty icon="check" title={tt("mt.empty")} body={tt("mt.emptyBody")} />}
            </div>
          ))}
        </div>
      </div>
    </>
  );
}

window.Maintenance = Maintenance;
