// Dashboard — real analytics computed from the поручения register + documents.

function Dashboard({ onNavigate }) {
  const { BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer, CartesianGrid } = Recharts;
  const YEARS = [2024, 2025, 2026];
  const [year, setYear] = React.useState(2025);
  const [tasks, setTasks] = React.useState([]);
  const [docs, setDocs] = React.useState([]);
  const [loading, setLoading] = React.useState(true);

  const load = React.useCallback(() => {
    if (!window.API) { setLoading(false); return; }
    setLoading(true);
    Promise.all([
      window.API.listTasks().catch(() => []),
      window.API.listDocuments().catch(() => []),
    ]).then(([t, d]) => {
      setTasks(Array.isArray(t) ? t : []);
      setDocs(Array.isArray(d) ? d : []);
    }).finally(() => setLoading(false));
  }, []);
  React.useEffect(() => { load(); }, [load]);

  const eff = (t) => (typeof effStatus === "function" ? effStatus(t) : t.status);
  const yearTasks = tasks.filter(t => t.year === year);
  const stat = { total: yearTasks.length, done: 0, overdue: 0, work: 0 };
  yearTasks.forEach(t => {
    const e = eff(t);
    if (e === "done") stat.done++;
    else if (e === "overdue") stat.overdue++;
    else stat.work++;
  });
  const donePct = stat.total ? Math.round(stat.done / stat.total * 100) : 0;

  const months = (typeof MONTH_ORDER !== "undefined") ? MONTH_ORDER : [];
  const byMonth = months.map(m => ({ name: m.slice(0, 3), Поручений: yearTasks.filter(t => t.mon === m).length }));
  const depts = (typeof DEPARTMENTS !== "undefined") ? DEPARTMENTS : [];
  const byDept = depts.map(d => {
    const list = yearTasks.filter(t => t.dept === d);
    return {
      name: d.replace("Отдел ", "").replace(" отдел", ""),
      Всего: list.length,
      Выполнено: list.filter(t => eff(t) === "done").length,
    };
  }).filter(x => x.Всего > 0);

  const recent = docs.slice(0, 5);

  return (
    <div className="page page-fade">
      <div className="page-head">
        <div>
          <h1 className="page-title">Дашборд</h1>
          <p className="page-subtitle">Аналитика по реестру поручений · {year} год{loading ? " · загрузка…" : ""}</p>
        </div>
        <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
          <div className="seg">
            {YEARS.map(y => <button key={y} className={y === year ? "active" : ""} onClick={() => setYear(y)}>{y}</button>)}
          </div>
          <button className="btn btn-outline" onClick={load}><I.Refresh size={14} /> Обновить</button>
          <button className="btn btn-primary" onClick={() => onNavigate("chat")}><I.Sparkle size={14} /> Спросить ИИ</button>
        </div>
      </div>

      <div className="kpi-grid">
        <Kpi label="Всего поручений" value={stat.total} unit="" icon={<I.Clipboard size={16} />} foot={`за ${year} год`} deltaNeutral />
        <Kpi label="Выполнено" value={donePct} unit="%" icon={<I.CheckCircle size={16} />} foot={`${stat.done} из ${stat.total}`} deltaNeutral>
          <div className="progress-track"><div className="progress-fill" style={{ width: donePct + "%" }} /></div>
        </Kpi>
        <Kpi label="Просрочено" value={stat.overdue} unit="" icon={<I.Alert size={16} />} foot="требуют внимания" deltaNeutral />
        <Kpi label="В работе" value={stat.work} unit="" icon={<I.Hourglass size={16} />} foot="открытые поручения" deltaNeutral />
      </div>

      <div className="split" style={{ marginBottom: 16 }}>
        <Card title="Поручения по месяцам" subtitle={`${year} год`} bodyStyle={{ padding: "12px 8px 8px 0", height: 300 }}>
          <ResponsiveContainer width="100%" height="100%">
            <BarChart data={byMonth} margin={{ top: 10, right: 12, left: 6, bottom: 0 }}>
              <CartesianGrid stroke="var(--ink-100)" vertical={false} />
              <XAxis dataKey="name" tick={{ fill: "var(--ink-400)", fontSize: 11 }} axisLine={false} tickLine={false} />
              <YAxis tick={{ fill: "var(--ink-400)", fontSize: 11 }} axisLine={false} tickLine={false} width={44} allowDecimals={false} />
              <Tooltip cursor={{ fill: "var(--ink-50)" }} contentStyle={{ borderRadius: 8, border: "1px solid var(--ink-100)", fontSize: 12 }} />
              <Bar dataKey="Поручений" fill="var(--accent)" radius={[3, 3, 0, 0]} />
            </BarChart>
          </ResponsiveContainer>
        </Card>

        <Card title="По отделам" subtitle="всего и выполнено" bodyStyle={{ padding: "12px 8px 8px 0", height: 300 }}>
          <ResponsiveContainer width="100%" height="100%">
            <BarChart data={byDept} margin={{ top: 10, right: 12, left: 6, bottom: 0 }} barCategoryGap={14}>
              <CartesianGrid stroke="var(--ink-100)" vertical={false} />
              <XAxis dataKey="name" tick={{ fill: "var(--ink-400)", fontSize: 10 }} axisLine={false} tickLine={false} interval={0} angle={-12} textAnchor="end" height={48} />
              <YAxis tick={{ fill: "var(--ink-400)", fontSize: 11 }} axisLine={false} tickLine={false} width={44} allowDecimals={false} />
              <Tooltip cursor={{ fill: "var(--ink-50)" }} contentStyle={{ borderRadius: 8, border: "1px solid var(--ink-100)", fontSize: 12 }} />
              <Bar dataKey="Всего" fill="var(--ink-200)" radius={[3, 3, 0, 0]} />
              <Bar dataKey="Выполнено" fill="var(--ok)" radius={[3, 3, 0, 0]} />
            </BarChart>
          </ResponsiveContainer>
        </Card>
      </div>

      <Card
        title="Последние документы"
        subtitle={`${docs.length} в библиотеке`}
        action={<button className="btn btn-ghost" onClick={() => onNavigate("docs")}>Все документы <I.ArrowRight size={13} /></button>}
        bodyStyle={{ padding: 0 }}
      >
        <div className="tbl-wrap">
          <table className="tbl">
            <thead>
              <tr><th style={{ width: "46%" }}>Название</th><th>Тип</th><th>Загружен</th><th>Размер</th></tr>
            </thead>
            <tbody>
              {recent.length === 0 && (
                <tr><td colSpan="4" style={{ textAlign: "center", padding: "28px", color: "var(--ink-400)" }}>Документов пока нет — загрузите на странице «Документы»</td></tr>
              )}
              {recent.map(d => (
                <tr key={d.id}>
                  <td><div className="file-cell"><FileIcon type={d.type} /><span style={{ fontWeight: 500 }}>{d.name}</span></div></td>
                  <td><span className="pill muted" style={{ textTransform: "uppercase", fontSize: 10.5 }}>{d.type || "file"}</span></td>
                  <td style={{ color: "var(--ink-500)" }}>{d.date}</td>
                  <td style={{ color: "var(--ink-500)" }}>{d.size}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </Card>
    </div>
  );
}

function Kpi({ label, value, unit, icon, delta, deltaDir, foot, deltaNeutral, children }) {
  return (
    <div className="kpi">
      <div className="kpi-head">
        <span className="kpi-label">{label}</span>
        <span className="kpi-ic">{icon}</span>
      </div>
      <div className="kpi-value">
        {value}
        {unit && <span className="unit">{unit}</span>}
      </div>
      <div className="kpi-foot">
        {delta && (
          <span className={`delta ${deltaNeutral ? "" : deltaDir}`}>
            {!deltaNeutral && (deltaDir === "up" ? <I.ArrowUp size={11} /> : <I.ArrowDown size={11} />)}
            {delta}
          </span>
        )}
        <span>{foot}</span>
      </div>
      {children}
    </div>
  );
}

window.Dashboard = Dashboard;
