// MDM SORP — Parties grid + Party card.

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

function PartiesScreen({ navigate }) {
  const { t, lang } = useI18n();

  const rows = useMemo(() => window.DATA.parties.map(p => ({
    ...p,
    name: p.short,
    full: p.full,
    roles_arr: p.roles || [],
    taxId: p.inn || p.trn,
    source_badge: p.source,
  })), []);

  const roleOpts = [
    { value: "customer",  label: "Заказчик",   color: "red" },
    { value: "supplier",  label: "Поставщик",  color: "blue" },
    { value: "end_user",  label: "Конечник",   color: "orange" },
    { value: "vehicle",   label: "Заход",      color: "ink" },
    { value: "contact",   label: "Контакт",    color: "gray" },
    { value: "beneficiary", label: "Бенефициар", color: "purple" },
  ];

  const countryOpts = [
    { value: "RU", label: "Россия", color: "red" },
    { value: "AE", label: "ОАЭ", color: "green" },
    { value: "CN", label: "Китай", color: "yellow" },
    { value: "TR", label: "Турция", color: "orange" },
    { value: "DE", label: "Германия", color: "gray" },
  ];

  const sanctionsOpts = [
    { value: "clean", label: "Чисто", color: "green" },
    { value: "review", label: "Review", color: "yellow" },
    { value: "match", label: "Совпадение", color: "orange" },
    { value: "flag", label: "Flag", color: "red" },
  ];

  const sourceOpts = [
    { value: "amo", label: "AmoCRM", color: "blue" },
    { value: "asana", label: "Asana", color: "red" },
    { value: "drive", label: "Drive", color: "blue" },
    { value: "ai", label: "ИИ", color: "red" },
    { value: "dadata", label: "Dadata", color: "purple" },
    { value: "manual", label: "Ручной", color: "gray" },
  ];

  const columns = [
    { id: "id", label: "ID", type: "text", width: 90, mono: true },
    { id: "name", label: "Краткое имя", type: "primary", width: 240 },
    { id: "full", label: "Полное наименование", type: "text", width: 280 },
    { id: "roles_arr", label: "Роли", type: "multi_select", width: 200, options: roleOpts },
    { id: "taxId", label: "ИНН / TRN", type: "text", width: 160, mono: true },
    { id: "country", label: "Страна", type: "select", width: 150, options: countryOpts },
    { id: "city", label: "Город", type: "text", width: 160 },
    { id: "phone", label: "Телефон", type: "text", width: 170, mono: true },
    { id: "email", label: "E-mail", type: "text", width: 220 },
    { id: "screening", label: "Скрининг", type: "sanctions", width: 130, options: sanctionsOpts },
    { id: "source_badge", label: "Источник", type: "select", width: 130, options: sourceOpts },
    { id: "conf", label: "Conf.", type: "percent", width: 80, accessor: r => Math.round((r.conf || 0) * 100) },
  ];

  const views = [
    { name: "Все party", kind: "grid", count: rows.length },
    { name: "Поставщики", kind: "grid",
      filter: [{ field: "roles_arr", op: "contains", value: "supplier" }] },
    { name: "По роли", kind: "kanban", stackBy: "country" },
    { name: "Карты поставщиков", kind: "gallery",
      filter: [{ field: "roles_arr", op: "contains", value: "supplier" }] },
    { name: "Низкий confidence", kind: "grid",
      filter: [{ field: "conf", op: "lt", value: 50 }],
      colorBy: "screening" },
    { name: "Группа по стране", kind: "grid", groupBy: "country",
      sort: [{ field: "name", dir: "asc" }] },
  ];

  return (
    <AirtableGrid
      entity="parties"
      views={views}
      columns={columns}
      rows={rows}
      primaryField="name"
      navigate={navigate}
      onRowOpen={(r) => navigate("party", { id: r.id })}
    />
  );
}

