// MDM SORP — Dashboards (M12).

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

function DashboardScreen({ navigate }) {
  const { t, lang } = useI18n();
  const [view, setView] = useState("director"); // director | procurement | compliance | dq
  return (
    <div style={{ flex: 1, overflow: "auto" }}>
      <div className="grid-toolbar">
        <h2>{lang === "ru" ? "Аналитика · Metabase" : "Analytics · Metabase"}</h2>
        <div className="lang-toggle" style={{ marginLeft: 8 }}>
          {[
            { id: "director", label: lang === "ru" ? "Руководитель" : "Director" },
            { id: "procurement", label: lang === "ru" ? "Закупки" : "Procurement" },
            { id: "compliance", label: lang === "ru" ? "Комплаенс" : "Compliance" },
            { id: "dq", label: lang === "ru" ? "Качество данных" : "Data quality" },
          ].map(x => (
            <button key={x.id} className={view === x.id ? "active" : ""} onClick={() => setView(x.id)}>{x.label}</button>
          ))}
        </div>
        <div style={{ flex: 1 }}/>
        <button className="filter-pill"><Icon name="filter" size={12}/> 2026 Q2</button>
        <button className="filter-pill">Все менеджеры</button>
        <button className="filter-pill">RUB</button>
        <button className="btn ghost sm"><Icon name="download" size={12}/> {t("export")}</button>
      </div>

      {view === "director" && <DirectorBoard/>}
      {view === "procurement" && <ProcurementBoard/>}
      {view === "compliance" && <ComplianceBoard/>}
      {view === "dq" && <DataQualityBoard navigate={navigate}/>}
    </div>
  );
}

