// MDM SORP — Home, Deals grid, Deal card, Parties grid, Party card.

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

/* =====================  HOME  ===================== */
function HomeScreen({ navigate }) {
  const { t, lang } = useI18n();
  return (
    <div className="home">
      <div className="home-hello">
        <div>
          <h1>{lang === "ru" ? "Доброе утро, Екатерина" : "Good morning, Ekaterina"}</h1>
          <div className="muted" style={{ marginTop: 6, fontSize: 13, maxWidth: 720 }}>{t("home_sub")}</div>
        </div>
        <div className="now">
          <div>{lang === "ru" ? "Среда, 27 мая 2026" : "Wednesday, May 27, 2026"} · 14:32</div>
          <div style={{ marginTop: 4 }}>{t("last_synced")}: <strong style={{ color: "var(--fg-1)" }}>Amo 03:14 · Asana 08:02 · Drive 11:45</strong></div>
        </div>
      </div>

      <div className="dashboard-grid">
        <KPI lbl={t("home_kpi_queue")} v="13" delta="+2" deltaTone="up" sub="из них 4 высокого приоритета" />
        <KPI lbl={t("home_kpi_dups")} v="4" delta="−1" deltaTone="up" sub="кандидаты по TRN/ИНН" />
        <KPI lbl={t("home_kpi_quality")} v="84%" delta="+1.2п" deltaTone="up" sub="fill-rate по party" />
        <KPI lbl={t("home_kpi_sanctions")} v="1" delta="0" deltaTone="flat" sub="OFAC review · Siemens CN" />

        {/* Today's queues */}
        <div className="panel" style={{ gridColumn: "span 7" }}>
          <div className="panel-head">
            <h3>{t("home_queues")}</h3>
            <span className="sub">обновлено 30 сек назад</span>
          </div>
          <div className="panel-body" style={{ padding: 0 }}>
            <QueueCard navigate={navigate} kind="enrichment" count={13} hot={4} icon="queue"
              title={lang === "ru" ? "Очередь обогащения" : "Enrichment queue"}
              desc={lang === "ru" ? "ИИ-подсказки + сырое → предложенное. Жми клавиатуру." : "AI suggestions, raw → suggested. Keyboard-driven."}/>
            <QueueCard navigate={navigate} kind="dedup" count={4} hot={2} icon="merge"
              title={lang === "ru" ? "Ревью дублей" : "Duplicate review"}
              desc={lang === "ru" ? "Schaffler vs Schaeffler — совпадение по TRN" : "Schaffler vs Schaeffler — TRN match"}/>
            <QueueCard navigate={navigate} kind="import" count={2} hot={0} icon="upload"
              title={lang === "ru" ? "ИИ-импорт ждёт подтверждения" : "AI import awaiting confirmation"}
              desc={lang === "ru" ? "Equipment_RFQ_Severstal_2026-05.xlsx · 47 строк" : "Equipment_RFQ_Severstal_2026-05.xlsx · 47 rows"}/>
            <QueueCard navigate={navigate} kind="sanctions" count={1} hot={1} icon="shield"
              title={lang === "ru" ? "Санкции — требует решения" : "Sanctions — needs decision"}
              desc={lang === "ru" ? "Siemens (Shanghai) — EAR99 advisory" : "Siemens (Shanghai) — EAR99 advisory"} danger/>
          </div>
        </div>

        {/* Activity */}
        <div className="panel" style={{ gridColumn: "span 5" }}>
          <div className="panel-head">
            <h3>{t("home_activity")}</h3>
            <span className="sub">за последние 12 часов</span>
          </div>
          <div className="panel-body">
            <Activity actor="Service" action={lang === "ru" ? "Импорт из AmoCRM" : "Imported from AmoCRM"} sub="47 сделок · 12 контрагентов · 0 ошибок" time="03:14"/>
            <Activity actor="Service" action={lang === "ru" ? "Скрининг OpenSanctions" : "OpenSanctions screening"} sub="284 проверки · 1 review" time="03:21"/>
            <Activity actor="Е. Соколова" action={lang === "ru" ? "Подтвердила обогащение" : "Approved enrichment"} sub="Schaeffler Dubai · address" time="09:47"/>
            <Activity actor="Д. Петров" action={lang === "ru" ? "Слил дубли" : "Merged duplicates"} sub="p_2003 → p_2002 · tombstone сохранён" time="11:02"/>
            <Activity actor="Service" action={lang === "ru" ? "Индекс Drive обновлён" : "Drive index refreshed"} sub="1 248 документов · 3 OCR" time="11:45"/>
            <Activity actor="ИИ Claude" action={lang === "ru" ? "Распознала спецификацию" : "Parsed RFQ"} sub="Equipment_RFQ_Severstal · в очередь" time="12:08"/>
          </div>
        </div>

        {/* Recent deals */}
        <div className="panel" style={{ gridColumn: "span 12" }}>
          <div className="panel-head">
            <h3>{t("home_recent")}</h3>
            <span className="sub">кликом — карточка сделки</span>
          </div>
          <div className="panel-body" style={{ padding: 0 }}>
            <DealsCompact navigate={navigate}/>
          </div>
        </div>
      </div>
    </div>
  );
}

