/**
 * TrendApp — Componentes base reutilizáveis
 * (exportados via window para serem acessíveis por outros arquivos Babel)
 *
 * Anti-padrão evitado: NÃO usar `const styles = { ... }` — usar inline ou objeto renomeado.
 */

// (React hooks declarados uma vez em logo.jsx)

// ─── Icon (Lucide via icons map) ──────────────────────────────────────────
// Lucide UMD expõe window.lucide.icons — cada ícone é [tag, attrs, children].
// Renderizamos SVG direto (compatível com React re-renders — sem createIcons).
const ICON_CACHE = {};

function getLucideIcon(name) {
  if (ICON_CACHE[name]) return ICON_CACHE[name];
  if (!window.lucide?.icons) return null;
  // Lucide expõe ícones em kebab e/ou pascal case. Normalizamos para kebab-case
  // (nome do prop) → chave pascal (chave interna do bundle UMD).
  const pascal = name
    .split('-')
    .map(s => s.charAt(0).toUpperCase() + s.slice(1))
    .join('');
  const spec = window.lucide.icons[pascal] || window.lucide.icons[name] || window.lucide.icons[pascal + 'Icon'];
  if (spec) ICON_CACHE[name] = spec;
  return spec || null;
}

function Icon({ name, size = 20, strokeWidth = 1.75, color, className, style }) {
  const spec = getLucideIcon(name);
  const commonStyle = {
    display: 'inline-block', flexShrink: 0,
    verticalAlign: 'middle',
    color: color ?? 'currentColor',
    ...style,
  };
  if (!spec) {
    // Fallback discreto — quadrado transparente com contorno leve
    return (
      <span
        aria-hidden="true"
        style={{
          ...commonStyle,
          width: size, height: size,
          border: '1px dashed currentColor', opacity: 0.35, borderRadius: 3,
        }}
      />
    );
  }
  // spec = [tag, defaultAttrs, children]
  // Lucide 0.469 usa formato [tag, attrs, children] onde children é array de [tag, attrs] (SVG paths).
  // Renderizamos <svg> com os children.
  const attrs = spec[1] || {};
  const children = Array.isArray(spec[2]) ? spec[2] : [];
  return (
    <svg
      xmlns="http://www.w3.org/2000/svg"
      width={size}
      height={size}
      viewBox={attrs.viewBox || '0 0 24 24'}
      fill={attrs.fill || 'none'}
      stroke={attrs.stroke || 'currentColor'}
      strokeWidth={strokeWidth}
      strokeLinecap={attrs['stroke-linecap'] || 'round'}
      strokeLinejoin={attrs['stroke-linejoin'] || 'round'}
      style={commonStyle}
      className={className}
      aria-hidden="true"
    >
      {children.map((child, i) => {
        // child = [tagName, attrsObject] OR [tagName, attrsObject, [more children]]
        const [tag, childAttrs] = child;
        // Convert kebab-case attrs to React camelCase
        const props = { key: i };
        for (const k in childAttrs) {
          if (k === 'stroke-linecap')    props.strokeLinecap = childAttrs[k];
          else if (k === 'stroke-linejoin') props.strokeLinejoin = childAttrs[k];
          else if (k === 'stroke-width')    props.strokeWidth = childAttrs[k];
          else if (k === 'fill-rule')       props.fillRule = childAttrs[k];
          else if (k === 'clip-rule')       props.clipRule = childAttrs[k];
          else                              props[k] = childAttrs[k];
        }
        return React.createElement(tag, props);
      })}
    </svg>
  );
}

// Legacy no-op — mantido para compat com chamadas useLucide() espalhadas.
// (Não precisamos mais de mutação DOM pós-render — ícones já renderizam como SVG puro.)
function useLucide(_deps) {}

// ─── Card ───────────────────────────────────────────────────────────────────
function Card({ children, className = '', style, onClick, as: As = 'div' }) {
  return (
    <As
      className={`card ${className}`}
      style={style}
      onClick={onClick}
      role={onClick ? 'button' : undefined}
      tabIndex={onClick ? 0 : undefined}
    >
      {children}
    </As>
  );
}

