// MDM SORP — Enrichment Queue (the hero screen).
// Keyboard-first: ↑/↓ navigate, A apply, E edit, R reject, D defer, → next.

const { useState, useEffect, useMemo, useRef, useCallback: _useCallback } = React;

function EnrichmentQueueScreen({ navigate }) {
  const { t, lang } = useI18n();
  const toast = useToast();
  const [filter, setFilter] = useState("all");
  const [queue, setQueue] = useState(window.DATA.queue);
  const [activeId, setActiveId] = useState(queue[0]?.id);
  const [processed, setProcessed] = useState(34);
  const [editingField, setEditingField] = useState(null);

  const filtered = useMemo(() => {
    if (filter === "all") return queue;
    return queue.filter(q => q.kind === filter);
  }, [filter, queue]);

  const active = filtered.find(q => q.id === activeId) || filtered[0];

  const goNext = _useCallback((removeCurrent = false) => {
    const cur = filtered.findIndex(q => q.id === activeId);
    if (removeCurrent) {
      setQueue(q => q.filter(x => x.id !== activeId));
      setProcessed(p => p + 1);
    }
    const nextIdx = removeCurrent ? cur : cur + 1;
    const next = filtered[nextIdx + (removeCurrent ? 0 : 0)] || filtered[nextIdx + 1];
    const remaining = (removeCurrent ? filtered.filter(x => x.id !== activeId) : filtered);
    setActiveId(remaining[Math.min(cur, remaining.length - 1)]?.id);
  }, [activeId, filtered]);

  const apply = () => {
    toast(`Применено: ${active?.party}`, { onUndo: () => setQueue(window.DATA.queue) });
    goNext(true);
  };
  const reject = () => {
    toast(`Отклонено: ${active?.party}`, { icon: "x", onUndo: () => setQueue(window.DATA.queue) });
    goNext(true);
  };
  const defer = () => {
    toast(`Отложено на 24ч`, { icon: "history" });
    goNext(true);
  };

  // Keyboard
  useEffect(() => {
    const h = (e) => {
      if (e.target.tagName === "INPUT" || e.target.tagName === "TEXTAREA") return;
      if (e.metaKey || e.ctrlKey) return;
      if (e.key === "a" || e.key === "A" || e.key === "ф" || e.key === "Ф") { e.preventDefault(); apply(); }
      else if (e.key === "r" || e.key === "R" || e.key === "к" || e.key === "К") { e.preventDefault(); reject(); }
      else if (e.key === "d" || e.key === "D" || e.key === "в" || e.key === "В") { e.preventDefault(); defer(); }
      else if (e.key === "e" || e.key === "E" || e.key === "у" || e.key === "У") { e.preventDefault(); setEditingField("inline"); }
      else if (e.key === "ArrowDown") { e.preventDefault(); const idx = filtered.findIndex(q => q.id === activeId); setActiveId(filtered[Math.min(filtered.length - 1, idx + 1)]?.id); }
      else if (e.key === "ArrowUp")   { e.preventDefault(); const idx = filtered.findIndex(q => q.id === activeId); setActiveId(filtered[Math.max(0, idx - 1)]?.id); }
      else if (e.key === "ArrowRight"){ e.preventDefault(); goNext(false); }
    };
    window.addEventListener("keydown", h);
    return () => window.removeEventListener("keydown", h);
  }, [activeId, filtered, apply, reject, defer, goNext]);

  const filters = [
    { id: "all", label: t("queue_filter_all"), count: queue.length },
    { id: "norm", label: t("queue_filter_norm"), count: queue.filter(q => q.kind === "norm").length },
    { id: "dedup", label: t("queue_filter_dedup"), count: queue.filter(q => q.kind === "dedup").length },
    { id: "ai", label: t("queue_filter_ai"), count: queue.filter(q => q.kind === "ai").length },
    { id: "sourcing", label: t("queue_filter_sourcing"), count: queue.filter(q => q.kind === "sourcing").length },
  ];

  return (
    <div className="queue">
      {/* ----- LEFT: list ----- */}
      <div className="queue-list">
        <div className="head">
          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <h2 style={{ margin: 0, fontSize: 14, fontWeight: 600 }}>{t("queue_title")}</h2>
            <span className="muted tabular" style={{ fontSize: 11 }}>{queue.length}</span>
          </div>
          <div style={{ display: "flex", flexWrap: "wrap", gap: 4, marginTop: 8 }}>
            {filters.map(f => (
              <button key={f.id}
                className={"filter-pill " + (filter === f.id ? "active" : "")}
                onClick={() => setFilter(f.id)}>
                {f.label} <span className="tabular">{f.count}</span>
              </button>
            ))}
          </div>
        </div>
        {filtered.map(q => (
          <div key={q.id}
               className={"qitem " + (q.id === activeId ? "active" : "")}
               onClick={() => setActiveId(q.id)}>
            <div className="top">
              <span className={"pri " + q.priority}></span>
              <span className="name">{q.party}</span>
            </div>
            <div className="meta">
              <span>{labelKind(q.kind, t)}</span>
              <span>·</span>
              <span>{q.field}</span>
              {q.deal && <><span>·</span><span className="mono">{q.deal}</span></>}
            </div>
            <div className="diff">
              <span className="mono" style={{ maxWidth: 100, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{q.raw || "—"}</span>
              <Icon name="arrow_right" size={11}/>
              <span style={{ fontWeight: 500, color: "var(--fg-1)", maxWidth: 110, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{q.suggested}</span>
            </div>
          </div>
        ))}
        {filtered.length === 0 && (
          <div style={{ padding: 32, textAlign: "center", color: "var(--fg-3)", fontSize: 13 }}>
            {t("empty_queue")}
          </div>
        )}
      </div>

      {/* ----- CENTER: diff stage ----- */}
      <div className="queue-stage">
        <div className="hero-head">
          <div>
            <div className="title">{active?.party}</div>
            <div className="meta">
              <span>{labelKind(active?.kind, t)}</span>
              {active?.deal && <><span>·</span><a className="mono" style={{ color: "var(--sorp-red)", textDecoration: "none" }} onClick={() => navigate("deal", { id: active.deal })}>{active.deal}</a></>}
              <span>·</span>
              <span>сфера: <strong style={{ color: "var(--fg-1)" }}>{active?.field}</strong></span>
            </div>
          </div>
          <div className="spacer"></div>
          <button className="btn ghost sm"><Icon name="history" size={13}/> {t("history")}</button>
          <button className="btn ghost sm" onClick={() => active?.deal && navigate("deal", { id: active.deal })}><Icon name="link" size={13}/> Карточка</button>
        </div>

        <div className="stage-body">
          <DiffCard active={active} editing={editingField === "inline"} onClose={() => setEditingField(null)} />

          {/* Linked records / inline meta */}
          <div className="card" style={{ padding: 14 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 12, fontSize: 12 }}>
              <Icon name="info" size={14} className="muted"/>
              <span>Эта запись связана с</span>
              {active?.deal && <Chip tone="outline"><Icon name="deals" size={11}/> {active.deal}</Chip>}
              <Chip tone="outline"><Icon name="parties" size={11}/> party_id: <span className="mono">{active?.party_id || "—"}</span></Chip>
              <span className="muted">Изменения уйдут в audit_log с tombstone-возможностью отката.</span>
            </div>
          </div>
        </div>

        <div className="queue-action-bar">
          <button className="qaction apply" onClick={apply} title="Apply (A)">
            <div className="lbl"><Icon name="check" size={14}/> {t("apply")}</div>
            <span className="key">A</span>
          </button>
          <button className="qaction" onClick={() => setEditingField("inline")} title="Edit (E)">
            <div className="lbl">{t("edit")}</div>
            <span className="key">E</span>
          </button>
          <button className="qaction reject" onClick={reject} title="Reject (R)">
            <div className="lbl"><Icon name="x" size={14}/> {t("reject")}</div>
            <span className="key">R</span>
          </button>
          <button className="qaction" onClick={defer} title="Defer (D)">
            <div className="lbl">{t("defer")}</div>
            <span className="key">D</span>
          </button>
          <div style={{ width: 1, height: 28, background: "var(--border-subtle)" }}/>
          <button className="btn ghost sm">
            <Icon name="link" size={13}/> Передать исполнителю
          </button>
          <div className="progress">
            <span>{t("queue_progress")}: <strong className="tabular" style={{ color: "var(--fg-1)" }}>{processed}</strong> / {processed + queue.length}</span>
            <span>{t("queue_speed")}: <strong className="tabular" style={{ color: "var(--fg-1)" }}>3.4с</strong></span>
            <div className="pbar"><i style={{ width: (processed / (processed + queue.length) * 100) + "%" }}/></div>
          </div>
        </div>
      </div>

      {/* ----- RIGHT: AI hint panel ----- */}
      <div className="queue-ai">
        <div className="ai-head">
          <span className="pulse"></span>
          <Icon name="sparkle" size={14}/>
          <span>{t("queue_ai_title")}</span>
        </div>
        {active?.ai && (
          <div className="ai-hint">
            <div className="h"><Icon name="lightbulb" size={13}/> {active.ai.title}</div>
            <div className="b">{active.ai.body}</div>
            <div className="actions">
              <button className="btn sm primary"><Icon name="check" size={12}/> {aiActionLabel(active.ai.action)}</button>
              <button className="btn sm ghost">Объяснить</button>
            </div>
          </div>
        )}

        {/* Related candidates */}
        {active?.kind === "dedup" && (
          <div className="ai-hint">
            <div className="h"><Icon name="merge" size={13}/> Кандидаты на слияние</div>
            <div className="b">
              <div style={{ display: "flex", flexDirection: "column", gap: 6, marginTop: 4 }}>
                <div className="card" style={{ padding: 8, fontSize: 12 }}>
                  <div style={{ fontWeight: 600 }}>Schaeffler Middle East FZE</div>
                  <div className="muted">TRN 100229876500003 · Dubai · с 2024-08</div>
                </div>
                <div className="card" style={{ padding: 8, fontSize: 12, background: "var(--sorp-red-wash)", borderColor: "var(--sorp-red-soft)" }}>
                  <div style={{ fontWeight: 600 }}>Schaffler M.E. Trading LLC</div>
                  <div className="muted">тот же TRN · опечатка в названии · с 2024-12</div>
                </div>
              </div>
              <button className="btn sm" style={{ marginTop: 8, width: "100%" }} onClick={() => navigate("dedup")}>
                Открыть ревью <Icon name="arrow_right" size={12}/>
              </button>
            </div>
          </div>
        )}

        {/* Quality signals */}
        <div className="ai-hint">
          <div className="h"><Icon name="shield" size={13}/> Сигналы качества</div>
          <div className="b">
            <div className="row" style={{ justifyContent: "space-between", padding: "3px 0" }}><span>Источник</span><Chip tone="outline">ИИ + Asana комментарий</Chip></div>
            <div className="row" style={{ justifyContent: "space-between", padding: "3px 0" }}><span>Совпадение типа</span><Chip tone="success">phone (E.164)</Chip></div>
            <div className="row" style={{ justifyContent: "space-between", padding: "3px 0" }}><span>Проверка регулярки</span><Chip tone="warning">Частично</Chip></div>
            <div className="row" style={{ justifyContent: "space-between", padding: "3px 0" }}><span>Контр. сумма</span><Chip tone="success">OK</Chip></div>
          </div>
        </div>

        <div className="ai-hint">
          <div className="h"><Icon name="history" size={13}/> Авторы предыдущих правок</div>
          <div className="b">
            <div className="row" style={{ gap: 6, padding: "4px 0" }}><Avatar name="Е. Соколова" size={20}/> <span>Подтвердила phone · 12 мин назад</span></div>
            <div className="row" style={{ gap: 6, padding: "4px 0" }}><Avatar name="Д. Петров" size={20}/> <span>Отклонил «вебинар» · вчера</span></div>
            <div className="row" style={{ gap: 6, padding: "4px 0" }}><Avatar name="Service" size={20} color="#3A4049"/> <span>Импорт Amo · 03:14</span></div>
          </div>
        </div>

        <div style={{ flex: 1 }}/>
        <div style={{ padding: "10px 16px", borderTop: "1px solid var(--border-subtle)", fontSize: 11, color: "var(--fg-3)", display: "flex", justifyContent: "space-between" }}>
          <span>Горячие клавиши</span>
          <span className="row" style={{ gap: 4 }}>
            <span className="kbd">A</span><span className="kbd">E</span><span className="kbd">R</span><span className="kbd">D</span><span className="kbd">↓</span>
          </span>
        </div>
      </div>
    </div>
  );
}

function DiffCard({ active, editing, onClose }) {
  if (!active) return null;
  return (
    <div className="diff-grid">
      <div className="hdr">{useI18n().t("queue_field")}</div>
      <div className="hdr">{useI18n().t("raw")}</div>
      <div className="hdr">{useI18n().t("suggested")}</div>
      {active.changes.map((c, i) => {
        const changed = !c.same;
        return (
          <React.Fragment key={i}>
            <div className="field">
              <div style={{ fontWeight: 500, color: "var(--fg-1)" }}>{c.field}</div>
              {c.note && <div style={{ fontSize: 11, color: "var(--fg-3)", marginTop: 2 }}>{c.note}</div>}
            </div>
            <div className={"raw " + (changed ? "bad" : "")}>{c.raw}</div>
            <div className={"sug " + (changed ? "changed" : "")}>
              {editing && i === 0
                ? <input defaultValue={c.sug} autoFocus style={{ width: "100%", border: "1px solid var(--sorp-red)", borderRadius: 6, padding: "4px 8px", fontSize: 13 }} onBlur={onClose} onKeyDown={(e) => e.key === "Escape" && onClose()}/>
                : <span className="v">{c.sug}</span>
              }
              {!c.same && <FieldBadge src={c.src} conf={c.conf}/>}
            </div>
          </React.Fragment>
        );
      })}
    </div>
  );
}

function labelKind(k, t) {
  return ({
    norm: t("queue_filter_norm"),
    dedup: t("queue_filter_dedup"),
    ai: t("queue_filter_ai"),
    sourcing: t("queue_filter_sourcing"),
  })[k] || k;
}

function aiActionLabel(a) {
  return ({
    apply: "Применить предложение",
    send_form: "Запросить у исполнителя",
    review: "Открыть ревью дублей",
    open_matrix: "Открыть матрицу",
  })[a] || "Применить";
}

window.EnrichmentQueueScreen = EnrichmentQueueScreen;
