/* FrontCall Hub — UI kit primitives (self-contained mirror of the design-system
   components, adapted to browser-global Babel). Reads the real token CSS vars. */

function Icon({ name, size = 20, color = "currentColor", strokeWidth = 2, style = {} }) {
  const inner = (window.FCIcons && window.FCIcons[name]) || "";
  return (
    <svg
      width={size}
      height={size}
      viewBox="0 0 24 24"
      fill="none"
      stroke={color}
      strokeWidth={strokeWidth}
      strokeLinecap="round"
      strokeLinejoin="round"
      style={{ display: "block", flexShrink: 0, ...style }}
      dangerouslySetInnerHTML={{ __html: inner }}
    />
  );
}

function Button({ children, variant = "primary", size = "md", block, pill, disabled, iconLeft, iconRight, onClick, style = {} }) {
  const sizes = {
    sm: { height: 36, padding: "0 14px", fontSize: "var(--fs-sm)", gap: 6 },
    md: { height: 44, padding: "0 18px", fontSize: "var(--fs-body)", gap: 8 },
    lg: { height: 52, padding: "0 24px", fontSize: "var(--fs-body-lg)", gap: 10 },
  };
  const variants = {
    primary: { background: "var(--brand)", color: "#fff", border: "1px solid transparent", boxShadow: "var(--shadow-brand)" },
    secondary: { background: "var(--surface-card)", color: "var(--text-strong)", border: "1px solid var(--border-default)" },
    ghost: { background: "transparent", color: "var(--text-strong)", border: "1px solid transparent" },
    danger: { background: "var(--danger-500)", color: "#fff", border: "1px solid transparent" },
  };
  const hoverBg = { primary: "var(--brand-hover)", secondary: "var(--surface-hover)", ghost: "var(--surface-hover)", danger: "var(--danger-600)" }[variant];
  return (
    <button
      type="button" disabled={disabled} onClick={onClick}
      onMouseEnter={(e) => { if (!disabled) e.currentTarget.style.background = hoverBg; }}
      onMouseLeave={(e) => { if (!disabled) { e.currentTarget.style.background = variants[variant].background; } e.currentTarget.style.transform = "scale(1)"; }}
      onMouseDown={(e) => { if (!disabled) e.currentTarget.style.transform = "scale(0.98)"; }}
      onMouseUp={(e) => { e.currentTarget.style.transform = "scale(1)"; }}
      style={{
        display: block ? "flex" : "inline-flex", width: block ? "100%" : undefined,
        alignItems: "center", justifyContent: "center", fontFamily: "var(--font-sans)",
        fontWeight: "var(--fw-semibold)", letterSpacing: "var(--ls-snug)",
        borderRadius: pill ? "var(--radius-full)" : "var(--radius-md)",
        cursor: disabled ? "not-allowed" : "pointer", opacity: disabled ? 0.5 : 1,
        transition: "background var(--dur-fast) var(--ease-standard), transform var(--dur-fast) var(--ease-standard)",
        whiteSpace: "nowrap", ...sizes[size], ...variants[variant], ...style,
      }}
    >
      {iconLeft}{children}{iconRight}
    </button>
  );
}

function Card({ children, interactive, inset, onClick, style = {} }) {
  const [hover, setHover] = React.useState(false);
  return (
    <div
      onClick={onClick}
      onMouseEnter={interactive ? () => setHover(true) : undefined}
      onMouseLeave={interactive ? () => setHover(false) : undefined}
      style={{
        background: "var(--surface-card)", border: "1px solid var(--border-subtle)",
        borderRadius: "var(--radius-lg)", boxShadow: hover ? "var(--shadow-md)" : "var(--shadow-sm)",
        padding: inset ? 0 : "var(--space-5)",
        transition: "box-shadow var(--dur-base) var(--ease-standard), transform var(--dur-base) var(--ease-standard)",
        transform: hover ? "translateY(-2px)" : "none", cursor: interactive ? "pointer" : "default", ...style,
      }}
    >{children}</div>
  );
}