const KPI = ({ lbl, v, delta, deltaTone = "up", sub }) => (
  <div className="kpi">
    <div className="lbl">{lbl}</div>
    <div className="v">{v}</div>
    <div className={"delta " + deltaTone}>
      <Icon name={deltaTone === "up" ? "arrow_up_right" : "arrow_right"} size={11}/> {delta}
    </div>
    <div className="muted" style={{ fontSize: 11, marginTop: 4 }}>{sub}</div>
  </div>
);

const QueueCard = ({ navigate, kind, count, hot, title, desc, icon, danger }) => {
  const { lang } = useI18n();
  return (
    <div onClick={() => navigate(kind)} style={{
      display: "flex", alignItems: "center", gap: 14, padding: "12px 16px",
      borderBottom: "1px solid var(--neutral-100)", cursor: "pointer",
    }} onMouseEnter={(e) => e.currentTarget.style.background = "var(--bg-page)"}
      onMouseLeave={(e) => e.currentTarget.style.background = ""}>
      <div style={{ width: 36, height: 36, borderRadius: 10, background: danger ? "var(--sorp-red-wash)" : "var(--bg-surface-alt)", color: danger ? "var(--sorp-red)" : "var(--fg-2)", display: "flex", alignItems: "center", justifyContent: "center" }}>
        <Icon name={icon} size={18}/>
      </div>
      <div style={{ flex: 1 }}>
        <div style={{ fontWeight: 600, fontSize: 13 }}>{title}</div>
        <div className="muted" style={{ fontSize: 12, marginTop: 1 }}>{desc}</div>
      </div>
      {hot > 0 && <Chip tone="danger">{hot} срочно</Chip>}
      <div style={{ minWidth: 32, textAlign: "right", fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 20, fontVariantNumeric: "tabular-nums" }}>{count}</div>
      <Icon name="chevron_right" size={14} className="muted"/>
    </div>
  );
};

const Activity = ({ actor, action, sub, time }) => (
  <div style={{ display: "flex", gap: 10, padding: "8px 0", borderBottom: "1px solid var(--neutral-100)", fontSize: 12 }}>
    <Avatar name={actor} size={22}/>
    <div style={{ flex: 1 }}>
      <div><strong>{actor}</strong> <span className="muted">·</span> {action}</div>
      <div className="muted" style={{ fontSize: 11 }}>{sub}</div>
    </div>
    <div className="muted tabular" style={{ fontSize: 11 }}>{time}</div>
  </div>
);