// ─── FarolPill ──────────────────────────────────────────────────────────────
function FarolPill({ farol, size = 'md' }) {
  const LABEL = { verde: 'Verde', amarelo: 'Amarelo', vermelho: 'Vermelho' };
  if (!farol) return null;
  return (
    <span className={`pill dot farol-${farol} ${size === 'sm' ? 'sm' : ''}`}>
      {LABEL[farol]}
    </span>
  );
}

// ─── RecuperacaoPill (Em risco / Churn) ────────────────────────────────────
function RecuperacaoPill({ faixa }) {
  if (!faixa) return null;
  if (faixa === 'em_risco') return <span className="pill status-warning">Em risco</span>;
  return <span className="pill status-danger">Churn</span>;
}

// ─── ComissaoPill ──────────────────────────────────────────────────────────
function ComissaoPill({ status }) {
  const map = window.TrendMocks.COMISSAO_LABEL;
  if (!status || !map[status]) return null;
  return <span className={`pill ${map[status].style}`}>{map[status].text}</span>;
}

// ─── StatusPedidoPill ──────────────────────────────────────────────────────
function StatusPedidoPill({ status, size = 'md' }) {
  const map = window.TrendMocks.STATUS_STYLE;
  const cfg = map[status];
  if (!cfg) return null;
  return <span className={`pill ${cfg.style} ${size === 'sm' ? 'sm' : ''}`}>{status}</span>;
}

// ─── DeltaChip ─────────────────────────────────────────────────────────────
function DeltaChip({ value, formato = 'pct', size = 'md' }) {
  if (value == null) return null;
  const isUp = value > 0, isDown = value < 0;
  const color = isUp ? 'var(--success)' : isDown ? 'var(--destructive)' : 'var(--muted-foreground)';
  const bg = isUp
    ? 'color-mix(in oklch, var(--success) 12%, transparent)'
    : isDown
    ? 'color-mix(in oklch, var(--destructive) 12%, transparent)'
    : 'color-mix(in oklch, var(--muted-foreground) 12%, transparent)';
  const arrow = isUp ? '↑' : isDown ? '↓' : '→';
  const abs = Math.abs(value);
  const label = formato === 'pp'
    ? `${abs.toFixed(1).replace('.', ',')} p.p.`
    : `${(abs * 100).toFixed(1).replace('.', ',')}%`;
  const fontSize = size === 'sm' ? '11px' : '12px';
  return (
    <span
      style={{
        display: 'inline-flex', alignItems: 'center', gap: 3,
        padding: size === 'sm' ? '2px 7px' : '3px 9px',
        borderRadius: 999, background: bg, color,
        fontSize, fontWeight: 600, fontVariantNumeric: 'tabular-nums',
        whiteSpace: 'nowrap',
      }}
    >
      <span aria-hidden="true">{arrow}</span>{label}
    </span>
  );
}

// ─── Initials ──────────────────────────────────────────────────────────────
function Initials({ name, size = 36, color }) {
  const text = window.TrendFmt.initials(name);
  const hue = (name || '').split('').reduce((a, c) => a + c.charCodeAt(0), 0) % 360;
  const bg = color ?? `oklch(0.9 0.05 ${hue})`;
  const fg = `oklch(0.35 0.08 ${hue})`;
  return (
    <div
      style={{
        width: size, height: size,
        borderRadius: '50%',
        background: bg, color: fg,
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        fontSize: size * 0.36, fontWeight: 600, flexShrink: 0,
        letterSpacing: '-0.01em',
      }}
      aria-hidden="true"
    >{text}</div>
  );
}

// ─── EmptyState ────────────────────────────────────────────────────────────
function EmptyState({ icon = 'inbox', title, description, cta }) {
  useLucide([icon, title]);
  return (
    <div className="empty">
      <div className="empty-icon"><Icon name={icon} size={24} /></div>
      {title && <div className="empty-title">{title}</div>}
      {description && <div style={{ fontSize: 13, maxWidth: 260 }}>{description}</div>}
      {cta}
    </div>
  );
}

