/* stats.jsx — Štatistický prehľad helpdesku PROPLUSCO */

/* ---------- malé komponenty ---------- */
function StatCard({ label, value, suffix, delta, deltaGood, hint, icon, tone }) {
  // delta: kladné/záporné %, deltaGood: či je rast dobrý
  let deltaColor = "var(--text-3)", deltaArrow = "";
  if (delta != null && delta !== 0) {
    const dobre = deltaGood ? delta > 0 : delta < 0;
    deltaColor = dobre ? "var(--green)" : "var(--red)";
    deltaArrow = delta > 0 ? "▲" : "▼";
  }
  const toneC = tone || "var(--accent)";
  return (
    <div style={{
      background: "var(--surface)", border: "1px solid var(--stroke)", borderRadius: "var(--radius-lg)",
      padding: "16px 18px", display: "flex", flexDirection: "column", gap: 6, minWidth: 0, boxShadow: "var(--shadow-sm)",
    }}>
      <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
        <span style={{ width: 30, height: 30, borderRadius: 8, flex: "0 0 auto", display: "inline-flex", alignItems: "center", justifyContent: "center",
          background: "color-mix(in srgb, " + toneC + " 14%, transparent)", color: toneC }}><Icon name={icon} size={17} /></span>
        <span style={{ fontSize: 12.5, fontWeight: 600, color: "var(--text-2)" }}>{label}</span>
      </div>
      <div style={{ display: "flex", alignItems: "baseline", gap: 7, marginTop: 2 }}>
        <span style={{ fontSize: 30, fontWeight: 700, letterSpacing: "-.02em", fontVariantNumeric: "tabular-nums", lineHeight: 1 }}>{value}</span>
        {suffix && <span style={{ fontSize: 14, fontWeight: 600, color: "var(--text-3)" }}>{suffix}</span>}
        {delta != null && (
          <span style={{ marginLeft: "auto", fontSize: 12.5, fontWeight: 700, color: deltaColor, display: "inline-flex", alignItems: "center", gap: 3 }}>
            <span style={{ fontSize: 9 }}>{deltaArrow}</span>{Math.abs(delta)}{typeof delta === "number" && hint && hint.includes("%") ? " b." : "%"}
          </span>
        )}
      </div>
      {hint && <div style={{ fontSize: 11.5, color: "var(--text-3)" }}>{hint}</div>}
    </div>
  );
}

function Panel({ title, subtitle, right, children, span }) {
  return (
    <section style={{
      background: "var(--surface)", border: "1px solid var(--stroke)", borderRadius: "var(--radius-lg)",
      padding: "18px 20px 20px", boxShadow: "var(--shadow-sm)", gridColumn: span ? "span " + span : "auto", minWidth: 0,
      display: "flex", flexDirection: "column",
    }}>
      <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 12, marginBottom: 16 }}>
        <div>
          <h3 style={{ margin: 0, fontSize: 15, fontWeight: 700, letterSpacing: "-.01em" }}>{title}</h3>
          {subtitle && <div style={{ fontSize: 12, color: "var(--text-3)", marginTop: 2 }}>{subtitle}</div>}
        </div>
        {right}
      </div>
      {children}
    </section>
  );
}

