/* global React */
const { useState, useEffect, useRef, useId, useMemo } = React;

/* ============================================================
   BEZA LOGO · imagem real da marca
   window.BEZA_ASSETS_PATH é definido em cada HTML antes de carregar ui.jsx
   ============================================================ */
function BezaLogo({ size = 32, withTagline = false, style }) {
  const h = size;
  const base = window.BEZA_ASSETS_PATH || 'assets';
  return (
    <span
      style={{
        display: 'inline-flex',
        alignItems: 'center',
        gap: h * 0.4,
        lineHeight: 1,
        ...style,
      }}
      aria-label="Beza Media"
    >
      <img
        src={`${base}/beza-roxo.png`}
        alt="Beza Media"
        height={Math.round(h * 1.5)}
        className="beza-logo-themed"
        style={{ display: 'block', width: 'auto' }}
      />
      {withTagline && (
        <span
          style={{
            fontFamily: "'IBM Plex Sans', sans-serif",
            fontWeight: 300,
            fontSize: h * 0.52,
            letterSpacing: '-0.005em',
            paddingLeft: h * 0.4,
            borderLeft: '1px solid currentColor',
            marginLeft: h * 0.1,
            opacity: 0.45,
            fontStyle: 'italic',
            color: 'currentColor',
          }}
        >
          relatórios
        </span>
      )}
    </span>
  );
}

/* ============================================================
   ÍCONES · stroke 1.5 · 24x24 · currentColor
   ============================================================ */
const Icon = {
  Instagram: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <rect x="3" y="3" width="18" height="18" rx="5" />
      <circle cx="12" cy="12" r="4" />
      <circle cx="17.5" cy="6.5" r="0.6" fill="currentColor" />
    </svg>
  ),
  YouTube: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <rect x="2.5" y="5" width="19" height="14" rx="3.5" />
      <path d="M10.5 9.2v5.6l5-2.8z" fill="currentColor" stroke="none" />
    </svg>
  ),
  LinkedIn: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <rect x="3" y="3" width="18" height="18" rx="3" />
      <line x1="7" y1="10" x2="7" y2="17" />
      <circle cx="7" cy="7" r="0.7" fill="currentColor" />
      <path d="M11 17v-4.2c0-1.2 0.8-2.3 2.2-2.3 1.4 0 2.3 1 2.3 2.4V17" />
    </svg>
  ),
  Meta: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <path d="M3 14.5c0 2 1 3.5 2.8 3.5 2 0 3.4-1.8 5.5-5.5C13.4 8.8 14.8 7 16.8 7c1.8 0 2.8 1.5 2.8 3.5 0 2-1 3.5-2.8 3.5-1.4 0-2.6-1-3.6-2.5" />
      <path d="M3 14.5c0-2.4 1.4-7.5 4.5-7.5 1.7 0 2.9 1.3 3.8 3" />
    </svg>
  ),
  Analytics: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <path d="M4 19h16" />
      <rect x="6" y="11" width="3" height="6" rx="0.5" />
      <rect x="11" y="7" width="3" height="10" rx="0.5" />
      <rect x="16" y="13" width="3" height="4" rx="0.5" />
    </svg>
  ),
  Up: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <path d="M6 14l5-5 3 3 5-7" />
      <path d="M19 5h-3M19 5v3" />
    </svg>
  ),
  Down: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <path d="M6 10l5 5 3-3 5 7" />
      <path d="M19 19h-3M19 19v-3" />
    </svg>
  ),
  Flat: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <path d="M5 12h14" />
    </svg>
  ),
  Info: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <circle cx="12" cy="12" r="9" />
      <path d="M12 11v5" />
      <circle cx="12" cy="8" r="0.6" fill="currentColor" />
    </svg>
  ),
  Heart: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <path d="M12 19.5s-6.5-4-8.5-8c-1.3-2.7 0.4-6 3.5-6 1.8 0 3.3 1 5 3 1.7-2 3.2-3 5-3 3.1 0 4.8 3.3 3.5 6-2 4-8.5 8-8.5 8z" />
    </svg>
  ),
  Comment: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <path d="M21 11.5c0 4.1-4 7.5-9 7.5-1.4 0-2.7-0.2-3.9-0.7L3 20l1.4-4C3.5 14.7 3 13.2 3 11.5 3 7.4 7 4 12 4s9 3.4 9 7.5z" />
    </svg>
  ),
  Bookmark: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <path d="M7 4h10v17l-5-3.5L7 21z" />
    </svg>
  ),
  Share: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <path d="M4 13l8-8v4c5 0 8 4 8 9-2-3-4.5-4.5-8-4.5V17z" />
    </svg>
  ),
  Eye: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12z" />
      <circle cx="12" cy="12" r="3" />
    </svg>
  ),
  Play: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <circle cx="12" cy="12" r="9" />
      <path d="M10 8.5v7l6-3.5z" fill="currentColor" stroke="none" />
    </svg>
  ),
  Users: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <circle cx="9" cy="8" r="3.5" />
      <path d="M3 19c0-3.3 2.7-6 6-6s6 2.7 6 6" />
      <circle cx="17" cy="9" r="2.5" />
      <path d="M16 14c2.8 0 5 2.2 5 5" />
    </svg>
  ),
  Click: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <path d="M9 4v3M5.6 5.6l2.1 2.1M4 9h3M14 12l7 2.5-3 1.5-1.5 3z" />
      <path d="M12 14l-3.5 3.5" />
    </svg>
  ),
  Arrow: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <path d="M5 12h14M13 6l6 6-6 6" />
    </svg>
  ),
  Calendar: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <rect x="3.5" y="5" width="17" height="15" rx="2" />
      <path d="M3.5 10h17M8 3.5v3M16 3.5v3" />
    </svg>
  ),
  Sparkle: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <path d="M12 4v4M12 16v4M4 12h4M16 12h4M6 6l2.5 2.5M15.5 15.5L18 18M6 18l2.5-2.5M15.5 8.5L18 6" />
    </svg>
  ),
  External: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <path d="M14 4h6v6M20 4l-9 9M10 6H5v13h13v-5" />
    </svg>
  ),
  Threads: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <path d="M12 3C7.6 3 4.5 6.2 4.5 10c0 2.4 1.2 4.3 3 5.4" />
      <path d="M12 3c3.1 0 5.6 1.8 6.9 4.4.8 1.5.7 3.7-.3 5.5C17.4 15.2 15 16.4 12.5 16.4c-1.5 0-2.8-.4-3.8-1.1" />
      <path d="M15.2 12.8c0 2-1.4 3.8-3.2 4.2" />
      <circle cx="12" cy="18.5" r="1.5" fill="currentColor" stroke="none" />
    </svg>
  ),
  TikTok: (p) => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <path d="M9 12a4 4 0 1 0 4 4V4a5 5 0 0 0 5 5" />
    </svg>
  ),
};