// ─── ErrorBanner ───────────────────────────────────────────────────────────
function ErrorBanner({ title = 'Não foi possível carregar', description = 'Tente novamente em instantes.', onRetry }) {
  useLucide();
  return (
    <div className="card" style={{
      background: 'color-mix(in oklch, var(--destructive) 6%, var(--card))',
      borderColor: 'color-mix(in oklch, var(--destructive) 25%, var(--border))',
    }}>
      <div style={{ display: 'flex', gap: 12, alignItems: 'flex-start' }}>
        <div style={{
          width: 32, height: 32, borderRadius: 999,
          background: 'color-mix(in oklch, var(--destructive) 12%, transparent)',
          color: 'var(--destructive)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          flexShrink: 0,
        }}><Icon name="alert-triangle" size={16} /></div>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--foreground)' }}>{title}</div>
          <div style={{ fontSize: 13, color: 'var(--muted-foreground)', marginTop: 2 }}>{description}</div>
          {onRetry && (
            <button className="btn sm secondary" style={{ marginTop: 10 }} onClick={onRetry}>
              <Icon name="refresh-cw" size={14} /> Tentar novamente
            </button>
          )}
        </div>
      </div>
    </div>
  );
}

// ─── Sheet (bottom sheet) ──────────────────────────────────────────────────
function Sheet({ open, onClose, title, children }) {
  useEffect(() => {
    if (open) {
      // Prevent scroll on body when sheet is open
      const previousOverflow = document.body.style.overflow;
      document.body.style.overflow = 'hidden';
      return () => { document.body.style.overflow = previousOverflow; };
    }
  }, [open]);
  useLucide([open]);
  return (
    <Fragment>
      <div className="sheet-backdrop" data-open={open ? 'true' : 'false'} onClick={onClose} />
      <div className="sheet" data-open={open ? 'true' : 'false'} role="dialog" aria-modal="true" aria-hidden={!open}>
        <div className="sheet-handle" />
        {title && <div className="sheet-title">{title}</div>}
        {children}
      </div>
    </Fragment>
  );
}

// ─── KpiCell — editorial (grid 2 col, hairlines em vez de cards) ──────────
function KpiCell({ label, value, delta, formato, hint }) {
  const deltaCls = delta == null
    ? null
    : delta > 0 ? 'delta-inline up'
    : delta < 0 ? 'delta-inline down'
    : 'delta-inline flat';
  const deltaText = delta == null ? null
    : `${delta > 0 ? '+' : delta < 0 ? '−' : ''}${(Math.abs(delta) * (formato === 'pp' ? 100 : 100)).toFixed(1).replace('.', ',')}${formato === 'pp' ? ' p.p.' : '%'}`;
  return (
    <div className="kpi-editorial">
      <div className="kpi-editorial-label">{label}</div>
      <div className="kpi-editorial-value">{value ?? '—'}</div>
      <div className="kpi-editorial-meta">
        {delta != null ? <span className={deltaCls}>{deltaText}</span> : (hint && <span>{hint}</span>)}
      </div>
    </div>
  );
}

// KpiGrid — layout 2 col separado por hairlines verticais + horizontais
function KpiGrid({ children }) {
  return (
    <div
      style={{
        display: 'grid',
        gridTemplateColumns: '1fr 1fr',
        columnGap: 24,
      }}
    >
      {React.Children.map(children, (child, i) => (
        <div
          style={{
            position: 'relative',
            borderRight: i % 2 === 0 ? '1px solid var(--border)' : 'none',
            paddingRight: i % 2 === 0 ? 12 : 0,
            paddingLeft: i % 2 === 1 ? 12 : 0,
            marginRight: i % 2 === 0 ? -12 : 0,
            marginLeft: i % 2 === 1 ? -12 : 0,
          }}
        >
          {child}
        </div>
      ))}
    </div>
  );
}

