// Professional minimalist UI components — Tormentas
const { useState: useStP, useEffect: useEffP, useRef: useRefP } = React;

const T = {
  // Core
  bg:       "#f8fafc",
  card:     "#ffffff",
  sidebar:  "#0f172a",
  sidebarHover: "#1e293b",
  sidebarActive: "#1e293b",

  // Text
  text:     "#0f172a",
  muted:    "#64748b",
  subtle:   "#94a3b8",
  inverse:  "#ffffff",
  inverseMuted: "#94a3b8",

  // Borders
  border:   "#e2e8f0",
  borderMd: "#cbd5e1",

  // Accent (single blue)
  accent:   "#2563eb",
  accentLt: "#eff6ff",
  accentMd: "#bfdbfe",

  // Semantic
  green:  "#16a34a",
  greenLt:"#f0fdf4",
  red:    "#dc2626",
  redLt:  "#fef2f2",
  yellow: "#d97706",
  yellowLt:"#fffbeb",

  // Stripe
  stripe: "#f8fafc",
};

// ── Avatar ───────────────────────────────────────────────
function PAvatar({ initials, color, size = 36, style = {} }) {
  // Desaturate colors for professional look
  return (
    <div style={{
      width: size, height: size, borderRadius: "50%",
      background: `${color}22`,
      border: `1.5px solid ${color}44`,
      display: "flex", alignItems: "center", justifyContent: "center",
      color: color, fontWeight: 700, fontSize: size * 0.33, flexShrink: 0,
      letterSpacing: "-0.01em",
      ...style
    }}>{initials}</div>
  );
}

// ── Card ────────────────────────────────────────────────
function PCard({ children, style = {}, onClick, padding = "24px" }) {
  return (
    <div onClick={onClick} style={{
      background: T.card, borderRadius: 8,
      border: `1px solid ${T.border}`,
      padding,
      cursor: onClick ? "pointer" : "default",
      transition: onClick ? "border-color 0.15s" : "none",
      ...style
    }}
    onMouseEnter={e => { if (onClick) e.currentTarget.style.borderColor = T.accent + "60"; }}
    onMouseLeave={e => { if (onClick) e.currentTarget.style.borderColor = T.border; }}
    >{children}</div>
  );
}

// ── KPI Card ────────────────────────────────────────────
function PKPICard({ label, value, delta, color = T.text, sub }) {
  return (
    <PCard>
      <div style={{ fontSize: 11, fontWeight: 600, color: T.muted, textTransform: "uppercase", letterSpacing: "0.08em", marginBottom: 10 }}>{label}</div>
      <div style={{ fontSize: 30, fontWeight: 800, color, letterSpacing: "-0.03em", lineHeight: 1 }}>{value}</div>
      {sub && <div style={{ fontSize: 12, color: T.muted, marginTop: 8 }}>{sub}</div>}
    </PCard>
  );
}

// ── Section Label ────────────────────────────────────────
function PLabel({ children }) {
  return (
    <div style={{ fontSize: 11, fontWeight: 700, color: T.muted, textTransform: "uppercase", letterSpacing: "0.08em", marginBottom: 12 }}>
      {children}
    </div>
  );
}

// ── Section Header ───────────────────────────────────────
function PSectionHeader({ title, action, onAction }) {
  return (
    <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 16 }}>
      <PLabel>{title}</PLabel>
      {action && (
        <button onClick={onAction} style={{
          background: "none", border: "none", color: T.accent,
          fontSize: 12, fontWeight: 600, cursor: "pointer", fontFamily: "inherit", padding: 0
        }}>{action}</button>
      )}
    </div>
  );
}

// ── Badge ────────────────────────────────────────────────
function PBadge({ text, color = T.accent, variant = "default" }) {
  if (variant === "pill") return (
    <span style={{
      background: `${color}14`, color,
      borderRadius: 4, padding: "2px 8px",
      fontSize: 11, fontWeight: 600, display: "inline-block"
    }}>{text}</span>
  );
  return (
    <span style={{
      border: `1px solid ${T.border}`,
      color: T.muted, borderRadius: 4,
      padding: "1px 7px", fontSize: 11, fontWeight: 500, display: "inline-block"
    }}>{text}</span>
  );
}