function Badge({ children, tone = "neutral", solid, dot, style = {} }) {
  const tones = {
    neutral: { fg: "var(--gray-600)", bg: "var(--gray-100)", solidBg: "var(--gray-600)" },
    brand: { fg: "var(--blue-700)", bg: "var(--blue-50)", solidBg: "var(--blue-500)" },
    success: { fg: "var(--success-600)", bg: "var(--success-bg)", solidBg: "var(--success-500)" },
    danger: { fg: "var(--danger-600)", bg: "var(--danger-bg)", solidBg: "var(--danger-500)" },
    warning: { fg: "var(--warning-500)", bg: "var(--warning-bg)", solidBg: "var(--warning-500)" },
    info: { fg: "var(--info-500)", bg: "var(--info-bg)", solidBg: "var(--info-500)" },
  };
  const t = tones[tone] || tones.neutral;
  return (
    <span style={{
      display: "inline-flex", alignItems: "center", gap: 6, fontFamily: "var(--font-sans)",
      fontSize: "var(--fs-caption)", fontWeight: "var(--fw-semibold)", lineHeight: 1,
      padding: "5px 10px", borderRadius: "var(--radius-full)",
      color: solid ? "#fff" : t.fg, background: solid ? t.solidBg : t.bg, ...style,
    }}>
      {dot && <span style={{ width: 7, height: 7, borderRadius: "var(--radius-full)", background: solid ? "#fff" : t.solidBg }} />}
      {children}
    </span>
  );
}

function LeadQualityBadge({ quality = "warm", size = "md", showIcon = true, style = {} }) {
  const map = {
    hot: { label: "Quente", bg: "var(--hot-500)", flame: true },
    warm: { label: "Morno", bg: "var(--warm-500)" },
    cold: { label: "Frio", bg: "var(--cold-500)" },
    unqualified: { label: "Não-qual.", bg: "var(--neutral-500)" },
  };
  const q = map[quality] || map.warm;
  const sizes = { sm: { fontSize: "var(--fs-micro)", padding: "3px 9px" }, md: { fontSize: "var(--fs-caption)", padding: "5px 11px" }, lg: { fontSize: "var(--fs-sm)", padding: "7px 14px" } };
  return (
    <span style={{
      display: "inline-flex", alignItems: "center", gap: 5, fontFamily: "var(--font-sans)",
      fontWeight: "var(--fw-bold)", letterSpacing: "var(--ls-snug)", lineHeight: 1,
      borderRadius: "var(--radius-full)", color: "#fff", background: q.bg, ...sizes[size], ...style,
    }}>
      {showIcon && q.flame ? <Icon name="flame" size={13} color="#fff" /> : null}
      {q.label}
    </span>
  );
}

function WaveBars({ active, size = 22, color = "var(--brand)", bars = 5, style = {} }) {
  const heights = [0.45, 0.75, 1, 0.75, 0.45];
  const barW = Math.max(2, Math.round(size * 0.12));
  const gap = Math.max(2, Math.round(size * 0.09));
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap, height: size, ...style }}>
      {Array.from({ length: bars }).map((_, i) => (
        <span key={i} className={active ? "fc-wave-bar" : ""} style={{
          width: barW, height: Math.round(size * heights[i % heights.length]),
          background: color, borderRadius: "var(--radius-full)", transformOrigin: "center",
          animation: active ? `fc-wave 900ms var(--ease-standard) ${i * 110}ms infinite` : "none",
        }} />
      ))}
    </span>
  );
}

function Avatar({ name = "", src, size = 40, style = {} }) {
  const initials = name.trim().split(/\s+/).slice(0, 2).map((w) => w[0]).join("").toUpperCase() || "?";
  const palette = [["var(--blue-100)", "var(--blue-700)"], ["var(--success-bg)", "var(--success-600)"], ["var(--warm-bg)", "var(--warm-600)"], ["var(--cold-bg)", "var(--cold-500)"], ["var(--gray-200)", "var(--gray-700)"]];
  let h = 0; for (let i = 0; i < name.length; i++) h = (h * 31 + name.charCodeAt(i)) >>> 0;
  const [bg, fg] = palette[h % palette.length];
  return (
    <span style={{
      display: "inline-flex", alignItems: "center", justifyContent: "center", flex: "none",
      width: size, height: size, borderRadius: "var(--radius-full)", overflow: "hidden",
      fontFamily: "var(--font-sans)", fontWeight: "var(--fw-semibold)", fontSize: size * 0.4,
      letterSpacing: "var(--ls-snug)", background: bg, color: fg, ...style,
    }}>{initials}</span>
  );
}

