const { StatusBadge, Icon, STATUS } = window.TersusDesignSystem_b3db99;

const { datumDe, istFaellig } = window.TersusTermine;

const STATUS_REIHENFOLGE = { verhandlung: 0, angeschrieben: 1, neu: 2, bestandskunde: 3, absage: 4 };
/* Fuehrende Anfuehrungszeichen und Ziffern ignorieren: "Luisenstift" steht unter L. */
const nameSchluessel = (n) => n.replace(/^[^\p{L}]+/u, "");
const nachName = (a, b) => nameSchluessel(a.name).localeCompare(nameSchluessel(b.name), "de");

/* Standard-Sortierung zum Abtelefonieren: faellige Wiedervorlagen zuerst (aelteste oben),
   dann kuenftige Wiedervorlagen, dann alles ohne Termin nach Status und Name. */
const SORTIERUNGEN = {
  wiedervorlage: (a, b) => {
    const wa = a.wiedervorlage || "9999", wb = b.wiedervorlage || "9999";
    return wa.localeCompare(wb) || STATUS_REIHENFOLGE[a.status] - STATUS_REIHENFOLGE[b.status] || nachName(a, b);
  },
  name: nachName,
  ort: (a, b) => (a.ort || "").localeCompare(b.ort || "", "de") || nachName(a, b),
  status: (a, b) => STATUS_REIHENFOLGE[a.status] - STATUS_REIHENFOLGE[b.status] || nachName(a, b),
};

const zelle = { padding: "9px 12px", borderBottom: "1px solid var(--divider)", verticalAlign: "top" };
const kopf = { ...zelle, position: "sticky", top: 0, background: "var(--surface-card)", zIndex: 1, textAlign: "left",
  font: "var(--text-label)", letterSpacing: "var(--ls-label)", textTransform: "uppercase", color: "var(--text-muted)", whiteSpace: "nowrap" };

function Spaltenkopf({ id, children, sortierung, setSortierung, style }) {
  const aktiv = sortierung === id;
  return (
    <th style={{ ...kopf, ...style }} aria-sort={aktiv ? "ascending" : "none"}>
      <button type="button" onClick={() => setSortierung(id)} style={{ color: aktiv ? "var(--text-primary)" : undefined }}>
        {children}{aktiv ? <Icon name="arrow-down" size={11} /> : null}
      </button>
    </th>
  );
}

function Anrufliste({ objekte, selectedId, onSelect }) {
  const [sortierung, setSortierung] = React.useState("wiedervorlage");
  const zeilen = React.useMemo(() => [...objekte].sort(SORTIERUNGEN[sortierung]), [objekte, sortierung]);
  const selRef = React.useRef(null);

  React.useEffect(() => {
    if (selRef.current) selRef.current.scrollIntoView({ block: "nearest" });
  }, [selectedId]);

  if (!zeilen.length) {
    return (
      <div style={{ flex: 1, display: "flex", alignItems: "center", justifyContent: "center", color: "var(--text-muted)", fontSize: "var(--fs-sm)" }}>
        Keine Karteikarten fuer diese Filter.
      </div>
    );
  }

  return (
    <div style={{ flex: 1, minWidth: 0, overflow: "auto", background: "var(--surface-card)" }}>
      <table className="anrufliste" style={{ width: "100%", borderCollapse: "separate", borderSpacing: 0, fontSize: "var(--fs-sm)" }}>
        <thead>
          <tr>
            <Spaltenkopf id="name" sortierung={sortierung} setSortierung={setSortierung}>Einrichtung</Spaltenkopf>
            <Spaltenkopf id="ort" sortierung={sortierung} setSortierung={setSortierung}>Ort</Spaltenkopf>
            <th style={kopf}>Telefon</th>
            <Spaltenkopf id="status" sortierung={sortierung} setSortierung={setSortierung}>Status</Spaltenkopf>
            <Spaltenkopf id="wiedervorlage" sortierung={sortierung} setSortierung={setSortierung}>Naechster Anruf</Spaltenkopf>
          </tr>
        </thead>
        <tbody>
          {zeilen.map(o => {
            const sel = o.id === selectedId;
            const faellig = istFaellig(o);
            return (
              <tr key={o.id} ref={sel ? selRef : null} aria-selected={sel} onClick={() => onSelect(o.id)}>
                <td style={{ ...zelle, minWidth: 260 }}>
                  <div style={{ fontWeight: "var(--fw-semibold)" }}>{o.name}</div>
                  <div style={{ fontSize: "var(--fs-xs)", color: "var(--text-muted)", marginTop: 2 }}>{o.kategorie}{o.traeger ? " · " + o.traeger : ""}</div>
                </td>
                <td style={{ ...zelle, whiteSpace: "nowrap" }}>
                  {o.ort}
                  <div style={{ fontSize: "var(--fs-xs)", color: "var(--text-muted)", marginTop: 2, fontVariantNumeric: "tabular-nums" }}>{o.plz}</div>
                </td>
                <td style={{ ...zelle, whiteSpace: "nowrap", fontVariantNumeric: "tabular-nums" }}>
                  {o.telefon
                    ? <a href={"tel:" + o.telefon.replace(/[^\d+]/g, "")} onClick={e => e.stopPropagation()}>{o.telefon}</a>
                    : <span style={{ color: "var(--text-muted)" }}>fehlt</span>}
                </td>
                <td style={{ ...zelle, whiteSpace: "nowrap" }}><StatusBadge status={o.status} size="sm" label={STATUS[o.status].label.split(" / ")[0]} /></td>
                <td style={{ ...zelle, whiteSpace: "nowrap", fontVariantNumeric: "tabular-nums" }}>
                  {o.wiedervorlage ? (
                    <span style={{ display: "inline-flex", alignItems: "center", gap: 6, color: faellig ? "var(--status-declined)" : undefined, fontWeight: faellig ? "var(--fw-semibold)" : undefined }}>
                      {faellig ? <Icon name="alarm-clock" size={13} /> : null}
                      {datumDe(o.wiedervorlage)}{faellig ? " · heute anrufen" : ""}
                    </span>
                  ) : <span style={{ color: "var(--text-muted)" }}>–</span>}
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
}

Object.assign(window, { Anrufliste });