// ── Table ────────────────────────────────────────────────
function PTable({ columns, rows, onRowClick }) {
  const [hovered, setHovered] = React.useState(null);
  return (
    <div style={{ overflowX: "auto" }}>
      <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 13 }}>
        <thead>
          <tr>
            {columns.map(col => (
              <th key={col.key} style={{
                padding: "9px 16px",
                textAlign: col.right ? "right" : "left",
                color: T.muted, fontWeight: 600, fontSize: 11,
                textTransform: "uppercase", letterSpacing: "0.06em",
                borderBottom: `2px solid ${T.border}`,
                whiteSpace: "nowrap", background: T.stripe
              }}>{col.label}</th>
            ))}
          </tr>
        </thead>
        <tbody>
          {rows.map((row, ri) => (
            <tr key={ri}
              onClick={() => onRowClick && onRowClick(row)}
              onMouseEnter={() => setHovered(ri)}
              onMouseLeave={() => setHovered(null)}
              style={{
                background: hovered === ri && onRowClick ? "#f1f5f9" : ri % 2 === 1 ? T.stripe : "#fff",
                cursor: onRowClick ? "pointer" : "default",
                transition: "background 0.1s"
              }}
            >
              {columns.map(col => (
                <td key={col.key} style={{
                  padding: "11px 16px",
                  borderBottom: `1px solid ${T.border}`,
                  textAlign: col.right ? "right" : "left",
                  fontWeight: col.bold ? 700 : 400,
                  color: col.color || T.text,
                  fontSize: 13
                }}>
                  {row[col.key]}
                </td>
              ))}
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

// ── Progress ─────────────────────────────────────────────
function PProgress({ value, max = 100, color = T.accent, height = 4 }) {
  const pct = Math.min(100, Math.round((value / max) * 100));
  return (
    <div style={{ background: T.border, borderRadius: 99, height, overflow: "hidden" }}>
      <div style={{ width: `${pct}%`, height: "100%", background: color, borderRadius: 99, transition: "width 0.5s ease" }} />
    </div>
  );
}

// ── Back Button ──────────────────────────────────────────
function PBackBtn({ onClick, label = "Atrás" }) {
  return (
    <button onClick={onClick} style={{
      background: "none", border: "none",
      color: T.accent, fontWeight: 600, fontSize: 13,
      cursor: "pointer", fontFamily: "inherit",
      padding: "0 0 20px 0", display: "flex", alignItems: "center", gap: 6
    }}>
      <span style={{ fontSize: 16 }}>←</span> {label}
    </button>
  );
}

// ── Divider ──────────────────────────────────────────────
function PDivider() {
  return <div style={{ height: 1, background: T.border, margin: "16px 0" }} />;
}

// ── Tab Bar ──────────────────────────────────────────────
function PTabBar({ tabs, active, onChange }) {
  return (
    <div style={{ display: "flex", gap: 0, borderBottom: `1px solid ${T.border}`, marginBottom: 24 }}>
      {tabs.map(([id, label]) => (
        <button key={id} onClick={() => onChange(id)} style={{
          padding: "10px 20px", border: "none", background: "none",
          fontSize: 13, fontWeight: active === id ? 600 : 400,
          color: active === id ? T.text : T.muted,
          cursor: "pointer", fontFamily: "inherit",
          borderBottom: `2px solid ${active === id ? T.accent : "transparent"}`,
          marginBottom: -1, transition: "all 0.15s"
        }}>{label}</button>
      ))}
    </div>
  );
}

// ── Line Chart ───────────────────────────────────────────
function PLineChart({ data, labels, color = T.accent, height = 120 }) {
  const ref = useRefP(null);
  useEffP(() => {
    const canvas = ref.current; if (!canvas) return;
    const dpr = window.devicePixelRatio || 1;
    const W = canvas.offsetWidth * dpr, H = height * dpr;
    canvas.width = W; canvas.height = H;
    const ctx = canvas.getContext("2d");
    ctx.scale(dpr, dpr);
    const cW = canvas.offsetWidth, cH = height;
    const pad = { top: 20, right: 16, bottom: 32, left: 36 };
    const iW = cW - pad.left - pad.right, iH = cH - pad.top - pad.bottom;
    const max = Math.max(...data, 1), n = data.length;
    const xOf = i => pad.left + (i / (n - 1)) * iW;
    const yOf = v => pad.top + iH - (v / max) * iH;

    // Grid
    [0, Math.ceil(max / 2), max].forEach(v => {
      const y = yOf(v);
      ctx.strokeStyle = T.border; ctx.lineWidth = 1;
      ctx.beginPath(); ctx.moveTo(pad.left, y); ctx.lineTo(cW - pad.right, y); ctx.stroke();
      ctx.fillStyle = T.muted; ctx.font = `11px DM Sans, sans-serif`;
      ctx.textAlign = "right"; ctx.fillText(v, pad.left - 6, y + 4);
    });

    // Fill
    const g = ctx.createLinearGradient(0, pad.top, 0, cH - pad.bottom);
    g.addColorStop(0, color + "28"); g.addColorStop(1, color + "00");
    ctx.beginPath();
    data.forEach((v, i) => i === 0 ? ctx.moveTo(xOf(i), yOf(v)) : ctx.lineTo(xOf(i), yOf(v)));
    ctx.lineTo(xOf(n - 1), yOf(0)); ctx.lineTo(xOf(0), yOf(0));
    ctx.closePath(); ctx.fillStyle = g; ctx.fill();

    // Line
    ctx.beginPath();
    data.forEach((v, i) => i === 0 ? ctx.moveTo(xOf(i), yOf(v)) : ctx.lineTo(xOf(i), yOf(v)));
    ctx.strokeStyle = color; ctx.lineWidth = 2; ctx.lineJoin = "round"; ctx.stroke();

    // Dots
    data.forEach((v, i) => {
      ctx.beginPath(); ctx.arc(xOf(i), yOf(v), 3.5, 0, Math.PI * 2);
      ctx.fillStyle = "#fff"; ctx.fill();
      ctx.strokeStyle = color; ctx.lineWidth = 2; ctx.stroke();
      ctx.fillStyle = T.muted; ctx.font = `10px DM Sans, sans-serif`;
      ctx.textAlign = "center"; ctx.fillText(labels[i], xOf(i), cH - 8);
    });
  }, [data, color, height]);
  return <canvas ref={ref} style={{ width: "100%", height, display: "block" }} />;
}

// ── Bar Chart ────────────────────────────────────────────
function PBarChart({ data, labels, color = T.accent, height = 100 }) {
  const ref = useRefP(null);
  useEffP(() => {
    const canvas = ref.current; if (!canvas) return;
    const dpr = window.devicePixelRatio || 1;
    canvas.width = canvas.offsetWidth * dpr;
    canvas.height = height * dpr;
    const ctx = canvas.getContext("2d");
    ctx.scale(dpr, dpr);
    const cW = canvas.offsetWidth, cH = height;
    const pad = { top: 16, right: 8, bottom: 28, left: 8 };
    const iW = cW - pad.left - pad.right, iH = cH - pad.top - pad.bottom;
    const max = Math.max(...data, 1), n = data.length;
    const gap = iW / n, bw = gap * 0.5;

    data.forEach((v, i) => {
      const x = pad.left + gap * i + (gap - bw) / 2;
      const bh = (v / max) * iH, y = pad.top + iH - bh;
      const col = Array.isArray(color) ? color[i % color.length] : color;
      ctx.fillStyle = col + "cc";
      ctx.beginPath(); ctx.roundRect(x, y, bw, bh, [3, 3, 0, 0]); ctx.fill();
      ctx.fillStyle = T.muted; ctx.font = `10px DM Sans, sans-serif`; ctx.textAlign = "center";
      ctx.fillText(labels[i], x + bw / 2, cH - 8);
      ctx.fillStyle = col; ctx.font = `bold 10px DM Sans, sans-serif`;
      if (v > 0) ctx.fillText(v, x + bw / 2, y - 4);
    });
  }, [data, color, height]);
  return <canvas ref={ref} style={{ width: "100%", height, display: "block" }} />;
}

// Pos colors — muted, professional
const posColorsP = {
  "Base":      "#2563eb",
  "Escolta":   "#7c3aed",
  "Alero":     "#0891b2",
  "Ala-Pívot": "#059669",
  "Pívot":     "#d97706",
};

Object.assign(window, {
  T, posColorsP,
  PAvatar, PCard, PKPICard, PLabel, PSectionHeader,
  PBadge, PTable, PProgress, PBackBtn, PDivider, PTabBar,
  PLineChart, PBarChart
});