function SegmentedTabs({ items = [], value, onChange, size = "md", scroll, style = {} }) {
  const sizes = { sm: { fontSize: "var(--fs-caption)", padding: "6px 12px" }, md: { fontSize: "var(--fs-sm)", padding: "9px 16px" } };
  return (
    <div style={{
      display: scroll ? "flex" : "inline-flex", gap: 4, padding: 4, background: "var(--surface-sunken)",
      borderRadius: "var(--radius-full)", overflowX: scroll ? "auto" : undefined,
      WebkitOverflowScrolling: "touch", scrollbarWidth: "none", ...style,
    }}>
      {items.map((it) => {
        const key = typeof it === "string" ? it : it.value;
        const label = typeof it === "string" ? it : it.label;
        const count = typeof it === "object" ? it.count : undefined;
        const active = key === value;
        return (
          <button key={key} onClick={() => onChange && onChange(key)} style={{
            border: "none", cursor: "pointer", fontFamily: "var(--font-sans)", fontWeight: "var(--fw-semibold)",
            borderRadius: "var(--radius-full)", whiteSpace: "nowrap", display: "inline-flex", alignItems: "center", gap: 6,
            transition: "background var(--dur-fast), color var(--dur-fast)",
            background: active ? "var(--surface-card)" : "transparent", color: active ? "var(--text-strong)" : "var(--text-secondary)",
            boxShadow: active ? "var(--shadow-xs)" : "none", flex: "none", ...sizes[size],
          }}>
            {label}
            {count != null && <span style={{ fontSize: "var(--fs-micro)", fontWeight: "var(--fw-bold)", background: active ? "var(--brand-subtle)" : "var(--gray-200)", color: active ? "var(--brand)" : "var(--text-muted)", borderRadius: "var(--radius-full)", padding: "1px 7px" }}>{count}</span>}
          </button>
        );
      })}
    </div>
  );
}

function StatTile({ label, value, unit = "", delta, deltaTone = "success", icon, style = {} }) {
  const deltaColors = { success: "var(--success-600)", danger: "var(--danger-600)", neutral: "var(--text-muted)" };
  return (
    <div style={{
      background: "var(--surface-card)", border: "1px solid var(--border-subtle)", borderRadius: "var(--radius-lg)",
      boxShadow: "var(--shadow-sm)", padding: "var(--space-4) var(--space-5)", display: "flex", flexDirection: "column", gap: 8, ...style,
    }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8 }}>
        <span style={{ fontSize: "var(--fs-micro)", fontWeight: "var(--fw-bold)", letterSpacing: "var(--ls-eyebrow)", textTransform: "uppercase", color: "var(--text-muted)" }}>{label}</span>
        {icon}
      </div>
      <div style={{ display: "flex", alignItems: "baseline", gap: 8, flexWrap: "wrap" }}>
        <span style={{ fontSize: 30, fontWeight: "var(--fw-bold)", letterSpacing: "var(--ls-tight)", color: "var(--text-strong)", lineHeight: 1 }}>
          {unit && <span style={{ color: "var(--brand)" }}>{unit}</span>}{value}
        </span>
        {delta != null && <span style={{ fontSize: "var(--fs-sm)", fontWeight: "var(--fw-semibold)", color: deltaColors[deltaTone] }}>{delta}</span>}
      </div>
    </div>
  );
}

function EmptyState({ title, description, art, action, style = {} }) {
  return (
    <div style={{ display: "flex", flexDirection: "column", alignItems: "center", textAlign: "center", gap: 12, padding: "var(--space-10) var(--space-6)", ...style }}>
      <div style={{ width: 72, height: 72, borderRadius: "var(--radius-full)", background: "var(--surface-brand-subtle)", display: "flex", alignItems: "center", justifyContent: "center", marginBottom: 4 }}>{art}</div>
      <div style={{ fontSize: "var(--fs-h4)", fontWeight: "var(--fw-semibold)", color: "var(--text-strong)", letterSpacing: "var(--ls-snug)" }}>{title}</div>
      {description && <p style={{ margin: 0, maxWidth: 340, fontSize: "var(--fs-sm)", lineHeight: "var(--lh-normal)", color: "var(--text-secondary)" }}>{description}</p>}
      {action && <div style={{ marginTop: 8 }}>{action}</div>}
    </div>
  );
}

Object.assign(window, { Icon, Button, Card, Badge, LeadQualityBadge, WaveBars, Avatar, SegmentedTabs, StatTile, EmptyState });
