// Dashboard Kit — shared React components
// Loaded via <script type="text/babel" src="/lib/components.jsx"></script>
// REQUIRES: window.DK.theme + window.DK.utils + window.React (already loaded)
// Exposes: window.DK.components

(function () {
  const ns = (window.DK = window.DK || {});
  const T = ns.theme;

  // ── BackToHub ─────────────────────────────────────────────────────────
  // Floating back-link to / (the hub). Mount once near the top of any
  // dashboard; positioned absolute so it doesn't disturb existing layout.
  function BackToHub() {
    return (
      <a
        href="/"
        title="Zpět na hub"
        style={{
          position: "fixed",
          top: 12,
          left: 12,
          zIndex: 100,
          display: "inline-flex",
          alignItems: "center",
          gap: 6,
          padding: "6px 10px",
          background: T.CARD,
          border: `1px solid ${T.BORDER}`,
          borderRadius: 999,
          color: T.TEXT2,
          fontFamily: T.FONT_MONO,
          fontSize: 11,
          textDecoration: "none",
          letterSpacing: 1,
        }}
      >
        ← <span style={{ opacity: 0.85 }}>Hub</span>
      </a>
    );
  }

  // ── MetricCard ────────────────────────────────────────────────────────
  // KPI tile: label (uppercase mono) + big value + optional sub-line.
  // `accent` overrides value color (use theme.GREEN/RED/GOLD for status).
  function MetricCard({ label, value, sub, accent }) {
    return (
      <div style={{
        background: T.CARD,
        border: `1px solid ${T.BORDER}`,
        borderRadius: 8,
        padding: "16px 20px",
        flex: 1,
        minWidth: 180,
      }}>
        <div style={{
          color: T.TEXT2, fontSize: 11, textTransform: "uppercase",
          letterSpacing: 1.2, marginBottom: 6, fontFamily: T.FONT_MONO,
        }}>{label}</div>
        <div style={{
          color: accent || T.TEXT, fontSize: 22, fontWeight: 700,
          fontFamily: T.FONT_MONO, lineHeight: 1.2,
        }}>{value}</div>
        {sub && <div style={{
          color: T.TEXT2, fontSize: 12, marginTop: 4, fontFamily: T.FONT_MONO,
        }}>{sub}</div>}
      </div>
    );
  }

  // ── SectionTitle ──────────────────────────────────────────────────────
  // H2 with gold underline. Used to group sections within a dashboard.
  function SectionTitle({ children, color }) {
    const c = color || T.GOLD;
    return (
      <h2 style={{
        color: c, fontSize: 13, fontWeight: 600, textTransform: "uppercase",
        letterSpacing: 2, marginBottom: 12, marginTop: 28,
        fontFamily: T.FONT_MONO,
        borderBottom: `1px solid ${T.BORDER}`, paddingBottom: 8,
      }}>{children}</h2>
    );
  }

  // ── CustomTooltip ─────────────────────────────────────────────────────
  // Recharts tooltip with the dashboard theme. Drop in: <Tooltip content={<CustomTooltip />}/>
  // `valueFormat`: "auto" (default) shows raw, "percent" appends %, "fixed1" uses .toFixed(1).
  function CustomTooltip({ active, payload, label, valueFormat = "auto" }) {
    if (!active || !payload || !payload.length) return null;
    function fmtVal(v) {
      if (typeof v !== "number") return v;
      if (valueFormat === "percent") return v.toFixed(1) + "%";
      if (valueFormat === "fixed1")  return v.toFixed(1);
      return v;
    }
    return (
      <div style={{
        background: T.CARD2,
        border: `1px solid ${T.BORDER}`,
        padding: "8px 12px",
        borderRadius: 6,
        fontSize: 12,
        fontFamily: T.FONT_MONO,
      }}>
        {label && <div style={{ color: T.TEXT2, marginBottom: 4 }}>{label}</div>}
        {payload.map((p, i) => (
          <div key={i} style={{ color: p.color || T.TEXT }}>
            {p.name}: {fmtVal(p.value)}
          </div>
        ))}
      </div>
    );
  }

  // ── PieLabel ──────────────────────────────────────────────────────────
  // Recharts <Pie label={PieLabel}>. Hides slices < 4 % to avoid clutter.
  function PieLabel({ cx, cy, midAngle, outerRadius, percent, name }) {
    if (percent < 0.04) return null;
    const RADIAN = Math.PI / 180;
    const radius = outerRadius + 20;
    const x = cx + radius * Math.cos(-midAngle * RADIAN);
    const y = cy + radius * Math.sin(-midAngle * RADIAN);
    return (
      <text
        x={x} y={y}
        fill={T.TEXT2}
        textAnchor={x > cx ? "start" : "end"}
        dominantBaseline="central"
        fontSize={11}
        fontFamily={T.FONT_MONO}
      >
        {name} {(percent * 100).toFixed(0)}%
      </text>
    );
  }

  // ── useIsNarrow ───────────────────────────────────────────────────────
  // Viewport hook for the responsive table→cards switch ("mobile karty").
  function useIsNarrow(bp = 600) {
    const [narrow, setNarrow] = React.useState(window.innerWidth < bp);
    React.useEffect(() => {
      const h = () => setNarrow(window.innerWidth < bp);
      window.addEventListener("resize", h);
      return () => window.removeEventListener("resize", h);
    }, [bp]);
    return narrow;
  }

  // ── MobileCards ───────────────────────────────────────────────────────
  // Mobile replacement for wide tables: one card per row — title + main value
  // on the first line, the remaining columns folded into a mono sub-line.
  // items: array; title/value/sub: (item, i) => node; valueColor: (item, i) => color.
  function MobileCards({ items, title, value, sub, valueColor, onItem, keyFn }) {
    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 8, marginBottom: 16 }}>
        {items.map((it, i) => (
          <div key={keyFn ? keyFn(it, i) : i}
            onClick={onItem ? () => onItem(it, i) : undefined}
            style={{
              background: T.CARD, border: `1px solid ${T.BORDER}`, borderRadius: 8,
              padding: "9px 12px", cursor: onItem ? "pointer" : "default",
            }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", gap: 10 }}>
              <span style={{ fontSize: 13, fontWeight: 600 }}>{title(it, i)}</span>
              {value && <span style={{
                fontSize: 13, fontWeight: 600, fontFamily: T.FONT_MONO, whiteSpace: "nowrap",
                color: valueColor ? valueColor(it, i) : T.TEXT,
              }}>{value(it, i)}</span>}
            </div>
            {sub && <div style={{
              fontSize: 11, color: T.TEXT2, fontFamily: T.FONT_MONO, marginTop: 3, lineHeight: 1.5,
            }}>{sub(it, i)}</div>}
          </div>
        ))}
      </div>
    );
  }

  ns.components = { BackToHub, MetricCard, SectionTitle, CustomTooltip, PieLabel,
                    useIsNarrow, MobileCards };
})();
