// MDM SORP — Dedup review & merge (6.7).

const { useState, useEffect, useMemo, useRef, useCallback, createContext, useContext } = React;

function DedupScreen({ navigate }) {
  const { t, lang } = useI18n();
  const toast = useToast();
  const cands = [
    { id: "p_2002", short: "Schaeffler Middle East FZE", full: "Schaeffler Middle East FZE",
      trn: "100229876500003", country: "AE", city: "Dubai (JAFZA)",
      phone: "+971 4 805-1888", email: "sales.me@schaeffler.com",
      created: "2024-08-14", source: "amo", conf: 0.93,
      deals: 4, refs: 12, docs: 7 },
    { id: "p_2003", short: "Schaffler M.E. Trading LLC", full: "Schaffler M.E. Trading LLC",
      trn: "100229876500003", country: "AE", city: "Dubai",
      phone: "+971-4-805 1888", email: "trade@schaffler-me.com",
      created: "2024-12-02", source: "drive", conf: 0.41,
      deals: 1, refs: 3, docs: 2 },
  ];
  const [survivor, setSurvivor] = useState("p_2002");
  const [picks, setPicks] = useState({
    short: "p_2002", full: "p_2002", trn: "p_2002", country: "p_2002",
    city: "p_2002", phone: "p_2002", email: "both",
  });

  const fields = [
    { key: "short", label: lang === "ru" ? "Краткое имя" : "Short name" },
    { key: "full", label: lang === "ru" ? "Полное наименование" : "Full legal name" },
    { key: "trn", label: "TRN", mono: true, same: true },
    { key: "country", label: t("party_country") },
    { key: "city", label: t("party_address") },
    { key: "phone", label: t("party_phone"), mono: true },
    { key: "email", label: t("party_email"), special: ["both"] },
  ];

  return (
    <div style={{ flex: 1, overflow: "auto" }}>
      <div className="grid-toolbar">
        <h2>{t("dedup_title")}</h2>
        <span className="count tabular">4 пары · 2 высокий приоритет</span>
        <div style={{ flex: 1 }}/>
        <button className="btn ghost sm"><Icon name="filter" size={12}/> Тип совпадения</button>
        <button className="btn ghost sm">Только high-conf</button>
      </div>

      {/* Candidate pair indicator */}
      <div style={{ padding: "12px 24px", background: "var(--bg-surface)", borderBottom: "1px solid var(--border-subtle)" }}>
        <div className="row" style={{ fontSize: 13 }}>
          <Chip tone="warning"><Icon name="merge" size={11}/> Пара #1 из 4</Chip>
          <span className="muted">·</span>
          <span><strong>Совпадение по TRN</strong> · ИИ confidence <span className="tabular">94%</span></span>
          <div style={{ flex: 1 }}/>
          <button className="btn ghost sm"><Icon name="arrow_right" size={11}/> Следующая пара</button>
        </div>
      </div>

      <div className="merge" style={{ "--cands": cands.length }}>
        {/* Header row */}
        <div></div>
        {cands.map(c => (
          <div key={c.id} className={"cand " + (survivor === c.id ? "survivor" : "")}>
            <div className="row" style={{ marginBottom: 8 }}>
              <Avatar name={c.short} size={32}/>
              <div style={{ marginLeft: 10, flex: 1 }}>
                <div style={{ fontWeight: 600, fontSize: 13 }}>{c.short}</div>
                <div className="muted mono" style={{ fontSize: 10 }}>{c.id} · создано {c.created}</div>
              </div>
              <FieldBadge src={c.source} conf={c.conf}/>
            </div>
            <button className={"btn sm " + (survivor === c.id ? "primary" : "")}
                    onClick={() => setSurvivor(c.id)}
                    style={{ width: "100%" }}>
              {survivor === c.id
                ? <><Icon name="check" size={12}/> {t("dedup_survivor")}</>
                : <>{t("dedup_make_survivor")}</>}
            </button>
            <div className="muted" style={{ fontSize: 11, marginTop: 8, lineHeight: 1.5 }}>
              <div className="row" style={{ justifyContent: "space-between" }}><span>Сделок</span><span className="tabular">{c.deals}</span></div>
              <div className="row" style={{ justifyContent: "space-between" }}><span>Связей</span><span className="tabular">{c.refs}</span></div>
              <div className="row" style={{ justifyContent: "space-between" }}><span>Документов</span><span className="tabular">{c.docs}</span></div>
            </div>
          </div>
        ))}
        <div className="cand" style={{ background: "var(--bg-page)" }}>
          <div className="t-eyebrow" style={{ marginBottom: 8 }}>Превью результата</div>
          <div style={{ fontSize: 12, lineHeight: 1.55 }}>
            <div>Одна запись <strong>{cands.find(c => c.id === survivor)?.short}</strong>.</div>
            <div className="muted" style={{ marginTop: 4 }}>Перенесётся: 5 сделок · 15 связей · 9 документов.</div>
            <div className="muted" style={{ marginTop: 4 }}>Дубль помечается tombstone (откат 30 дней).</div>
          </div>
          <div className="divider"/>
          <button className="btn primary" style={{ width: "100%" }} onClick={() => toast("Записи слиты. p_2003 → p_2002", { onUndo: () => {} })}>
            <Icon name="merge" size={13}/> {t("dedup_merge")}
          </button>
          <button className="btn" style={{ width: "100%", marginTop: 6 }} onClick={() => toast("Помечено как не дубли")}>
            <Icon name="x" size={13}/> {t("dedup_not_dup")}
          </button>
          <button className="btn ghost" style={{ width: "100%", marginTop: 6 }}>{t("defer")}</button>
        </div>

        {/* Field-by-field rows */}
        {fields.map(f => {
          const v0 = cands[0][f.key] || "—";
          const v1 = cands[1][f.key] || "—";
          const same = v0 === v1;
          return (
            <div className="merge-row" key={f.key}>
              <div className="lbl">
                {f.label}
                {!same && <Chip tone="warning" style={{ marginLeft: 6 }}>{t("dedup_conflict")}</Chip>}
                {same && <Icon name="check" size={11} className="muted" style={{ marginLeft: 6 }}/>}
              </div>
              {cands.map(c => (
                <div key={c.id}
                     className={"v " + (picks[f.key] === c.id ? "picked" : "") + (!same ? " conflict" : "")}
                     onClick={() => setPicks(p => ({ ...p, [f.key]: c.id }))}>
                  <input type="radio" checked={picks[f.key] === c.id} readOnly/>
                  <span className={f.mono ? "mono" : ""}>{c[f.key] || "—"}</span>
                </div>
              ))}
              <div className="v" style={{ background: "var(--bg-page)", cursor: "default" }}>
                {f.special?.includes("both") && picks[f.key] === "both"
                  ? <span className="muted">обе</span>
                  : <strong className={f.mono ? "mono" : ""}>{cands.find(c => c.id === picks[f.key])?.[f.key] || cands.find(c => c.id === survivor)?.[f.key] || "—"}</strong>
                }
                {f.key === "email" && (
                  <button className="btn ghost sm" style={{ marginLeft: "auto" }} onClick={() => setPicks(p => ({ ...p, email: p.email === "both" ? survivor : "both" }))}>
                    {picks.email === "both" ? "одно" : "оставить оба"}
                  </button>
                )}
              </div>
            </div>
          );
        })}
      </div>

      <div style={{ padding: "0 24px 24px" }}>
        <div className="card">
          <div className="card-head"><Icon name="info" size={14}/> <h3>Что произойдёт после слияния</h3></div>
          <div className="card-body" style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 16, fontSize: 12 }}>
            <div>
              <div className="t-eyebrow" style={{ marginBottom: 4 }}>Сделки</div>
              <div>Все ссылки <span className="mono">deal.supplier</span> и <span className="mono">deal_item.supplier</span> переадресуются на p_2002.</div>
            </div>
            <div>
              <div className="t-eyebrow" style={{ marginBottom: 4 }}>Документы</div>
              <div>Drive-папка <span className="mono">/Suppliers/Schaffler</span> остаётся, индекс перемаппится.</div>
            </div>
            <div>
              <div className="t-eyebrow" style={{ marginBottom: 4 }}>Tombstone</div>
              <div>p_2003 не удаляется. Запись остаётся в БД с флагом <span className="mono">merged_into=p_2002</span>.</div>
            </div>
            <div>
              <div className="t-eyebrow" style={{ marginBottom: 4 }}>Откат</div>
              <div>30 дней через журнал · «Восстановить запись». Все связи откатываются обратно.</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

window.DedupScreen = DedupScreen;