/* ---------- trend: stĺpcový graf nové vs vyriešené ---------- */
function TrendChart({ data, rozsah, setRozsah }) {
  const W = 760, Hh = 240, padL = 34, padB = 28, padT = 12;
  const innerW = W - padL - 8, innerH = Hh - padB - padT;
  const max = Math.max(...data.map((d) => Math.max(d.nove, d.vyriesene)), 5);
  const step = innerW / data.length;
  const bw = Math.min(14, step * 0.34);
  const ticks = 4;
  const [hover, setHover] = useState(null);

  return (
    <div style={{ position: "relative" }}>
      <svg viewBox={"0 0 " + W + " " + Hh} style={{ width: "100%", height: "auto", display: "block", overflow: "visible" }}>
        {/* mriežka + osi Y */}
        {Array.from({ length: ticks + 1 }).map((_, i) => {
          const v = Math.round(max * i / ticks);
          const y = padT + innerH - (innerH * i / ticks);
          return (
            <g key={i}>
              <line x1={padL} y1={y} x2={W - 8} y2={y} stroke="var(--stroke)" strokeDasharray={i === 0 ? "0" : "3 4"} />
              <text x={padL - 8} y={y + 4} textAnchor="end" fontSize="10" fill="var(--text-3)">{v}</text>
            </g>
          );
        })}
        {data.map((d, i) => {
          const x = padL + i * step + step / 2;
          const hN = innerH * d.nove / max, hV = innerH * d.vyriesene / max;
          const yN = padT + innerH - hN, yV = padT + innerH - hV;
          const showLabel = data.length <= 14 || i % Math.ceil(data.length / 14) === 0;
          return (
            <g key={i} onMouseEnter={() => setHover(i)} onMouseLeave={() => setHover(null)} style={{ cursor: "default" }}>
              <rect x={padL + i * step} y={padT} width={step} height={innerH} fill={hover === i ? "var(--surface-3)" : "transparent"} />
              <rect x={x - bw - 1.5} y={yN} width={bw} height={hN} rx={2} fill="var(--p-stred)" opacity={0.45} />
              <rect x={x + 1.5} y={yV} width={bw} height={hV} rx={2} fill="var(--green)" />
              {showLabel && <text x={x} y={Hh - 8} textAnchor="middle" fontSize="9.5" fill="var(--text-3)">{d.label}</text>}
            </g>
          );
        })}
      </svg>
      {hover != null && (
        <div style={{ position: "absolute", top: 0, left: "50%", transform: "translateX(-50%)", display: "flex", gap: 14,
          background: "var(--surface)", border: "1px solid var(--stroke)", borderRadius: "var(--radius-sm)", boxShadow: "var(--shadow-md)",
          padding: "6px 12px", fontSize: 12, fontWeight: 600, whiteSpace: "nowrap" }}>
          <span style={{ color: "var(--text-2)" }}>{data[hover].den} {data[hover].label}</span>
          <span style={{ color: "var(--p-stred)" }}>Nové: {data[hover].nove}</span>
          <span style={{ color: "var(--green)" }}>Vyriešené: {data[hover].vyriesene}</span>
        </div>
      )}
      <div style={{ display: "flex", gap: 18, marginTop: 12, fontSize: 12.5, color: "var(--text-2)", fontWeight: 600 }}>
        <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}><span style={{ width: 11, height: 11, borderRadius: 3, background: "var(--p-stred)", opacity: .45 }} /> Nové tikety</span>
        <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}><span style={{ width: 11, height: 11, borderRadius: 3, background: "var(--green)" }} /> Vyriešené tikety</span>
      </div>
    </div>
  );
}