function DirectorBoard() {
  return (
    <div className="dashboard-grid">
      <div className="kpi"><div className="lbl">Активные сделки</div><div className="v">38</div><div className="delta up"><Icon name="arrow_up_right" size={11}/> +4</div><div className="muted" style={{ fontSize: 11 }}>против пр. недели</div></div>
      <div className="kpi"><div className="lbl">Закупочный бюджет</div><div className="v">$ 4.2M</div><div className="delta up"><Icon name="arrow_up_right" size={11}/> +12%</div><div className="muted" style={{ fontSize: 11 }}>USD, по курсу ЦБ</div></div>
      <div className="kpi"><div className="lbl">Средняя маржа</div><div className="v">14.8%</div><div className="delta down" style={{ color: "var(--sorp-red)" }}><Icon name="arrow_right" size={11}/> −0.6п</div><div className="muted" style={{ fontSize: 11 }}>цель: 16%</div></div>
      <div className="kpi"><div className="lbl">Прогноз поставки</div><div className="v">92%</div><div className="delta up"><Icon name="arrow_up_right" size={11}/> +3п</div><div className="muted" style={{ fontSize: 11 }}>в срок к дедлайну</div></div>

      <div className="panel" style={{ gridColumn: "span 8" }}>
        <div className="panel-head"><h3>Воронка заявок · ₽ млн в каждом этапе</h3><span className="sub">drill-down: клик по столбцу → список сделок</span></div>
        <div className="panel-body" style={{ height: 280 }}>
          <FunnelChart/>
        </div>
      </div>
      <div className="panel" style={{ gridColumn: "span 4" }}>
        <div className="panel-head"><h3>Маржа по направлениям</h3><span className="sub">YTD</span></div>
        <div className="panel-body">
          {[
            { name: "Подшипники", mar: 14.6, val: 1820 },
            { name: "Гидравлика", mar: 17.2, val: 940 },
            { name: "ЧПУ запчасти", mar: 22.4, val: 410 },
            { name: "Метизы", mar: 26.5, val: 280 },
            { name: "Редукторы", mar: 11.8, val: 750 },
          ].map((b, i) => (
            <div key={i} className="row" style={{ padding: "8px 0", fontSize: 12 }}>
              <div style={{ flex: 1 }}>{b.name}</div>
              <div style={{ width: 140, marginRight: 12 }}>
                <div style={{ height: 6, background: "var(--neutral-200)", borderRadius: 3 }}>
                  <div style={{ width: (b.mar / 30 * 100) + "%", height: "100%", background: b.mar > 20 ? "var(--status-success)" : b.mar > 15 ? "var(--sorp-red)" : "var(--status-warning)", borderRadius: 3 }}/>
                </div>
              </div>
              <div className="tabular" style={{ width: 50, textAlign: "right" }}>{b.mar}%</div>
              <div className="tabular muted" style={{ width: 60, textAlign: "right" }}>${b.val}k</div>
            </div>
          ))}
        </div>
      </div>

      <div className="panel" style={{ gridColumn: "span 6" }}>
        <div className="panel-head"><h3>Тренд: маржа vs закупочный бюджет</h3><span className="sub">12 недель</span></div>
        <div className="panel-body" style={{ height: 220 }}>
          <LineChart/>
        </div>
      </div>
      <div className="panel" style={{ gridColumn: "span 6" }}>
        <div className="panel-head"><h3>Дедлайны · 14 дней</h3><span className="sub">«успеем»/«риск»/«просрочка»</span></div>
        <div className="panel-body">
          {window.DATA.deals.slice(0, 5).map(d => {
            const days = Math.round((new Date(d.deadline) - new Date("2026-05-27")) / 86400000);
            const tone = days > 14 ? "success" : days > 0 ? "warning" : "danger";
            return (
              <div key={d.id} className="row" style={{ padding: "8px 0", fontSize: 12 }}>
                <span className="mono" style={{ color: "var(--sorp-red)", fontWeight: 700, width: 80 }}>{d.id}</span>
                <span style={{ flex: 1, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{d.title}</span>
                <Chip tone={tone}>{days > 0 ? `${days}д` : "просрочка"}</Chip>
                <span className="mono muted" style={{ marginLeft: 8, width: 80, textAlign: "right" }}>{d.deadline}</span>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

function ProcurementBoard() {
  return (
    <div className="dashboard-grid">
      <div className="kpi"><div className="lbl">Поставщиков активных</div><div className="v">68</div><div className="muted" style={{ fontSize: 11 }}>+4 за месяц</div></div>
      <div className="kpi"><div className="lbl">Открытые RFQ</div><div className="v">14</div><div className="muted" style={{ fontSize: 11 }}>5 ждут ответа &gt;48ч</div></div>
      <div className="kpi"><div className="lbl">Ср. lead time</div><div className="v">34<span style={{ fontSize: 14, color: "var(--fg-3)" }}> д</span></div><div className="muted" style={{ fontSize: 11 }}>оптимум: 30</div></div>
      <div className="kpi"><div className="lbl">Себест. логистика+таможня</div><div className="v">7.8%</div><div className="muted" style={{ fontSize: 11 }}>от закупки в RUB</div></div>

      <div className="panel" style={{ gridColumn: "span 12" }}>
        <div className="panel-head"><h3>Поставщики по объёму ($) · топ-10</h3></div>
        <div className="panel-body">
          {[
            { name: "SKF Middle East FZE", c: "ae", v: 982, deals: 14, lead: 32, sanc: "clean" },
            { name: "Schaeffler Middle East FZE", c: "ae", v: 740, deals: 11, lead: 35, sanc: "clean" },
            { name: "Wuxi WLR Bearings", c: "cn", v: 412, deals: 8, lead: 28, sanc: "clean" },
            { name: "Erkunt Sanayi A.Ş.", c: "tr", v: 286, deals: 4, lead: 42, sanc: "clean" },
            { name: "Bosch Rexroth ME", c: "ae", v: 184, deals: 3, lead: 30, sanc: "clean" },
            { name: "Siemens (Shanghai) Industrial", c: "cn", v: 91, deals: 2, lead: 45, sanc: "review" },
          ].map((s, i) => (
            <div key={i} className="row" style={{ padding: "8px 0", borderBottom: "1px solid var(--neutral-100)", fontSize: 12 }}>
              <Flag code={s.c}/>
              <span style={{ flex: 1, fontWeight: 500 }}>{s.name}</span>
              <div style={{ width: 240 }}>
                <div style={{ height: 6, background: "var(--neutral-200)", borderRadius: 3 }}>
                  <div style={{ width: (s.v / 1000 * 100) + "%", height: "100%", background: "var(--sorp-red)", borderRadius: 3 }}/>
                </div>
              </div>
              <span className="tabular" style={{ width: 80, textAlign: "right" }}>${s.v}k</span>
              <span className="tabular muted" style={{ width: 60, textAlign: "right" }}>{s.deals} сд.</span>
              <span className="tabular muted" style={{ width: 50, textAlign: "right" }}>{s.lead}д</span>
              <SanctionsChip status={s.sanc}/>
            </div>
          ))}
        </div>
      </div>

      <div className="panel" style={{ gridColumn: "span 6" }}>
        <div className="panel-head"><h3>Мультивалюта закупок · доля по сумме</h3></div>
        <div className="panel-body" style={{ display: "flex", alignItems: "center", gap: 24 }}>
          <DonutChart segments={[
            { label: "USD", v: 56, color: "#D63D4A" },
            { label: "EUR", v: 22, color: "#2C5C8C" },
            { label: "CNY", v: 14, color: "#2F7D5B" },
            { label: "AED", v: 8, color: "#C77A1F" },
          ]}/>
        </div>
      </div>
      <div className="panel" style={{ gridColumn: "span 6" }}>
        <div className="panel-head"><h3>Курс/наценка</h3><span className="sub">2026-05-27 · ЦБ РФ + 1.5%</span></div>
        <div className="panel-body" style={{ fontSize: 12 }}>
          {[
            { ccy: "USD", rate: 78.42, d: "+0.18" },
            { ccy: "EUR", rate: 84.10, d: "+0.32" },
            { ccy: "AED", rate: 21.35, d: "+0.05" },
            { ccy: "CNY", rate: 10.92, d: "−0.02" },
          ].map((r, i) => (
            <div key={i} className="row" style={{ padding: "8px 0", borderBottom: "1px solid var(--neutral-100)" }}>
              <span className="mono" style={{ fontWeight: 700, width: 50 }}>{r.ccy}</span>
              <span className="tabular" style={{ flex: 1 }}>{r.rate} ₽</span>
              <span className="tabular muted">{r.d}</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function ComplianceBoard() {
  return (
    <div className="dashboard-grid">
      <div className="kpi"><div className="lbl">Записей в базе</div><div className="v">2 184</div><div className="muted" style={{ fontSize: 11 }}>party — все роли</div></div>
      <div className="kpi"><div className="lbl">Под скринингом</div><div className="v">2 184</div><div className="muted" style={{ fontSize: 11 }}>OpenSanctions ежедневно</div></div>
      <div className="kpi"><div className="lbl">Совпадений</div><div className="v" style={{ color: "var(--sorp-red)" }}>3</div><div className="muted" style={{ fontSize: 11 }}>1 review · 2 false-positive</div></div>
      <div className="kpi"><div className="lbl">Dual-use позиции</div><div className="v" style={{ color: "var(--status-warning)" }}>27</div><div className="muted" style={{ fontSize: 11 }}>HS 8413/8481/8542</div></div>

      <div className="panel" style={{ gridColumn: "span 12" }}>
        <div className="panel-head"><h3>Активные комплаенс-флаги</h3><span className="sub">требуют решения</span></div>
        <table className="dg dense">
          <thead><tr><th>Что</th><th>Где</th><th>Какой список</th><th>Источник флага</th><th>Прим.</th><th></th></tr></thead>
          <tbody>
            <tr>
              <td><strong>Siemens (Shanghai) Industrial Trading</strong></td>
              <td><Chip tone="outline">Поставщик</Chip> · 2 сделки</td>
              <td><Chip tone="warning">EAR99 advisory</Chip></td>
              <td><FieldBadge src="ai" conf={0.78} raw="OpenSanctions hit · 2026-05-27"/></td>
              <td>Связь с подсанкционной материнской</td>
              <td><button className="btn sm primary">Решение</button></td>
            </tr>
            <tr>
              <td><strong>SORP-3955 · позиция 04</strong></td>
              <td><Chip tone="outline">deal_item</Chip></td>
              <td><Chip tone="warning">Dual-use HS 8482.10</Chip></td>
              <td><FieldBadge src="ai" conf={0.94}/></td>
              <td>Подшипник 7224 — подшипники для прокатных станов</td>
              <td><button className="btn sm">Сертификат</button></td>
            </tr>
            <tr>
              <td><strong>p_2003 Schaffler M.E. Trading</strong></td>
              <td><Chip tone="outline">Поставщик</Chip></td>
              <td><Chip tone="outline">—</Chip></td>
              <td><FieldBadge src="ai" conf={0.41}/></td>
              <td>Низкое доверие · возможный фейк/дубль</td>
              <td><button className="btn sm">Открыть дедуп</button></td>
            </tr>
          </tbody>
        </table>
      </div>

      <div className="panel" style={{ gridColumn: "span 6" }}>
        <div className="panel-head"><h3>Санкционная экспозиция портфеля</h3><span className="sub">по сумме сделок</span></div>
        <div className="panel-body" style={{ display: "flex", alignItems: "center", gap: 24 }}>
          <DonutChart segments={[
            { label: "Clean", v: 86, color: "#2F7D5B" },
            { label: "Review", v: 9, color: "#C77A1F" },
            { label: "Flag", v: 3, color: "#D63D4A" },
            { label: "Pending", v: 2, color: "#7A7468" },
          ]}/>
        </div>
      </div>
      <div className="panel" style={{ gridColumn: "span 6" }}>
        <div className="panel-head"><h3>Конечник ≠ заказчику</h3><span className="sub">parallel-import scenario</span></div>
        <div className="panel-body" style={{ fontSize: 12 }}>
          <div className="row" style={{ padding: "8px 0", borderBottom: "1px solid var(--neutral-100)" }}>
            <strong style={{ flex: 1 }}>SORP-3974 · Vesuvius rolls</strong>
            <Chip tone="outline">Северсталь-Метиз</Chip>
            <Icon name="arrow_right" size={11} className="muted" style={{ margin: "0 4px" }}/>
            <Chip tone="warning">ТМК Волжский</Chip>
          </div>
          <div className="row" style={{ padding: "8px 0", borderBottom: "1px solid var(--neutral-100)" }}>
            <strong style={{ flex: 1 }}>SORP-4011</strong>
            <Chip tone="outline">ООО «Холдинг-Запад»</Chip>
            <Icon name="arrow_right" size={11} className="muted" style={{ margin: "0 4px" }}/>
            <Chip tone="warning">3 разных АО</Chip>
          </div>
          <div className="muted" style={{ marginTop: 8, fontSize: 11 }}>Всего 9 сделок · «Конечник» обязателен по комплаенс-политике для проверки скрытого назначения.</div>
        </div>
      </div>
    </div>
  );
}

function DataQualityBoard({ navigate }) {
  return (
    <div className="dashboard-grid">
      <div className="kpi"><div className="lbl">Fill-rate party</div><div className="v">84%</div><div className="delta up"><Icon name="arrow_up_right" size={11}/> +1.2п</div></div>
      <div className="kpi"><div className="lbl">Дубли (кандидаты)</div><div className="v">4</div><div className="delta down" style={{ color: "var(--status-success)" }}><Icon name="arrow_right" size={11}/> −1</div></div>
      <div className="kpi"><div className="lbl">Ненормализованных</div><div className="v">62</div><div className="muted" style={{ fontSize: 11 }}>телефоны · email · адреса</div></div>
      <div className="kpi"><div className="lbl">Записей без источника</div><div className="v" style={{ color: "var(--sorp-red)" }}>11</div><div className="muted" style={{ fontSize: 11 }}>требует ручной разметки</div></div>

      <div className="panel" style={{ gridColumn: "span 8" }}>
        <div className="panel-head"><h3>Fill-rate по полям party</h3><span className="sub">из 2 184 записей</span></div>
        <div className="panel-body">
          {[
            { f: "ИНН / TRN",     v: 96 },
            { f: "Полное имя",    v: 99 },
            { f: "Телефон",       v: 88 },
            { f: "E-mail",        v: 79 },
            { f: "Адрес",         v: 71 },
            { f: "Бенефициар",    v: 28 },
            { f: "Координаты",    v: 64 },
            { f: "Капабилити",    v: 42 },
          ].map((r, i) => (
            <div key={i} className="row" style={{ padding: "7px 0", fontSize: 12 }}>
              <span style={{ flex: 1 }}>{r.f}</span>
              <div style={{ width: 360 }}>
                <div style={{ height: 6, background: "var(--neutral-200)", borderRadius: 3 }}>
                  <div style={{ width: r.v + "%", height: "100%", background: r.v > 80 ? "var(--status-success)" : r.v > 60 ? "var(--status-warning)" : "var(--sorp-red)", borderRadius: 3 }}/>
                </div>
              </div>
              <span className="tabular" style={{ width: 50, textAlign: "right" }}>{r.v}%</span>
              <button className="btn ghost sm" onClick={() => navigate("enrichment")}>Исправить</button>
            </div>
          ))}
        </div>
      </div>

      <div className="panel" style={{ gridColumn: "span 4" }}>
        <div className="panel-head"><h3>Источники данных</h3><span className="sub">в каких полях</span></div>
        <div className="panel-body">
          {[
            { s: "Amo", pct: 42, color: "#2E91FE" },
            { s: "Asana", pct: 28, color: "#F06A6A" },
            { s: "Drive (OCR)", pct: 12, color: "#1A73E8" },
            { s: "ИИ-обогащение", pct: 10, color: "#D63D4A" },
            { s: "Ручной ввод", pct: 7, color: "#3A4049" },
            { s: "Dadata", pct: 1, color: "#6E45E2" },
          ].map((r, i) => (
            <div key={i} className="row" style={{ padding: "6px 0", fontSize: 12 }}>
              <span style={{ width: 8, height: 8, borderRadius: 999, background: r.color }}/>
              <span style={{ flex: 1, marginLeft: 8 }}>{r.s}</span>
              <span className="tabular">{r.pct}%</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

/* ---------- Mini chart components (pure SVG) ---------- */
function FunnelChart() {
  const stages = [
    { name: "Заявка",   v: 4.2, n: 28 },
    { name: "Поиск",    v: 8.1, n: 18 },
    { name: "Спец.",    v: 6.6, n: 14 },
    { name: "Закупка",  v: 5.2, n: 9 },
    { name: "Поставка", v: 3.4, n: 7 },
    { name: "Завершено",v: 2.1, n: 5 },
  ];
  const max = Math.max(...stages.map(s => s.v));
  return (
    <div style={{ display: "flex", alignItems: "flex-end", gap: 16, height: 220, padding: "20px 16px 0" }}>
      {stages.map((s, i) => {
        const h = s.v / max * 180;
        return (
          <div key={i} style={{ flex: 1, display: "flex", flexDirection: "column", alignItems: "center", gap: 6 }}>
            <span className="tabular" style={{ fontSize: 12, fontWeight: 600 }}>{s.v}M ₽</span>
            <div style={{ width: "100%", height: h, background: i === 0 ? "var(--neutral-300)" : i === stages.length - 1 ? "var(--status-success)" : "var(--sorp-red)", opacity: 0.85, borderRadius: "8px 8px 0 0" }}/>
            <div style={{ fontSize: 11, color: "var(--fg-3)" }}>{s.name}</div>
            <div className="tabular" style={{ fontSize: 10, color: "var(--fg-3)" }}>{s.n} сделок</div>
          </div>
        );
      })}
    </div>
  );
}

function LineChart() {
  const w = 480, h = 200, pad = 24;
  const data = [12.4, 14.1, 13.8, 15.2, 14.9, 16.1, 15.4, 14.2, 13.6, 15.5, 16.8, 14.8];
  const max = Math.max(...data), min = Math.min(...data);
  const pts = data.map((v, i) => [pad + i / (data.length - 1) * (w - 2 * pad), h - pad - (v - min) / (max - min) * (h - 2 * pad)]);
  const d = pts.map((p, i) => (i === 0 ? "M" : "L") + p[0].toFixed(1) + "," + p[1].toFixed(1)).join(" ");
  return (
    <svg viewBox={`0 0 ${w} ${h}`} style={{ width: "100%", height: "100%" }}>
      <line x1={pad} y1={h - pad} x2={w - pad} y2={h - pad} stroke="var(--border-subtle)"/>
      <path d={d} stroke="var(--sorp-red)" strokeWidth="2" fill="none"/>
      <path d={d + ` L${pad + (w - 2 * pad)},${h - pad} L${pad},${h - pad} Z`} fill="var(--sorp-red)" opacity="0.08"/>
      {pts.map((p, i) => <circle key={i} cx={p[0]} cy={p[1]} r="2.5" fill="var(--sorp-red)"/>)}
      {pts.map((p, i) => i % 2 === 0 ? <text key={"l" + i} x={p[0]} y={h - 6} textAnchor="middle" style={{ fontSize: 10, fill: "var(--fg-3)" }}>W{i + 12}</text> : null)}
    </svg>
  );
}

function DonutChart({ segments }) {
  const total = segments.reduce((s, x) => s + x.v, 0);
  let a = -Math.PI / 2;
  const cx = 60, cy = 60, r = 50, r2 = 32;
  const paths = segments.map((s) => {
    const start = a; const len = s.v / total * Math.PI * 2; a += len;
    const x1 = cx + r * Math.cos(start),  y1 = cy + r * Math.sin(start);
    const x2 = cx + r * Math.cos(start + len), y2 = cy + r * Math.sin(start + len);
    const x3 = cx + r2 * Math.cos(start + len), y3 = cy + r2 * Math.sin(start + len);
    const x4 = cx + r2 * Math.cos(start), y4 = cy + r2 * Math.sin(start);
    const large = len > Math.PI ? 1 : 0;
    return `M${x1},${y1} A${r},${r} 0 ${large} 1 ${x2},${y2} L${x3},${y3} A${r2},${r2} 0 ${large} 0 ${x4},${y4} Z`;
  });
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 20 }}>
      <svg width="120" height="120" viewBox="0 0 120 120">
        {paths.map((d, i) => <path key={i} d={d} fill={segments[i].color}/>)}
      </svg>
      <div>
        {segments.map((s, i) => (
          <div key={i} className="row" style={{ padding: "3px 0", fontSize: 12, gap: 8 }}>
            <span style={{ width: 8, height: 8, borderRadius: 2, background: s.color }}/>
            <span style={{ minWidth: 80 }}>{s.label}</span>
            <span className="tabular" style={{ fontWeight: 600 }}>{s.v}%</span>
          </div>
        ))}
      </div>
    </div>
  );
}

window.DashboardScreen = DashboardScreen;