// ─── Section (título + children) ───────────────────────────────────────────
function Section({ title, action, children, description }) {
  return (
    <section>
      {(title || action) && (
        <div className="between" style={{ marginBottom: 10 }}>
          <div>
            <div className="section-title">{title}</div>
            {description && <div style={{ fontSize: 12, color: 'var(--muted-foreground)', marginTop: 2 }}>{description}</div>}
          </div>
          {action}
        </div>
      )}
      {children}
    </section>
  );
}

// ─── Skeleton helpers ──────────────────────────────────────────────────────
function SkelLine({ w = '100%', h = 14, style }) {
  return <div className="skel" style={{ width: w, height: h, ...style }} />;
}
function SkelCard({ h = 120 }) {
  return <div className="skel" style={{ height: h, borderRadius: 14 }} />;
}

// ─── Header (page) ─────────────────────────────────────────────────────────
// ─── HeroHeader — dark sólido premium (tabs Vendas/Clientes/Perfil) ─────
// Título light, eyebrow uppercase, micro-ação opcional à direita.
// Mesma linguagem do Home hero fotográfico, mas sem imagem.
function HeroHeader({
  eyebrow,          // string uppercase
  title,            // string principal
  subtitle,         // opcional (fica abaixo do título, cor muted)
  action,           // { icon, onClick, ariaLabel } — micro-ação à direita
  avatar,           // opcional — string nome para <Initials>
  minHeight = 200,  // altura mínima do bloco dark
  children,         // conteúdo opcional (ex.: KPI hero, chip, etc.)
}) {
  return (
    <div style={{
      position: 'relative',
      minHeight,
      background: '#040805',
      color: '#F5F7F7',
      overflow: 'hidden',
      marginBottom: 8,
    }}>
      {/* Foto de textura orgânica (mesma imagem do Home/Welcome) */}
      <div aria-hidden="true" style={{
        position: 'absolute', inset: 0,
        backgroundImage: 'url(/static/trendapp/assets/welcome-hero.jpg)',
        backgroundSize: 'cover',
        backgroundPosition: 'center center',
        backgroundRepeat: 'no-repeat',
      }} />
      {/* Overlay dark verde-preto mais forte
          (headers menores → precisam de mais escurecimento pra manter
          legibilidade sem que a textura compita com o texto) */}
      <div aria-hidden="true" style={{
        position: 'absolute', inset: 0,
        background:
          'linear-gradient(180deg,' +
          ' rgba(6, 14, 9, 0.72) 0%,' +
          ' rgba(4, 10, 6, 0.85) 55%,' +
          ' rgba(4, 8, 5, 0.96) 100%)',
      }} />
      {/* Vinheta lateral */}
      <div aria-hidden="true" style={{
        position: 'absolute', inset: 0,
        background: 'radial-gradient(ellipse at center, transparent 40%, rgba(0,0,0,0.5) 100%)',
        pointerEvents: 'none',
      }} />

      {/* Conteúdo */}
      <div style={{
        position: 'relative', zIndex: 1,
        padding: 'calc(16px + var(--safe-top)) 24px 24px',
        display: 'flex', flexDirection: 'column',
        minHeight,
      }}>
        {/* Topo: marca + micro-ação */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 4 }}>
          <div style={{ color: '#F5F7F7', opacity: 0.95 }}>
            <TrendAppLogo height={18} />
          </div>
          <div style={{ flex: 1 }} />
          {action && (
            <button
              onClick={action.onClick}
              aria-label={action.ariaLabel}
              style={{
                width: 36, height: 36,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                color: 'rgba(245,247,247,0.7)',
                background: 'transparent',
              }}
            >
              <Icon name={action.icon} size={17} strokeWidth={1.5} />
            </button>
          )}
          {avatar && (
            <div style={{
              width: 34, height: 34, borderRadius: '50%',
              border: '1px solid rgba(255,255,255,0.25)',
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
              fontSize: 12, fontWeight: 400, letterSpacing: '-0.01em',
              color: '#F5F7F7',
              background: 'rgba(255,255,255,0.06)',
              backdropFilter: 'blur(8px)',
            }}>
              {window.TrendFmt.initials(avatar)}
            </div>
          )}
        </div>

        <div style={{ flex: 1 }} />

        {/* Título editorial */}
        {eyebrow && (
          <div style={{
            fontSize: 10.5,
            fontWeight: 400,
            letterSpacing: '0.14em',
            textTransform: 'uppercase',
            color: 'rgba(245,247,247,0.55)',
            marginBottom: 10,
          }}>
            {eyebrow}
          </div>
        )}
        <h1 style={{
          fontSize: 32,
          fontWeight: 300,
          letterSpacing: '-0.028em',
          lineHeight: 1.1,
          color: '#F5F7F7',
          margin: 0,
        }}>
          {title}
        </h1>
        {subtitle && (
          <p style={{
            marginTop: 8,
            fontSize: 13.5,
            fontWeight: 400,
            color: 'rgba(245,247,247,0.55)',
            maxWidth: 320,
          }}>
            {subtitle}
          </p>
        )}

        {children && <div style={{ marginTop: 16 }}>{children}</div>}
      </div>
    </div>
  );
}