/* ---------- donut graf ---------- */
function Donut({ data, farby, center }) {
  const total = data.reduce((s, d) => s + d.pocet, 0) || 1;
  const R = 56, r = 36, cx = 70, cy = 70;
  let angle = -Math.PI / 2;
  const arc = (start, end) => {
    const large = end - start > Math.PI ? 1 : 0;
    const x1 = cx + R * Math.cos(start), y1 = cy + R * Math.sin(start);
    const x2 = cx + R * Math.cos(end), y2 = cy + R * Math.sin(end);
    const x3 = cx + r * Math.cos(end), y3 = cy + r * Math.sin(end);
    const x4 = cx + r * Math.cos(start), y4 = cy + r * Math.sin(start);
    return "M" + x1 + " " + y1 + " A" + R + " " + R + " 0 " + large + " 1 " + x2 + " " + y2 +
           " L" + x3 + " " + y3 + " A" + r + " " + r + " 0 " + large + " 0 " + x4 + " " + y4 + " Z";
  };
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 20, flexWrap: "wrap" }}>
      <svg viewBox="0 0 140 140" style={{ width: 134, height: 134, flex: "0 0 auto" }}>
        {data.map((d, i) => {
          const frac = d.pocet / total;
          const start = angle, end = angle + frac * Math.PI * 2;
          angle = end;
          if (d.pocet === 0) return null;
          return <path key={i} d={arc(start, end)} fill={farby[i]} stroke="var(--surface)" strokeWidth="1.5" />;
        })}
        <text x="70" y="66" textAnchor="middle" fontSize="26" fontWeight="700" fill="var(--text)">{center != null ? center : total}</text>
        <text x="70" y="82" textAnchor="middle" fontSize="10" fill="var(--text-3)">spolu</text>
      </svg>
      <div style={{ display: "flex", flexDirection: "column", gap: 7, flex: 1, minWidth: 130 }}>
        {data.map((d, i) => (
          <div key={i} style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 12.5 }}>
            <span style={{ width: 10, height: 10, borderRadius: 3, background: farby[i], flex: "0 0 auto" }} />
            <span style={{ color: "var(--text-2)", fontWeight: 600 }}>{d.kluc}</span>
            <span style={{ marginLeft: "auto", fontWeight: 700, fontVariantNumeric: "tabular-nums" }}>{d.pocet}</span>
            <span style={{ color: "var(--text-3)", fontSize: 11, width: 34, textAlign: "right" }}>{Math.round(d.pocet / total * 100)}%</span>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ---------- horizontálne pruhy ---------- */
function HBars({ data, farba }) {
  const max = Math.max(...data.map((d) => d.pocet), 1);
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
      {data.map((d, i) => (
        <div key={i} title={d.tikety && d.tikety.length ? "Zdrojové tikety: " + d.tikety.join(", ") : undefined}>
          <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12.5, marginBottom: 4 }}>
            <span style={{ fontWeight: 600, color: "var(--text-2)", display: "inline-flex", alignItems: "center", gap: 7 }}>
              {d.tema}
              {d.trend != null && d.trend !== 0 && (
                <span style={{ fontSize: 11, fontWeight: 700, color: d.trend > 0 ? "var(--p-vysoka)" : "var(--green)" }}>
                  {d.trend > 0 ? "▲" : "▼"}{Math.abs(d.trend)}
                </span>
              )}
            </span>
            <span style={{ fontWeight: 700, fontVariantNumeric: "tabular-nums" }}>{d.pocet}</span>
          </div>
          <div style={{ height: 8, borderRadius: 5, background: "var(--surface-3)", overflow: "hidden" }}>
            <div style={{ height: "100%", width: (d.pocet / max * 100) + "%", borderRadius: 5,
              background: farba || "var(--accent)" }} />
          </div>
        </div>
      ))}
    </div>
  );
}

/* ---------- SLA gauge (polkruh) ---------- */
function SlaGauge({ percent, prev }) {
  const R = 70, cx = 90, cy = 88, sw = 16;
  // uhly v stupňoch: 180° = vľavo, 270° = hore (vrchol), 360° = vpravo — polkruh cez vrch
  const pt = (deg) => {
    const rad = (deg * Math.PI) / 180;
    return [cx + R * Math.cos(rad), cy + R * Math.sin(rad)];
  };
  const [sx, sy] = pt(180), [ex, ey] = pt(360);
  const angDeg = 180 + Math.max(0, Math.min(100, percent)) * 1.8;
  const [fx, fy] = pt(angDeg);
  const largeArc = angDeg - 180 > 180 ? 1 : 0;
  const farba = percent >= 90 ? "var(--green)" : percent >= 80 ? "var(--p-vysoka)" : "var(--red)";
  const delta = percent - prev;
  return (
    <div style={{ display: "flex", flexDirection: "column", alignItems: "center" }}>
      <svg viewBox="0 0 180 110" style={{ width: 200, height: 122 }}>
        <path d={"M" + sx + " " + sy + " A" + R + " " + R + " 0 0 1 " + ex + " " + ey} fill="none" stroke="var(--surface-3)" strokeWidth={sw} strokeLinecap="round" />
        <path d={"M" + sx + " " + sy + " A" + R + " " + R + " 0 " + largeArc + " 1 " + fx + " " + fy} fill="none" stroke={farba} strokeWidth={sw} strokeLinecap="round" />
        <text x="90" y="80" textAnchor="middle" fontSize="34" fontWeight="700" fill="var(--text)">{percent}<tspan fontSize="18" fill="var(--text-3)">%</tspan></text>
      </svg>
      <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: -6 }}>
        <span style={{ fontSize: 12.5, color: "var(--text-2)", fontWeight: 600 }}>v termíne</span>
        <span style={{ fontSize: 12, fontWeight: 700, color: delta >= 0 ? "var(--green)" : "var(--red)" }}>{delta >= 0 ? "▲" : "▼"} {Math.abs(delta)} b. vs minulý mes.</span>
      </div>
    </div>
  );
}