function PartyDrawer({ p, onOpen }) {
  const { t, lang } = useI18n();
  if (!p) return null;
  return (
    <>
      <div className="drawer-head">
        <div style={{ flex: 1 }}>
          <div className="title">{p.short}</div>
          <div className="sub">{p.full}</div>
          <div className="row" style={{ marginTop: 8, gap: 6, flexWrap: "wrap" }}>
            {(p.roles || []).map(r => <RoleChip key={r} role={r}/>)}
            <SanctionsChip status={p.screening}/>
            <Chip tone="outline"><Flag code={p.country}/> {p.city}</Chip>
          </div>
        </div>
        <button className="btn ghost sm" onClick={onOpen}><Icon name="arrow_up_right" size={13}/></button>
      </div>
      <div className="drawer-body" style={{ padding: 16 }}>
        <PartyFields p={p}/>
        <h4 style={{ marginTop: 20 }}>{lang === "ru" ? "Связанные сделки" : "Related deals"}</h4>
        {window.DATA.deals.filter(d => d.customer === p.id || d.end_user === p.id || d.vehicle === p.id).slice(0, 3).map(d => (
          <div key={d.id} className="card" style={{ padding: 10, marginBottom: 6, fontSize: 12 }}>
            <div className="row" style={{ gap: 8 }}>
              <span className="mono" style={{ color: "var(--sorp-red)", fontWeight: 700 }}>{d.id}</span>
              <span style={{ flex: 1, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{d.title}</span>
              <Chip tone="info">{d.stage}</Chip>
              <span className="tabular muted">{fmtMoney(d.value_usd, "USD")}</span>
            </div>
          </div>
        ))}
      </div>
      <div className="drawer-foot">
        <button className="btn ghost"><Icon name="sparkle" size={13}/> {t("enrich")}</button>
        <button className="btn ghost"><Icon name="merge" size={13}/> {t("findDups")}</button>
        <button className="btn primary" onClick={onOpen}>Открыть карточку <Icon name="arrow_right" size={13}/></button>
      </div>
    </>
  );
}

function PartyFields({ p }) {
  const { t } = useI18n();
  const rows = [
    { lbl: t("party_full_name"), v: p.full, src: p.source, conf: p.conf, raw: p.raw_note },
    { lbl: t("party_short_name"), v: p.short, src: p.source, conf: p.conf },
    { lbl: p.inn ? t("party_inn") : t("party_trn"), v: p.inn || p.trn || "—", src: p.inn ? "amo" : "manual", conf: 1.0, mono: true },
    { lbl: t("party_country"), v: p.country, src: p.source, conf: 1.0 },
    { lbl: t("party_phone"), v: p.phone, src: p.source, conf: p.conf, mono: true },
    { lbl: t("party_email"), v: p.email, src: p.source, conf: p.conf },
    { lbl: t("party_address"), v: p.city, src: "dadata", conf: 0.88 },
  ];
  return (
    <div>
      {rows.map((r, i) => (
        <div key={i} className="frow">
          <div className="lbl">{r.lbl}</div>
          <div className="val">
            <span className={"text " + (r.mono ? "mono" : "") + (!r.v ? " empty" : "")} contentEditable suppressContentEditableWarning>
              {r.v || "—"}
            </span>
            <FieldBadge src={r.src} conf={r.conf} raw={r.raw}/>
          </div>
          <div className="actions">
            <button className="icon-mini" title="Изменить"><Icon name="pencil" size={11}/></button>
            <button className="icon-mini" title="Скопировать"><Icon name="copy" size={11}/></button>
            <button className="icon-mini" title="История"><Icon name="history" size={11}/></button>
          </div>
        </div>
      ))}
    </div>
  );
}

/* =====================  PARTY CARD (full)  ===================== */
function PartyCardScreen({ navigate, params }) {
  const { t, lang } = useI18n();
  const id = params?.id || "p_2002";
  const p = findParty(id) || window.DATA.parties[0];
  const [tab, setTab] = useState("overview");

  return (
    <div style={{ flex: 1, overflow: "auto" }}>
      <div style={{ padding: "20px 24px 0", background: "var(--bg-surface)", borderBottom: "1px solid var(--border-subtle)" }}>
        <div className="row" style={{ fontSize: 11, color: "var(--fg-3)" }}>
          <button className="btn ghost sm" onClick={() => navigate("parties")}><Icon name="arrow_right" size={11} className=""/> {lang === "ru" ? "к списку" : "back to list"}</button>
          <span>·</span>
          <span className="mono">{p.id}</span>
          {p.possibleDupOf && (
            <>
              <span>·</span>
              <Chip tone="warning"><Icon name="merge" size={11}/> возможный дубль · <a onClick={() => navigate("dedup")} style={{ color: "inherit", textDecoration: "underline", cursor: "pointer" }}>открыть ревью</a></Chip>
            </>
          )}
        </div>
        <div className="row" style={{ alignItems: "flex-start", marginTop: 10 }}>
          <Avatar name={p.short} size={56}/>
          <div style={{ flex: 1, marginLeft: 14 }}>
            <h1 style={{ margin: 0, fontSize: 24, fontWeight: 600, fontFamily: "var(--font-display)" }}>{p.short}</h1>
            <div className="muted" style={{ fontSize: 13, marginTop: 4 }}>{p.full}</div>
            <div className="row" style={{ marginTop: 10, gap: 6, flexWrap: "wrap" }}>
              {(p.roles || []).map(r => <RoleChip key={r} role={r}/>)}
              <SanctionsChip status={p.screening}/>
              <Chip tone="outline"><Flag code={p.country}/> {p.city}</Chip>
              {p.inn && <Chip tone="outline">ИНН <span className="mono">{p.inn}</span></Chip>}
              {p.trn && <Chip tone="outline">TRN <span className="mono">{p.trn}</span></Chip>}
            </div>
          </div>
          <div className="row" style={{ gap: 6 }}>
            <button className="btn"><Icon name="sparkle" size={13}/> {t("enrich")}</button>
            <button className="btn"><Icon name="merge" size={13}/> {t("findDups")}</button>
            <button className="btn"><Icon name="shield" size={13}/> {t("sanctionsCheck")}</button>
            <button className="btn primary"><Icon name="file" size={13}/> {t("generateDossier")}</button>
          </div>
        </div>

        <div className="tabs" style={{ padding: 0, marginTop: 14, borderBottom: 0 }}>
          {[
            { id: "overview", label: t("overview"), n: null },
            { id: "deals", label: t("deals"), n: window.DATA.deals.filter(d => d.customer === p.id || d.end_user === p.id || d.vehicle === p.id).length },
            { id: "contacts", label: lang === "ru" ? "Контакты" : "Contacts", n: 4 },
            { id: "docs", label: t("docs"), n: 12 },
            { id: "capability", label: lang === "ru" ? "Возможности" : "Capability", n: p.roles?.includes("supplier") ? 6 : null },
            { id: "history", label: t("history"), n: 28 },
          ].filter(x => x.n !== null || x.id === "overview").map(x =>
            <button key={x.id} className={"tab " + (tab === x.id ? "active" : "")} onClick={() => setTab(x.id)}>
              {x.label} {x.n != null && <span className="count tabular">{x.n}</span>}
            </button>
          )}
        </div>
      </div>

      <div style={{ padding: 24 }}>
        {tab === "overview" && <PartyOverviewTab p={p}/>}
        {tab === "deals" && <PartyDealsTab p={p} navigate={navigate}/>}
        {tab === "contacts" && <PartyContactsTab/>}
        {tab === "docs" && <PartyDocsTab/>}
        {tab === "capability" && <PartyCapabilityTab/>}
        {tab === "history" && <PartyHistoryTab/>}
      </div>
    </div>
  );
}

function PartyOverviewTab({ p }) {
  const { t, lang } = useI18n();
  return (
    <div style={{ display: "grid", gridTemplateColumns: "2fr 1fr", gap: 24, maxWidth: 1200 }}>
      <div className="card">
        <div className="card-head"><Icon name="parties" size={14}/> <h3>{lang === "ru" ? "Основные поля" : "Core fields"}</h3>
          <span style={{ flex: 1 }}/>
          <Chip tone="success">fill-rate 87%</Chip>
        </div>
        <div className="card-body" style={{ padding: "0 16px" }}>
          <PartyFields p={p}/>
        </div>
      </div>

      <div className="col" style={{ gap: 16 }}>
        <div className="card">
          <div className="card-head"><Icon name="link" size={14}/> <h3>{lang === "ru" ? "Связи в системах" : "System links"}</h3></div>
          <div className="card-body">
            <SystemLink color="#2E91FE" label="AmoCRM" id="contact #2841" sub="контрагент · sales" status="ok"/>
            <SystemLink color="#F06A6A" label="Asana" id="upcoming" sub="нет связи · автосшивка ждёт SORP-ключ" status="pending"/>
            <SystemLink color="#1A73E8" label="Drive" id="/Suppliers/Schaeffler" sub="папка · 12 документов" status="ok"/>
          </div>
        </div>
        <div className="card">
          <div className="card-head"><Icon name="shield" size={14}/> <h3>{lang === "ru" ? "Скрининг" : "Screening"}</h3>
            <span style={{ flex: 1 }}/>
            <span className="muted" style={{ fontSize: 11 }}>OpenSanctions · 2026-05-27 03:21</span>
          </div>
          <div className="card-body">
            <div className="row" style={{ justifyContent: "space-between", padding: "6px 0", fontSize: 12 }}>
              <span>OFAC SDN</span><Chip tone="success">Clean</Chip>
            </div>
            <div className="row" style={{ justifyContent: "space-between", padding: "6px 0", fontSize: 12 }}>
              <span>EU CFSP</span><Chip tone="success">Clean</Chip>
            </div>
            <div className="row" style={{ justifyContent: "space-between", padding: "6px 0", fontSize: 12 }}>
              <span>UK HM Treasury</span><Chip tone="success">Clean</Chip>
            </div>
            <div className="row" style={{ justifyContent: "space-between", padding: "6px 0", fontSize: 12 }}>
              <span>Dual-use HS 8482</span><Chip tone="warning">Advisory</Chip>
            </div>
          </div>
        </div>
        <div className="card">
          <div className="card-head"><Icon name="info" size={14}/> <h3>{lang === "ru" ? "Метаданные" : "Metadata"}</h3></div>
          <div className="card-body" style={{ fontSize: 12 }}>
            <div className="row" style={{ justifyContent: "space-between", padding: "4px 0" }}><span className="muted">Создано</span><span>2024-08-14</span></div>
            <div className="row" style={{ justifyContent: "space-between", padding: "4px 0" }}><span className="muted">Обновлено</span><span>2026-05-26 14:08</span></div>
            <div className="row" style={{ justifyContent: "space-between", padding: "4px 0" }}><span className="muted">Создал</span><span>Service · импорт Amo</span></div>
            <div className="row" style={{ justifyContent: "space-between", padding: "4px 0" }}><span className="muted">Доступ</span><span>RBAC: открытое</span></div>
          </div>
        </div>
      </div>
    </div>
  );
}

function PartyDealsTab({ p, navigate }) {
  const deals = window.DATA.deals.filter(d => d.customer === p.id || d.end_user === p.id || d.vehicle === p.id);
  if (!deals.length) return <div className="muted">Связанных сделок нет.</div>;
  return (
    <div className="card">
      <table className="dg dense">
        <thead>
          <tr><th>ID</th><th>Сделка</th><th>Роль party</th><th>Этап</th><th className="num">Сумма</th><th>Дедлайн</th></tr>
        </thead>
        <tbody>
          {deals.map(d => (
            <tr key={d.id} onClick={() => navigate("deal", { id: d.id })}>
              <td><a style={{ color: "var(--sorp-red)", fontWeight: 600 }}>{d.id}</a></td>
              <td>{d.title}</td>
              <td>{d.customer === p.id ? <RoleChip role="customer"/> : d.end_user === p.id ? <RoleChip role="end_user"/> : <RoleChip role="vehicle"/>}</td>
              <td><Chip tone="info">{d.stage}</Chip></td>
              <td className="num tabular">{fmtMoney(d.value_usd, "USD")}</td>
              <td className="mono">{d.deadline}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

function PartyContactsTab() {
  const contacts = [
    { name: "Mohammed Al-Fardan", role: "Sales Manager ME", phone: "+971 50 412-7788", email: "m.alfardan@schaeffler.com", src: "amo", conf: 0.96 },
    { name: "Priya Ramesh", role: "Logistics Coordinator", phone: "+971 4 805-1903", email: "p.ramesh@schaeffler.com", src: "drive", conf: 0.78, raw: "из PDF КП от 2026-04-22" },
    { name: "Sven Karlsson", role: "Global Key Account", phone: "+49 9132 82-0", email: "sven.karlsson@schaeffler.com", src: "ai", conf: 0.61 },
    { name: "—", role: "(нужен бенефициар)", phone: "", email: "", src: "manual", conf: 0.0 },
  ];
  return (
    <div className="card">
      <table className="dg dense">
        <thead><tr><th></th><th>Имя</th><th>Роль</th><th>Телефон</th><th>E-mail</th><th>Источник</th></tr></thead>
        <tbody>
          {contacts.map((c, i) => (
            <tr key={i}>
              <td><Avatar name={c.name} size={22}/></td>
              <td><strong>{c.name}</strong></td>
              <td className="muted">{c.role}</td>
              <td className="mono">{c.phone || <span className="empty-cell">—</span>}</td>
              <td>{c.email || <span className="empty-cell">—</span>}</td>
              <td>{c.conf > 0 ? <FieldBadge src={c.src} conf={c.conf} raw={c.raw}/> : <Chip tone="outline">пусто</Chip>}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

function PartyDocsTab() {
  return <div className="muted">Связанные документы из Drive (12 файлов) — см. вкладку Документы сделки.</div>;
}

function PartyCapabilityTab() {
  const caps = [
    { cat: "Подшипники качения (HS 8482.10)", confidence: 0.96, lead: "28–35 д", note: "Прямой производитель, JAFZA склад" },
    { cat: "Подшипники конические (HS 8482.20)", confidence: 0.92, lead: "35–42 д", note: "Каталог 23/24" },
    { cat: "Подшипники самовыравнивающие (HS 8482.30)", confidence: 0.85, lead: "28 д", note: "—" },
    { cat: "Уплотнения промышленные", confidence: 0.74, lead: "42 д", note: "Доп. категория, поставка под заказ" },
    { cat: "Смазочные системы", confidence: 0.61, lead: "—", note: "ИИ-предложение, не подтверждено" },
    { cat: "Гидравлические клапаны (HS 8481)", confidence: 0.20, lead: "—", note: "Не профильно, отклонить?" },
  ];
  return (
    <div className="card">
      <div className="card-head"><Icon name="grid" size={14}/> <h3>Категории поставки (capability matrix)</h3></div>
      <div className="card-body" style={{ padding: 0 }}>
        {caps.map((c, i) => (
          <div key={i} style={{ display: "flex", alignItems: "center", gap: 16, padding: "12px 16px", borderBottom: "1px solid var(--neutral-100)" }}>
            <Icon name="box" size={16} className="muted"/>
            <div style={{ flex: 1 }}>
              <div style={{ fontWeight: 600, fontSize: 13 }}>{c.cat}</div>
              <div className="muted" style={{ fontSize: 11, marginTop: 2 }}>{c.note}</div>
            </div>
            <div style={{ minWidth: 120 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
                <div style={{ width: 70, height: 4, background: "var(--neutral-200)", borderRadius: 2 }}><div style={{ height: "100%", width: (c.confidence * 100) + "%", background: c.confidence > 0.8 ? "var(--status-success)" : c.confidence > 0.5 ? "var(--status-warning)" : "var(--sorp-red)" }}/></div>
                <span className="tabular" style={{ fontSize: 11 }}>{Math.round(c.confidence * 100)}%</span>
              </div>
            </div>
            <div className="muted tabular" style={{ minWidth: 60, fontSize: 11 }}>{c.lead}</div>
            <button className="btn ghost sm">Изменить</button>
          </div>
        ))}
      </div>
    </div>
  );
}

function PartyHistoryTab() {
  return <div className="muted">История изменений party — формат как на сделке.</div>;
}

window.PartiesScreen = PartiesScreen;
window.PartyCardScreen = PartyCardScreen;