function PageHeader({ title, subtitle, back, right, transparent = false }) {
  useLucide([title, back, right]);
  return (
    <header className={`page-header ${transparent ? '' : 'with-border'}`}>
      {back && (
        <button className="icon-btn" onClick={back} aria-label="Voltar">
          <Icon name="chevron-left" size={22} />
        </button>
      )}
      <div className="grow">
        <div className="h-title truncate">{title}</div>
        {subtitle && <div className="h-sub">{subtitle}</div>}
      </div>
      {right}
    </header>
  );
}

// ─── Router link back helper — não bem um componente ───────────────────────
function BackBtn({ onClick }) {
  useLucide();
  return (
    <button className="icon-btn" onClick={onClick} aria-label="Voltar">
      <Icon name="chevron-left" size={22} />
    </button>
  );
}

// ─── FieldRow (label: value) usado em detalhes ─────────────────────────────
function FieldRow({ label, value, mono = true }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', gap: 12, padding: '10px 0', borderBottom: '1px solid var(--border)' }}>
      <span style={{ fontSize: 13, color: 'var(--muted-foreground)' }}>{label}</span>
      <span
        style={{
          fontSize: 14, fontWeight: 500, color: 'var(--foreground)', textAlign: 'right',
          fontVariantNumeric: mono ? 'tabular-nums' : 'normal',
          minWidth: 0, wordBreak: 'break-word',
        }}
      >{value ?? '—'}</span>
    </div>
  );
}

// ─── ListItem (usado em várias telas) ──────────────────────────────────────
function ListItem({ leading, title, subtitle, meta, onClick, priority }) {
  useLucide();
  return (
    <div
      className="card tight"
      style={{ display: 'flex', gap: 12, alignItems: 'center', cursor: onClick ? 'pointer' : 'default', position: 'relative' }}
      onClick={onClick}
      role={onClick ? 'button' : undefined}
      tabIndex={onClick ? 0 : undefined}
    >
      {priority && (
        <span style={{
          position: 'absolute', left: -1, top: 12, bottom: 12,
          width: 3, borderRadius: '0 2px 2px 0',
          background: 'var(--destructive)',
        }} />
      )}
      {leading}
      <div className="grow" style={{ minWidth: 0 }}>
        <div style={{ fontSize: 14, fontWeight: 500, color: 'var(--foreground)' }}>{title}</div>
        {subtitle && <div style={{ fontSize: 12, color: 'var(--muted-foreground)', marginTop: 2 }}>{subtitle}</div>}
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 4, flexShrink: 0 }}>
        {meta}
        {onClick && <Icon name="chevron-right" size={16} color="var(--muted-foreground)" />}
      </div>
    </div>
  );
}

// ─── Assign to window ──────────────────────────────────────────────────────
Object.assign(window, {
  Icon, useLucide,
  Card, FarolPill, RecuperacaoPill, ComissaoPill, StatusPedidoPill, DeltaChip,
  Initials, EmptyState, ErrorBanner, Sheet, KpiCell, KpiGrid, Section,
  SkelLine, SkelCard, PageHeader, HeroHeader, BackBtn, FieldRow, ListItem,
});