/* ---------- vek formátovač ---------- */
function fmtVek(ms) {
  const h = Math.floor(ms / 3600000);
  if (h < 24) return h + " h";
  const d = Math.floor(h / 24);
  return d + " d " + (h % 24) + " h";
}

/* ====================== HLAVNÝ ŠTATISTICKÝ SCREEN ====================== */
function StatsScreen() {
  const S = window.HELPDESK_STATS;
  const [obdobie, setObdobie] = useState("30 dní");
  const trendData = obdobie === "7 dní" ? S.trend.slice(-7) : obdobie === "14 dní" ? S.trend.slice(-14) : S.trend;

  const pctDelta = (cur, prev) => prev ? Math.round((cur - prev) / prev * 100) : 0;

  const stavFarby = S.podlaStavu.map((d) => STAV_FARBA[d.kluc]);
  const prioFarby = S.podlaPriority.map((d) => PRIO_FARBA[d.kluc]);
  const katFarby = ["var(--accent)", "var(--p-stred)", "var(--c-caka)", "var(--c-prirad)"];

  return (
    <div style={{ height: "100%", overflowY: "auto", background: "var(--bg)" }}>
      <div style={{ maxWidth: 1320, margin: "0 auto", padding: "24px 28px 48px" }}>
        {/* hlavička */}
        <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 16, marginBottom: 22, flexWrap: "wrap" }}>
          <div>
            <h1 style={{ margin: 0, fontSize: 24, fontWeight: 700, letterSpacing: "-.02em" }}>Štatistika a prehľad</h1>
            <div style={{ fontSize: 13, color: "var(--text-2)", marginTop: 4 }}>Výkonnosť helpdesku PROPLUSCO · aktualizované {new Date(S.now).toLocaleString("sk-SK", { day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit" })}</div>
          </div>
          <div style={{ display: "flex", gap: 6, background: "var(--surface)", border: "1px solid var(--stroke)", borderRadius: 999, padding: 3 }}>
            {["7 dní", "14 dní", "30 dní"].map((o) => (
              <button key={o} onClick={() => setObdobie(o)} style={{
                padding: "6px 14px", borderRadius: 999, border: "none", fontSize: 12.5, fontWeight: 600,
                background: obdobie === o ? "var(--accent)" : "transparent", color: obdobie === o ? "#fff" : "var(--text-2)",
              }}>{o}</button>
            ))}
          </div>
        </div>

        {/* KPI riadok */}
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(180px, 1fr))", gap: 14, marginBottom: 18 }}>
          <StatCard label="Otvorené tikety" value={S.otvorene} icon="mail" tone="var(--accent)" hint="práve teraz v rieš." />
          <StatCard label="Vyriešené (7 dní)" value={S.vyriesene7} icon="checkCircle" tone="var(--green)" delta={pctDelta(S.vyriesene7, S.vyriesenePrev7)} deltaGood={true} hint="vs predch. týždeň" />
          <StatCard label="Priem. čas riešenia" value={S.mttrHod} suffix="h" icon="clock" tone="var(--c-riesi)" delta={pctDelta(S.mttrHod, S.mttrPrev)} deltaGood={false} hint="MTTR · vs min. mesiac" />
          <StatCard label="Čas prvej odpovede" value={S.frtHod} suffix="h" icon="send" tone="var(--p-stred)" delta={pctDelta(S.frtHod, S.frtPrev)} deltaGood={false} hint="FRT · vs min. mesiac" />
          <StatCard label="Eskalované" value={S.eskalovane} icon="warning" tone="var(--red)" hint="po termíne SLA" />
        </div>

        {/* trend + SLA */}
        <div style={{ display: "grid", gridTemplateColumns: "minmax(0,2.4fr) minmax(0,1fr)", gap: 16, marginBottom: 16 }} className="hd-stats-2col">
          <Panel title="Vývoj objemu tiketov" subtitle={"Nové vs. vyriešené · posledných " + obdobie}>
            <TrendChart data={trendData} />
          </Panel>
          <Panel title="Plnenie SLA" subtitle="Vyriešené v rámci termínu">
            <div style={{ display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", flex: 1, gap: 14 }}>
              <SlaGauge percent={S.slaSplnene} prev={S.slaPrev} />
              <div style={{ display: "flex", gap: 10, width: "100%" }}>
                <div style={{ flex: 1, textAlign: "center", padding: "10px 8px", borderRadius: "var(--radius)", background: "var(--surface-2)", border: "1px solid var(--stroke)" }}>
                  <div style={{ fontSize: 20, fontWeight: 700, color: "var(--green)" }}>{S.vyriesene30 - S.slaPorusene30}</div>
                  <div style={{ fontSize: 11, color: "var(--text-3)", marginTop: 2 }}>v termíne</div>
                </div>
                <div style={{ flex: 1, textAlign: "center", padding: "10px 8px", borderRadius: "var(--radius)", background: "var(--surface-2)", border: "1px solid var(--stroke)" }}>
                  <div style={{ fontSize: 20, fontWeight: 700, color: "var(--red)" }}>{S.slaPorusene30}</div>
                  <div style={{ fontSize: 11, color: "var(--text-3)", marginTop: 2 }}>po termíne</div>
                </div>
              </div>
            </div>
          </Panel>
        </div>

        {/* tri donuty / bary */}
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(280px, 1fr))", gap: 16, marginBottom: 16 }}>
          <Panel title="Podľa stavu"><Donut data={S.podlaStavu.filter((d) => d.pocet > 0)} farby={S.podlaStavu.filter((d) => d.pocet > 0).map((d) => STAV_FARBA[d.kluc])} center={S.podlaStavu.reduce((s, d) => s + d.pocet, 0)} /></Panel>
          <Panel title="Podľa priority"><Donut data={S.podlaPriority} farby={prioFarby} /></Panel>
          <Panel title="Podľa kategórie"><Donut data={S.podlaKategorie} farby={katFarby} /></Panel>
        </div>

        {/* najdlhšie otvorené + témy */}
        <div style={{ display: "grid", gridTemplateColumns: "minmax(0,1.5fr) minmax(0,1fr)", gap: 16, marginBottom: 16 }} className="hd-stats-2col">
          <Panel title="Najdlhšie otvorené tikety" subtitle="Vyžadujú pozornosť — zoradené podľa veku">
            <div style={{ display: "flex", flexDirection: "column" }}>
              <div style={{ display: "grid", gridTemplateColumns: "76px 1fr 110px 84px", gap: 10, padding: "0 4px 8px", fontSize: 11, fontWeight: 700, color: "var(--text-3)", textTransform: "uppercase", letterSpacing: ".4px", borderBottom: "1px solid var(--stroke)" }}>
                <span>Tiket</span><span>Predmet</span><span>Priorita</span><span style={{ textAlign: "right" }}>Vek</span>
              </div>
              {S.najdlhsie.map((t) => (
                <div key={t.cislo} style={{ display: "grid", gridTemplateColumns: "76px 1fr 110px 84px", gap: 10, alignItems: "center", padding: "11px 4px", borderBottom: "1px solid var(--stroke)", fontSize: 13 }}>
                  <span style={{ fontWeight: 700, color: "var(--accent)", fontVariantNumeric: "tabular-nums", fontSize: 12 }}>{t.cislo}</span>
                  <span style={{ fontWeight: 600, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", display: "flex", alignItems: "center", gap: 6 }}>
                    {t.eskalovany && <span style={{ color: "var(--red)", display: "inline-flex", flex: "0 0 auto" }}><Icon name="warning" size={13} /></span>}
                    {t.predmet}
                  </span>
                  <span><PriorityBadge priorita={t.priorita} small /></span>
                  <span style={{ textAlign: "right", fontWeight: 700, fontVariantNumeric: "tabular-nums", color: t.poTermine ? "var(--red)" : "var(--text-2)" }}>{fmtVek(t.vek)}</span>
                </div>
              ))}
            </div>
          </Panel>
          <Panel title="Najčastejšie témy" subtitle="Odvodené z poľa „Téma“ na tiketoch · hover pre zdrojové tikety">
            <HBars data={S.temy} farba="var(--accent)" />
          </Panel>
        </div>

        {/* výkon technikov */}
        <Panel title="Výkon technikov" subtitle="Vyriešené tikety, priemerný čas riešenia a plnenie SLA za 30 dní">
          <div style={{ display: "grid", gridTemplateColumns: "1fr 90px 110px 1fr", gap: 12, padding: "0 4px 10px", fontSize: 11, fontWeight: 700, color: "var(--text-3)", textTransform: "uppercase", letterSpacing: ".4px", borderBottom: "1px solid var(--stroke)" }} className="hd-tech-head">
            <span>Technik</span><span style={{ textAlign: "right" }}>Vyriešené</span><span style={{ textAlign: "right" }}>Priem. čas</span><span>Plnenie SLA</span>
          </div>
          {S.technikVykon.map((u, i) => (
            <div key={u.id} style={{ display: "grid", gridTemplateColumns: "1fr 90px 110px 1fr", gap: 12, alignItems: "center", padding: "13px 4px", borderBottom: i < S.technikVykon.length - 1 ? "1px solid var(--stroke)" : "none" }} className="hd-tech-row">
              <div style={{ display: "flex", alignItems: "center", gap: 11, minWidth: 0 }}>
                <Avatar meno={u.meno} farba={u.farba} size={34} />
                <div style={{ minWidth: 0 }}>
                  <div style={{ fontWeight: 700, fontSize: 13.5, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{u.meno}</div>
                  <div style={{ fontSize: 11.5, color: "var(--text-3)" }}>{u.rola === "Admin" ? "Administrátor" : "Technik"} · {u.otvorene} otvorených</div>
                </div>
              </div>
              <span style={{ textAlign: "right", fontWeight: 700, fontSize: 16, fontVariantNumeric: "tabular-nums" }}>{u.vyriesene}</span>
              <span style={{ textAlign: "right", fontWeight: 600, fontVariantNumeric: "tabular-nums", color: "var(--text-2)" }}>{u.mttr.toFixed(1)} h</span>
              <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                <div style={{ flex: 1, height: 8, borderRadius: 5, background: "var(--surface-3)", overflow: "hidden" }}>
                  <div style={{ height: "100%", width: u.sla + "%", borderRadius: 5, background: u.sla >= 90 ? "var(--green)" : u.sla >= 80 ? "var(--p-vysoka)" : "var(--red)" }} />
                </div>
                <span style={{ fontWeight: 700, fontSize: 13, fontVariantNumeric: "tabular-nums", width: 38, textAlign: "right", color: u.sla >= 90 ? "var(--green)" : "var(--text)" }}>{u.sla}%</span>
              </div>
            </div>
          ))}
        </Panel>
      </div>
    </div>
  );
}

window.StatsScreen = StatsScreen;