/* ============================================================
   PILL · chip pequeno
   ============================================================ */
function Pill({ children, tone = 'neutral', icon, style }) {
  const tones = {
    neutral: { bg: 'var(--accent-soft)', fg: 'var(--text-muted)', bd: 'var(--border)' },
    purple:  { bg: 'rgba(154,155,229,0.14)', fg: 'var(--accent)', bd: 'rgba(154,155,229,0.30)' },
    success: { bg: 'rgba(111,200,120,0.14)', fg: 'var(--success)', bd: 'rgba(111,200,120,0.30)' },
    error:   { bg: 'rgba(243,77,77,0.12)', fg: 'var(--error)', bd: 'rgba(243,77,77,0.28)' },
    warning: { bg: 'rgba(243,174,77,0.14)', fg: 'var(--warning)', bd: 'rgba(243,174,77,0.30)' },
  };
  const t = tones[tone] || tones.neutral;
  return (
    <span
      style={{
        display: 'inline-flex',
        alignItems: 'center',
        gap: 6,
        padding: '4px 10px',
        borderRadius: 'var(--r-pill)',
        background: t.bg,
        color: t.fg,
        border: `1px solid ${t.bd}`,
        fontSize: 12,
        fontWeight: 500,
        letterSpacing: '0.02em',
        lineHeight: 1.3,
        whiteSpace: 'nowrap',
        ...style,
      }}
    >
      {icon}
      {children}
    </span>
  );
}

/* ============================================================
   CARD · default surface
   ============================================================ */