/* =====================  DEALS GRID (Airtable-style)  ===================== */
function DealsScreen({ navigate }) {
  const { t, lang } = useI18n();

  // Enrich deal rows with linked-record metadata
  const rows = useMemo(() => window.DATA.deals.map(d => {
    const c = findParty(d.customer); const eu = findParty(d.end_user); const v = findParty(d.vehicle);
    return {
      ...d,
      title: lang === "en" ? d.title_en : d.title,
      stage: stageKey(d.stage_en),
      _customer: c,
      _customer_pills: c ? [{ id: c.id, label: c.short, flag: c.country }] : [],
      _eu_pills: eu ? [{ id: eu.id, label: eu.short, flag: eu.country }] : [],
      _vehicle_pills: v ? [{ id: v.id, label: v.short, flag: v.country }] : [],
      items: { done: d.items_done, total: d.items_count },
      systems: { amo: !!d.amo_id, asana: !!d.asana_gid, drive: !!d.drive, onec: false },
    };
  }), [lang]);

  const stages = [
    { value: "inquiry", label: "Заявка", color: "gray" },
    { value: "sourcing", label: "Поиск поставщиков", color: "yellow" },
    { value: "spec", label: "Спецификация", color: "blue" },
    { value: "proposal", label: "КП заказчику", color: "purple" },
    { value: "procurement", label: "Закупка", color: "orange" },
    { value: "delivery", label: "Поставка", color: "teal" },
    { value: "closed", label: "Завершено", color: "green" },
  ];

  const columns = [
    { id: "id", label: "SORP-ключ", type: "text", width: 110, mono: true },
    { id: "title", label: "Сделка", type: "primary", width: 320 },
    { id: "_customer_pills", label: "Заказчик", type: "linked", width: 200 },
    { id: "_eu_pills", label: "Конечник", type: "linked", width: 180 },
    { id: "_vehicle_pills", label: "Заход", type: "linked", width: 180 },
    { id: "stage", label: "Этап", type: "status_workflow", width: 230, options: stages },
    { id: "value_usd", label: "Сумма", type: "currency", ccy: "USD", width: 130 },
    { id: "margin_pct", label: "Маржа", type: "percent", width: 90 },
    { id: "deadline", label: "Дедлайн", type: "date", width: 160 },
    { id: "items", label: "Позиции", type: "progress", width: 150 },
    { id: "systems", label: "Системы", type: "systems", width: 130 },
    { id: "managers", label: "Менеджеры", type: "users", width: 100 },
    { id: "sanctions", label: "Санкции", type: "sanctions", width: 120,
      options: [
        { value: "clean", label: "Чисто", color: "green" },
        { value: "review", label: "Review", color: "yellow" },
        { value: "flag", label: "Flag", color: "red" },
      ] },
  ];

  const views = [
    { name: "Все сделки", kind: "grid", count: rows.length,
      sort: [{ field: "deadline", dir: "asc" }] },
    { name: "По этапу", kind: "kanban", stackBy: "stage" },
    { name: "Календарь дедлайнов", kind: "calendar", dateField: "deadline" },
    { name: "Галерея high-value", kind: "gallery",
      filter: [{ field: "value_usd", op: "gt", value: 100000 }] },
    { name: "Срочные ≤ 30д", kind: "grid",
      filter: [{ field: "stage", op: "not", value: "closed" }],
      sort: [{ field: "deadline", dir: "asc" }],
      colorBy: "sanctions" },
    { name: "Группа по этапу", kind: "grid", groupBy: "stage",
      sort: [{ field: "value_usd", dir: "desc" }] },
  ];

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

function stageKey(en) {
  return ({
    "Inquiry": "inquiry",
    "Sourcing": "sourcing",
    "Spec sheet": "spec",
    "Proposal sent": "proposal",
    "Procurement": "procurement",
    "Delivery": "delivery",
    "Closed": "closed",
  })[en] || "spec";
}

/* =====================  DEAL CARD  ===================== */
function DealCardScreen({ navigate, params }) {
  const { t, lang } = useI18n();
  const id = params?.id || "SORP-3929";
  const d = findDeal(id) || window.DATA.deals[0];
  const cust = findParty(d.customer);
  const eu = findParty(d.end_user);
  const veh = findParty(d.vehicle);
  const [tab, setTab] = useState("items");

  return (
    <div style={{ flex: 1, overflow: "auto" }}>
      {/* Header */}
      <div style={{ padding: "20px 24px 0", background: "var(--bg-surface)", borderBottom: "1px solid var(--border-subtle)" }}>
        <div className="row" style={{ marginBottom: 4, fontSize: 11, color: "var(--fg-3)" }}>
          <span className="mono">SORP-key</span><span>·</span>
          <span>{lang === "ru" ? "обновлено" : "updated"} {d.updated}</span>
          <span>·</span>
          <span>{lang === "ru" ? "создано" : "created"} {d.created}</span>
        </div>
        <div className="row" style={{ alignItems: "flex-start" }}>
          <div style={{ flex: 1 }}>
            <h1 style={{ margin: 0, fontSize: 24, fontWeight: 600, fontFamily: "var(--font-display)", letterSpacing: "-0.01em" }}>
              <span style={{ color: "var(--sorp-red)", fontWeight: 700, marginRight: 12 }}>{d.id}</span>
              {lang === "en" ? d.title_en : d.title}
            </h1>
            <div className="row" style={{ marginTop: 10, flexWrap: "wrap", gap: 6 }}>
              <Chip tone="ink">{lang === "en" ? d.stage_en : d.stage}</Chip>
              <SanctionsChip status={d.sanctions}/>
              <Chip tone="outline"><Icon name="parties" size={11}/> {cust?.short} · <span className="muted">{lang === "ru" ? "заказчик" : "customer"}</span></Chip>
              {eu?.id !== cust?.id && <Chip tone="outline"><Icon name="flag" size={11}/> {eu?.short} · <span className="muted">{lang === "ru" ? "конечник" : "end-user"}</span></Chip>}
              <Chip tone="outline"><Icon name="box" size={11}/> {veh?.short} · <span className="muted">{lang === "ru" ? "заход" : "vehicle"}</span></Chip>
              <Chip tone="outline">{fmtMoney(d.value_usd, "USD")} · {d.margin_pct}% маржа</Chip>
              <Chip tone="outline">{lang === "ru" ? "дедлайн" : "deadline"}: {d.deadline}</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 primary"><Icon name="file" size={13}/> {t("generateProposal")}</button>
          </div>
        </div>

        {/* Cross-system links */}
        <div className="row" style={{ gap: 0, marginTop: 16, paddingBottom: 12, flexWrap: "wrap" }}>
          <SystemLink color="#2E91FE" label="AmoCRM" id={"#" + d.amo_id} sub={lang === "ru" ? "сделка · sales pipeline" : "deal · sales pipeline"} status="ok"/>
          <SystemLink color="#F06A6A" label="Asana" id={d.asana_gid} sub={lang === "ru" ? "задача · 42 кастом-поля · 12 комментариев" : "task · 42 custom fields · 12 comments"} status="ok"/>
          <SystemLink color="#1A73E8" label="Drive" id={d.drive} sub={lang === "ru" ? "папка · 18 документов · OCR готов" : "folder · 18 docs · OCR ready"} status="ok"/>
          <SystemLink color="#FFC700" label="1C" id="—" sub={lang === "ru" ? "ожидается этап 3" : "stage 3 planned"} status="pending"/>
        </div>

        <div className="tabs" style={{ padding: 0, marginTop: 8, borderBottom: 0 }}>
          {[
            { id: "items", label: t("items"), n: d.items_count },
            { id: "sourcing", label: t("sourcing"), n: 4 },
            { id: "docs", label: t("docs"), n: 18 },
            { id: "history", label: t("history"), n: 42 },
            { id: "parties", label: lang === "ru" ? "Стороны" : "Parties", n: 5 },
          ].map(x =>
            <button key={x.id} className={"tab " + (tab === x.id ? "active" : "")} onClick={() => setTab(x.id)}>
              {x.label} <span className="count tabular">{x.n}</span>
            </button>
          )}
        </div>
      </div>

      {/* Body */}
      {tab === "items" && <DealItemsTab/>}
      {tab === "sourcing" && <DealSourcingTab/>}
      {tab === "docs" && <DealDocsTab/>}
      {tab === "history" && <DealHistoryTab/>}
      {tab === "parties" && <DealPartiesTab d={d} cust={cust} eu={eu} veh={veh}/>}
    </div>
  );
}

const SystemLink = ({ color, label, id, sub, status }) => (
  <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "10px 14px", border: "1px solid var(--border-subtle)", borderRadius: 8, marginRight: 8, minWidth: 220, background: "var(--bg-page)" }}>
    <span style={{ width: 8, height: 8, borderRadius: 999, background: color, flexShrink: 0 }}/>
    <div style={{ minWidth: 0, flex: 1 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 6, fontWeight: 600, fontSize: 12 }}>
        <span style={{ color }}>{label}</span>
        <span className="mono muted" style={{ fontSize: 11, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", maxWidth: 130 }}>{id}</span>
      </div>
      <div className="muted" style={{ fontSize: 10.5, marginTop: 2 }}>{sub}</div>
    </div>
    {status === "ok" && <Icon name="arrow_up_right" size={12} className="muted"/>}
    {status === "pending" && <Chip tone="outline">soon</Chip>}
  </div>
);

function DealItemsTab() {
  const { lang } = useI18n();
  return (
    <div className="grid-wrap">
      <table className="dg dense" style={{ background: "var(--bg-surface)" }}>
        <thead>
          <tr>
            <th style={{ width: 30 }}>№</th>
            <th>{lang === "ru" ? "Запрошено" : "Requested"}</th>
            <th>{lang === "ru" ? "Принято / артикул" : "Accepted / SKU"}</th>
            <th className="num">HS</th>
            <th className="num">{lang === "ru" ? "Кол-во" : "Qty"}</th>
            <th>{lang === "ru" ? "Поставщик" : "Supplier"}</th>
            <th className="num">{lang === "ru" ? "Закупка" : "Buy"}</th>
            <th className="num">{lang === "ru" ? "Продажа" : "Sell"}</th>
            <th className="num">{lang === "ru" ? "Маржа" : "Margin"}</th>
            <th className="num">{lang === "ru" ? "Срок" : "Lead"}</th>
            <th>{lang === "ru" ? "Сертификат" : "Cert"}</th>
            <th>{lang === "ru" ? "Сан." : "Sanc."}</th>
          </tr>
        </thead>
        <tbody>
          {window.DATA.dealItems_3929.map((it, i) => {
            const sup = it.supplier ? findParty(it.supplier) : null;
            const empty = !it.name_acc || it.name_acc === "—";
            return (
              <tr key={i}>
                <td className="mono">{it.idx}</td>
                <td><span className="v">{it.name_req}</span></td>
                <td>{empty ? <span className="empty-cell">{lang === "ru" ? "не подтверждено" : "not accepted"}</span> : (
                  <div className="cell-with-badge"><span className="v" style={{ fontWeight: 500 }}>{it.name_acc}</span><FieldBadge src="ai" conf={0.91} raw={it.name_req}/></div>
                )}</td>
                <td className="num mono">{it.hs || "—"}</td>
                <td className="num tabular">{empty ? <span className="empty-cell">{it.qty_req} запр.</span> : it.qty_acc}</td>
                <td>{sup ? <div className="cell-with-badge"><Flag code={sup.country}/><span className="v">{sup.short}</span></div> : <span className="empty-cell">{lang === "ru" ? "в сорсинге" : "in sourcing"}</span>}</td>
                <td className="num tabular">{it.buy ? fmtMoney(it.buy.price, it.buy.ccy) : <span className="empty-cell">—</span>}</td>
                <td className="num tabular">{it.sell ? fmtMoney(it.sell.price, it.sell.ccy) : <span className="empty-cell">—</span>}</td>
                <td className="num tabular">{it.margin_pct ? it.margin_pct + "%" : "—"}</td>
                <td className="num tabular">{it.lead_days ? it.lead_days + "д" : "—"}</td>
                <td>{it.cert === "ok" ? <Chip tone="success">EAC/CT-1</Chip> : it.cert === "pending" ? <Chip tone="warning">Ожидается</Chip> : <Chip tone="outline">—</Chip>}</td>
                <td>{it.sanctions ? <Chip tone="danger">Flag</Chip> : <Chip tone="success">OK</Chip>}</td>
              </tr>
            );
          })}
        </tbody>
      </table>
      <div style={{ padding: "12px 16px", borderTop: "1px solid var(--border-subtle)", display: "flex", alignItems: "center", gap: 12, fontSize: 12, background: "var(--bg-surface)" }}>
        <Chip tone="warning"><Icon name="alert" size={11}/> 1 позиция без поставщика — отправить в сорсинг?</Chip>
        <Chip tone="info">Итого: 5 позиций · $98 460 закупка · $112 100 продажа · 13.9% маржа взвешенная</Chip>
        <span style={{ marginLeft: "auto" }} className="muted">Курсы: USD 78.42 · EUR 84.10 · AED 21.35 · от 2026-05-27 ЦБ РФ</span>
      </div>
    </div>
  );
}

function DealSourcingTab() {
  return (
    <div style={{ padding: 24 }}>
      <div className="card">
        <div className="card-head">
          <Icon name="search" size={14}/> <h3>Сорсинг: подшипник радиально-упорный 7224 · HS 8482.10</h3>
          <span style={{ flex: 1 }}/>
          <Chip tone="warning">4 кандидата</Chip>
        </div>
        <div className="card-body" style={{ padding: 0 }}>
          {[
            { name: "Wuxi WLR Bearings Co., Ltd.", country: "CN", price: "$142", lead: 28, sanc: "clean", cap: 0.91, note: "Прямой производитель, MOQ 100" },
            { name: "ZWZ Wafangdian Bearing Group", country: "CN", price: "$165", lead: 35, sanc: "clean", cap: 0.85, note: "В каталоге аналог 7224C" },
            { name: "Harbin HRB Group", country: "CN", price: "$180", lead: 42, sanc: "clean", cap: 0.78, note: "Через дистрибутора в OAE" },
            { name: "NSK Asia Ltd.", country: "JP", price: "$210", lead: 60, sanc: "review", cap: 0.95, note: "Может отказать — комплаенс смотрит" },
          ].map((c, i) => (
            <div key={i} style={{ display: "flex", alignItems: "center", gap: 16, padding: "12px 16px", borderBottom: "1px solid var(--neutral-100)" }}>
              <Flag code={c.country.toLowerCase()}/>
              <div style={{ flex: 1 }}>
                <div style={{ fontWeight: 600, fontSize: 13 }}>{c.name}</div>
                <div className="muted" style={{ fontSize: 11, marginTop: 2 }}>{c.note}</div>
              </div>
              <div style={{ minWidth: 100 }}>
                <div className="muted" style={{ fontSize: 10 }}>Совпадение возможностей</div>
                <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
                  <div style={{ width: 50, height: 4, background: "var(--neutral-200)", borderRadius: 2, overflow: "hidden" }}><div style={{ height: "100%", width: (c.cap * 100) + "%", background: "var(--status-success)" }}/></div>
                  <span className="tabular" style={{ fontSize: 11 }}>{Math.round(c.cap * 100)}%</span>
                </div>
              </div>
              <div className="mono tabular" style={{ minWidth: 70, textAlign: "right" }}>{c.price}</div>
              <div className="tabular muted" style={{ minWidth: 50, textAlign: "right" }}>{c.lead}д</div>
              <SanctionsChip status={c.sanc}/>
              <button className="btn sm primary">Запрос КП</button>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function DealDocsTab() {
  const docs = [
    { name: "Заявка-Северсталь-Метиз_v1.pdf", type: "inquiry", typed: 0.99, size: "1.2 MB", date: "2026-04-12" },
    { name: "КП-Schaeffler-SORP-3929-v3.pdf", type: "proposal", typed: 0.98, size: "486 KB", date: "2026-05-26" },
    { name: "Spec-bearings-confirmed.xlsx", type: "spec", typed: 0.95, size: "112 KB", date: "2026-05-22" },
    { name: "Invoice INV-2026-04321.pdf", type: "invoice", typed: 0.92, size: "230 KB", date: "—", scanned: true },
    { name: "Bill_of_Lading_MSC_38421.pdf", type: "customs", typed: 0.81, size: "1.8 MB", date: "—", scanned: true },
    { name: "Pmt-Caspian-USD-104k.pdf", type: "payment", typed: 0.71, size: "210 KB", date: "—" },
    { name: "Photo-pre-shipment.jpg", type: "photo", typed: 0.96, size: "3.4 MB", date: "—" },
    { name: "EAC-cert-SKF-bearings.pdf", type: "cert", typed: 0.94, size: "780 KB", date: "—" },
  ];
  const types = { inquiry: "Заявка", proposal: "КП", spec: "Спецификация", invoice: "Инвойс", customs: "Таможня", payment: "Платёж", photo: "Фото", cert: "Сертификат" };
  return (
    <div style={{ padding: 24 }}>
      <div className="card">
        <div className="card-head">
          <Icon name="docs" size={14}/> <h3>Папка Google Drive · 18 документов · OCR готов</h3>
          <span style={{ flex: 1 }}/>
          <button className="btn ghost sm"><Icon name="upload" size={12}/> Загрузить</button>
        </div>
        <table className="dg dense">
          <thead>
            <tr>
              <th style={{ width: 24 }}><Icon name="file" size={12}/></th>
              <th>Файл</th>
              <th>Тип (ИИ-распознан)</th>
              <th className="num">Размер</th>
              <th>Дата в документе</th>
              <th>Источник</th>
            </tr>
          </thead>
          <tbody>
            {docs.map((d, i) => (
              <tr key={i}>
                <td><Icon name="file" size={14} className="muted"/></td>
                <td><span className="v" style={{ fontWeight: 500 }}>{d.name}</span> {d.scanned && <Chip tone="outline">скан · OCR</Chip>}</td>
                <td><div className="cell-with-badge"><Chip tone="info">{types[d.type]}</Chip><FieldBadge src="ai" conf={d.typed}/></div></td>
                <td className="num tabular muted">{d.size}</td>
                <td className="mono">{d.date}</td>
                <td><Chip tone="outline"><span style={{ color: "#1A73E8", fontWeight: 700, fontSize: 9 }}>Drive</span></Chip></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function DealHistoryTab() {
  const events = [
    { who: "Е. Соколова",   what: "stage", old: "Поиск поставщиков", neu: "Спецификация", when: "сегодня 14:08", src: "manual" },
    { who: "ИИ Claude",     what: "items[03].supplier", old: "—", neu: "Schaeffler Middle East FZE", when: "сегодня 12:18", src: "ai", conf: 0.94 },
    { who: "Service",       what: "amo_id", old: "—", neu: "47821", when: "сегодня 03:14", src: "amo" },
    { who: "Д. Петров",     what: "deadline", old: "2026-07-04", neu: "2026-07-18", when: "вчера 16:42", src: "manual" },
    { who: "Service",       what: "asana_gid",  old: "—", neu: "1206734821093", when: "2026-05-20 11:30", src: "asana" },
    { who: "С. Кравцов",    what: "title", old: "Подшипники SKF для ТМК", neu: "Промышленные подшипники SKF для ТМК Волжский", when: "2026-04-12 10:12", src: "manual" },
  ];
  return (
    <div style={{ padding: 24, maxWidth: 900 }}>
      <div className="card">
        <div className="card-head"><Icon name="history" size={14}/> <h3>История изменений</h3></div>
        <div>
          {events.map((e, i) => (
            <div key={i} style={{ display: "flex", alignItems: "center", gap: 12, padding: "10px 16px", borderBottom: "1px solid var(--neutral-100)", fontSize: 12.5 }}>
              <Avatar name={e.who} size={22}/>
              <div style={{ minWidth: 160 }}>{e.who}</div>
              <span className="mono muted" style={{ minWidth: 140 }}>{e.what}</span>
              <span className="muted" style={{ minWidth: 140, textDecoration: "line-through" }}>{e.old}</span>
              <Icon name="arrow_right" size={11} className="muted"/>
              <strong style={{ minWidth: 220 }}>{e.neu}</strong>
              <FieldBadge src={e.src} conf={e.conf || 1}/>
              <span className="muted" style={{ marginLeft: "auto", fontSize: 11 }}>{e.when}</span>
              <button className="btn ghost sm"><Icon name="undo" size={11}/></button>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function DealPartiesTab({ d, cust, eu, veh }) {
  const parties = [
    { p: cust, role: "customer", note: "Подписант: А. Морозов · ген. директор" },
    { p: eu, role: "end_user", note: "Конечник = заказчику · single-tier поставка" },
    { p: veh, role: "vehicle", note: "Наша компания-заход · Dubai (DAFZA)" },
    { p: findParty("p_2001"), role: "supplier", note: "Подшипники · поз. 01-02-05" },
    { p: findParty("p_2003"), role: "supplier", note: "Подшипники конические · поз. 03 · ⚠️ возможный дубль" },
  ];
  return (
    <div style={{ padding: 24 }}>
      {parties.filter(x => x.p).map(({ p, role, note }) => (
        <div key={p.id + role} className="card" style={{ marginBottom: 12 }}>
          <div className="card-head">
            <RoleChip role={role}/>
            <div style={{ marginLeft: 8 }}>
              <div style={{ fontWeight: 600 }}>{p.full}</div>
              <div className="muted" style={{ fontSize: 11 }}>{note}</div>
            </div>
            <span style={{ flex: 1 }}/>
            <SanctionsChip status={p.screening}/>
            <button className="btn ghost sm">Открыть карточку <Icon name="arrow_up_right" size={11}/></button>
          </div>
        </div>
      ))}
    </div>
  );
}

function DealsCompact({ navigate }) {
  const { lang } = useI18n();
  return (
    <table className="dg dense">
      <thead>
        <tr>
          <th>ID</th>
          <th>{lang === "ru" ? "Сделка" : "Deal"}</th>
          <th>{lang === "ru" ? "Заказчик" : "Customer"}</th>
          <th>{lang === "ru" ? "Этап" : "Stage"}</th>
          <th className="num">{lang === "ru" ? "Сумма" : "Value"}</th>
          <th className="num">{lang === "ru" ? "Маржа" : "Margin"}</th>
          <th>{lang === "ru" ? "Дедлайн" : "Deadline"}</th>
          <th className="num">{lang === "ru" ? "Поз." : "Items"}</th>
          <th>{lang === "ru" ? "Санкции" : "Sanc."}</th>
        </tr>
      </thead>
      <tbody>
        {window.DATA.deals.map(d => {
          const cust = findParty(d.customer);
          return (
            <tr key={d.id} onClick={() => navigate("deal", { id: d.id })}>
              <td><a style={{ color: "var(--sorp-red)", textDecoration: "none", fontWeight: 700 }} className="mono">{d.id}</a></td>
              <td><span className="v">{lang === "en" ? d.title_en : d.title}</span></td>
              <td><div className="cell-with-badge"><Flag code={cust?.country}/><span className="v">{cust?.short}</span></div></td>
              <td><Chip tone="info">{lang === "en" ? d.stage_en : d.stage}</Chip></td>
              <td className="num tabular">{fmtMoney(d.value_usd, "USD")}</td>
              <td className="num tabular">{d.margin_pct}%</td>
              <td className="mono">{d.deadline}</td>
              <td className="num tabular">{d.items_done}/{d.items_count}</td>
              <td><SanctionsChip status={d.sanctions}/></td>
            </tr>
          );
        })}
      </tbody>
    </table>
  );
}

window.HomeScreen = HomeScreen;
window.DealsScreen = DealsScreen;
window.DealCardScreen = DealCardScreen;
window.DealsCompact = DealsCompact;