function Card({ children, padding = 24, style, variant = 'default', ...rest }) {
  const variants = {
    default: {
      background: 'var(--surface)',
      border: '1px solid var(--border)',
      backdropFilter: 'blur(20px)',
      WebkitBackdropFilter: 'blur(20px)',
    },
    elevated: {
      background: 'var(--surface-strong)',
      border: '1px solid var(--border)',
      boxShadow: 'var(--shadow-md)',
    },
    bordered: {
      background: 'transparent',
      border: '1px solid var(--border-strong)',
    },
    featured: {
      background: 'linear-gradient(135deg, rgba(154,155,229,0.10), rgba(154,155,229,0.02))',
      border: '1px solid rgba(154,155,229,0.40)',
      boxShadow: 'var(--shadow-purple-glow)',
    },
  };
  return (
    <div
      style={{
        borderRadius: 'var(--r-card-lg)',
        padding,
        ...variants[variant],
        ...style,
      }}
      {...rest}
    >
      {children}
    </div>
  );
}

/* ============================================================
   DELTA · variação % vs período anterior
   ============================================================ */
function Delta({ value, suffix = '%', invertColor = false }) {
  if (value === null || value === undefined || isNaN(value)) {
    return <span style={{ color: 'var(--text-faint)' }}>—</span>;
  }
  const isFlat = Math.abs(value) < 0.5;
  const isUp = value > 0;
  const isGood = invertColor ? !isUp : isUp;
  const color = isFlat ? 'var(--text-faint)' : (isGood ? 'var(--success)' : 'var(--error)');
  const I = isFlat ? Icon.Flat : (isUp ? Icon.Up : Icon.Down);
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 4,
      color, fontWeight: 500, fontSize: 13,
      fontVariantNumeric: 'tabular-nums',
    }}>
      <I width={14} height={14} />
      {isUp ? '+' : ''}{value.toFixed(1).replace('.', ',')}{suffix}
    </span>
  );
}

/* ============================================================
   INFOTIP · explica termo técnico no hover
   ============================================================ */
function Infotip({ label, children }) {
  const [open, setOpen] = useState(false);
  return (
    <span style={{ position: 'relative', display: 'inline-flex', alignItems: 'center', gap: 4 }}>
      <span>{label}</span>
      <span
        role="button"
        tabIndex={0}
        onMouseEnter={() => setOpen(true)}
        onMouseLeave={() => setOpen(false)}
        onFocus={() => setOpen(true)}
        onBlur={() => setOpen(false)}
        style={{
          display: 'inline-flex',
          color: 'var(--text-faint)',
          cursor: 'help',
          marginLeft: 2,
        }}
      >
        <Icon.Info width={13} height={13} />
      </span>
      {open && (
        <span
          role="tooltip"
          style={{
            position: 'absolute',
            top: 'calc(100% + 8px)',
            left: 0,
            zIndex: 50,
            width: 260,
            padding: '10px 12px',
            background: 'var(--bg-flat)',
            color: 'var(--text)',
            border: '1px solid var(--border-strong)',
            borderRadius: 'var(--r-card)',
            boxShadow: 'var(--shadow-lg)',
            fontSize: 12,
            fontWeight: 400,
            letterSpacing: 0,
            textTransform: 'none',
            lineHeight: 1.5,
            opacity: 1,
          }}
        >
          {children}
        </span>
      )}
    </span>
  );
}

/* ============================================================
   FORMATAÇÃO PT-BR
   ============================================================ */
const fmt = {
  int: (n) => new Intl.NumberFormat('pt-BR').format(Math.round(n)),
  dec: (n, d = 1) => new Intl.NumberFormat('pt-BR', { minimumFractionDigits: d, maximumFractionDigits: d }).format(n),
  pct: (n, d = 1) => fmt.dec(n, d) + '%',
  brl: (n) => 'R$ ' + new Intl.NumberFormat('pt-BR', { minimumFractionDigits: 2 }).format(n),
  k:   (n) => {
    if (n >= 1_000_000) return fmt.dec(n/1_000_000, 1).replace(',0', '') + 'M';
    if (n >= 10_000)    return fmt.dec(n/1_000, 0) + 'k';
    if (n >= 1_000)     return fmt.dec(n/1_000, 1).replace(',0', '') + 'k';
    return fmt.int(n);
  },
};

/* ============================================================
   EXPORTS GLOBAIS
   ============================================================ */
Object.assign(window, {
  BezaLogo, Icon, Pill, Card, Delta, Infotip, fmt,
});
