// ============================================================
// Maquinário — peças recorrentes do módulo (chips, painéis, tabelas)
// ============================================================
const STATUS_STYLE = {
  'Atrasada': { bg: 'var(--color-danger-dark)', fg: '#fff' },
  'A vencer': { bg: 'var(--color-warning)', fg: '#fff' },
  'Atenção': { bg: 'var(--color-alert)', fg: 'var(--color-alert-dark)' },
  'Segura': { bg: 'var(--color-success-light)', fg: '#fff' },
}
function StatusChip({ status, minWidth = 80 }) {
  const s = STATUS_STYLE[status] || STATUS_STYLE['Segura']
  return <span style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', minWidth, padding: '5px 14px', borderRadius: 100,
    background: s.bg, color: s.fg, fontSize: 14, fontWeight: 500, whiteSpace: 'nowrap' }}>{status}</span>
}

// Glifos ausentes na fonte ckl-icon (chave/escudo) desenhados em SVG no mesmo peso
function GlyphWrench({ size = 17 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ display: 'block' }}>
      <path d="M15.3 3.3a4.7 4.7 0 0 0-1.2 4.6L4.4 17.6a2 2 0 0 0 2.8 2.8l9.7-9.7a4.7 4.7 0 0 0 4.6-1.2l-3-.5-.5-3z" />
    </svg>
  )
}
function GlyphShieldCheck({ size = 17 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ display: 'block' }}>
      <path d="M12 3 4.5 5.6v5.2c0 4.3 3 8.1 7.5 9.6 4.5-1.5 7.5-5.3 7.5-9.6V5.6L12 3z" />
      <path d="M9 11.6l2.2 2.2L15.2 9.8" />
    </svg>
  )
}
function TypeGlyph({ type, size = 17 }) {
  const { Ic } = window
  if (type === 'Corretiva') return <GlyphWrench size={size} />
  if (type === 'Preventiva') return <GlyphShieldCheck size={size} />
  const s = TYPE_STYLE[type] || TYPE_STYLE['Corretiva']
  return <Ic name={s.icon} size={size} />
}

// Tipos de manutenção — cada um com hue própria: Preventiva (terracota), Periódica
// (azul-petróleo, base em dias), Garantia (roxo, única) e Corretiva (azul).
const TYPE_STYLE = {
  'Preventiva': { bg: 'var(--color-warning)', fg: '#fff', icon: 'checkmark-circle-outline' },
  'Periódica': { bg: 'oklch(0.52 0.14 265)', fg: '#fff', icon: 'calendar' },
  'Garantia': { bg: 'oklch(0.55 0.19 300)', fg: '#fff', icon: 'ribbon-outline' },
  'Corretiva': { bg: 'var(--color-info)', fg: '#fff', icon: 'warning-outline' },
}
function TypeChip({ type, variant }) {
  const s = TYPE_STYLE[type] || TYPE_STYLE['Corretiva']
  if (variant === 'text') return (
    <span style={{ display: 'inline-flex', alignItems: 'center', fontSize: 14, fontWeight: 500, color: 'var(--color-grayish)', whiteSpace: 'nowrap' }}>{type}</span>
  )
  return <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8, padding: '6px 16px', borderRadius: 100,
    background: s.bg, color: s.fg, fontSize: 14, fontWeight: 500, whiteSpace: 'nowrap' }}>
    <TypeGlyph type={type} />{type}</span>
}

// Pílulas de filtro por tipo de manutenção (dashboard)
function TypeFilterPills({ value, onChange, types }) {
  const all = [{ key: '', label: 'Todas' }, ...types.map(t => ({ key: t, label: t }))]
  return (
    <div style={{ display: 'flex', flexWrap: 'wrap', gap: 10 }}>
      {all.map(t => {
        const on = value === t.key
        const s = TYPE_STYLE[t.key]
        return (
          <button key={t.key || 'all'} onClick={() => onChange(t.key)} style={{ display: 'inline-flex', alignItems: 'center', gap: 8, padding: '7px 16px', borderRadius: 100, cursor: 'pointer', fontFamily: 'inherit', fontSize: 14, fontWeight: 500, whiteSpace: 'nowrap',
            border: '1px solid ' + (on ? 'transparent' : 'var(--color-neutral-200)'),
            background: on ? (s ? s.bg : 'var(--color-grayish)') : '#fff',
            color: on ? (s ? s.fg : '#fff') : 'var(--color-grayish)' }}>
            {s && <TypeGlyph type={t.key} size={16} />}{t.label}
          </button>
        )
      })}
    </div>
  )
}

function ActiveChip({ active }) {
  const { Ic } = window
  return <span style={{ display: 'inline-flex', alignItems: 'center', gap: 7, padding: '6px 16px', borderRadius: 100,
    background: active ? 'var(--color-success)' : 'var(--color-neutral-300)', color: '#fff', fontSize: 14, fontWeight: 500 }}>
    <Ic name={active ? 'radio-button-on' : 'radio-button-off'} size={15} />{active ? 'Ativo' : 'Inativo'}</span>
}

// Painel branco (styles.tableContainer / filtersContainer)
function Panel({ children, style, pad = 32 }) {
  return <section style={{ background: '#fff', borderRadius: 'var(--border-radius-default)', boxShadow: 'var(--shadow-card-default)', padding: pad, ...style }}>{children}</section>
}

function BlockTitle({ children, style }) {
  return <h2 style={{ margin: '0 0 32px', fontSize: 22, fontWeight: 600, color: 'var(--color-grayish-dark)', letterSpacing: 'var(--letter-space-default)', ...style }}>{children}</h2>
}

// Cabeçalho de tabela com afordância de ordenação (uppercase + seta)
function Th({ children, sortable = true, align = 'left', width }) {
  return <th style={{ textAlign: align, padding: '14px 16px', width, fontSize: 13, fontWeight: 500, letterSpacing: '0.6px', textTransform: 'uppercase',
    color: 'var(--color-grayish)', background: '#fff', borderBottom: '1px solid var(--color-neutral-100)', whiteSpace: 'nowrap' }}>
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, cursor: sortable ? 'pointer' : 'default' }}>
      {children}{sortable && <span style={{ opacity: 0.5, fontSize: 13 }}>↓</span>}</span></th>
}
function Td({ children, style, onClick, title }) {
  return <td onClick={onClick} title={title} style={{ padding: '18px 16px', fontSize: 15, fontWeight: 500, color: 'var(--color-grayish)', verticalAlign: 'middle', ...style }}>{children}</td>
}
function Row({ children, i, onClick }) {
  const [h, setH] = React.useState(false)
  const zebra = i % 2 === 1
  return <tr onClick={onClick} onMouseEnter={() => setH(true)} onMouseLeave={() => setH(false)}
    style={{ background: h ? 'var(--color-background-dark-1)' : (zebra ? '#F7F7F7' : '#fff'), cursor: onClick ? 'pointer' : 'default' }}>{children}</tr>
}
function TableFrame({ children, style }) {
  return <div style={{ overflowX: 'auto' }}><table style={{ width: '100%', borderCollapse: 'collapse', ...style }}>{children}</table></div>
}

function Pagination({ pages = 4, page = 1, onPage }) {
  const { Ic } = window
  if (pages <= 1) return null
  return (
    <div style={{ display: 'flex', justifyContent: 'flex-end', alignItems: 'center', gap: 6, marginTop: 24 }}>
      <Ic name="chevron-back" size={18} color="var(--color-grayish-light)" />
      {Array.from({ length: pages }, (_, i) => i + 1).map(n => (
        <button key={n} onClick={() => onPage && onPage(n)} style={{ width: 34, height: 34, borderRadius: 6, border: 0, cursor: 'pointer', fontFamily: 'inherit', fontSize: 14, fontWeight: 600,
          background: n === page ? 'var(--color-primary)' : 'transparent', color: n === page ? '#fff' : 'var(--color-grayish)' }}>{n}</button>
      ))}
      <Ic name="chevron-forward" size={18} color="var(--color-grayish-light)" />
    </div>
  )
}

// Estados de lista — mesmos textos do produto
function EmptyState({ message }) {
  const { Ic } = window
  return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 20, padding: '64px 24px' }}>
      <span style={{ width: 96, height: 96, borderRadius: '50%', background: 'var(--color-neutral-light-200)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <Ic name="file-tray-full-outline" size={42} color="var(--color-neutral-300)" /></span>
      <p style={{ margin: 0, fontSize: 17, fontWeight: 500, color: 'var(--color-grayish)', textAlign: 'center', maxWidth: 420, textWrap: 'pretty' }}>{message}</p>
    </div>
  )
}
function SkeletonRows({ rows = 6, height = 22 }) {
  return <div style={{ display: 'flex', flexDirection: 'column', gap: 18, padding: '8px 0' }}>
    {Array.from({ length: rows }).map((_, i) => (
      <div key={i} style={{ height, borderRadius: 6, background: 'linear-gradient(90deg, #EDEDED 25%, #F6F6F6 50%, #EDEDED 75%)', backgroundSize: '200% 100%', animation: 'fgShimmer 1.2s linear infinite' }} />
    ))}</div>
}

// Barra horizontal para os gráficos agregados do dashboard
function Bar({ label, segments, total, suffix }) {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr', gap: 6 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', gap: 12, fontSize: 14, fontWeight: 500, color: 'var(--color-grayish)' }}>
        <span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{label}</span>
        <span style={{ color: 'var(--color-grayish-dark)' }}>{suffix}</span>
      </div>
      <div style={{ display: 'flex', gap: 2, height: 14, borderRadius: 100, overflow: 'hidden', background: 'var(--color-neutral-light-300)' }}>
        {segments.filter(s => s.value > 0).map((s, i) => (
          <span key={i} title={s.name + ': ' + s.value} style={{ width: (s.value / total * 100) + '%', background: s.color }} />
        ))}
      </div>
    </div>
  )
}
function Legend({ items }) {
  return <div style={{ display: 'flex', flexWrap: 'wrap', gap: 18, marginTop: 20 }}>
    {items.map((it, i) => (
      <span key={i} style={{ display: 'inline-flex', alignItems: 'center', gap: 7, fontSize: 13, fontWeight: 500, color: 'var(--color-grayish)' }}>
        <span style={{ width: 12, height: 12, borderRadius: 3, background: it.color }} />{it.name}</span>
    ))}</div>
}

function InfoBanner({ message, linkText, onClose }) {
  const { Ic } = window
  const parts = message.split(linkText)
  return (
    <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12, maxWidth: 420, padding: '14px 16px', borderRadius: 'var(--border-radius-default)', background: 'var(--color-info)', color: '#fff' }}>
      <Ic name="information-circle-outline" size={20} style={{ flexShrink: 0, marginTop: 1 }} />
      <span style={{ fontSize: 14, fontWeight: 500, lineHeight: 1.4 }}>{parts[0]}<a href="#" onClick={e => e.preventDefault()} style={{ color: '#fff', textDecoration: 'underline' }}>{linkText}</a>{parts[1]}</span>
      <Ic name="close" size={18} onClick={onClose} style={{ flexShrink: 0 }} />
    </div>
  )
}

function FilterButton({ count, onClick }) {
  const { Btn } = window
  return <Btn type="ghost" size="medium" label={count ? `Filtrar (${count})` : 'Filtrar'} icon="filter" onClick={onClick} />
}

function Caption({ children, style }) {
  return <span style={{ display: 'block', fontSize: 12, fontWeight: 500, letterSpacing: '0.8px', textTransform: 'uppercase', color: 'var(--color-primary)', ...style }}>{children}</span>
}

function fmtNum(n) { return typeof n === 'number' ? n.toLocaleString('pt-BR') : n }
function fmtDateBR(iso) { const [y, m, d] = iso.split('-'); return `${d}/${m}/${y}` }

Object.assign(window, { StatusChip, TypeChip, TypeGlyph, TypeFilterPills, TYPE_STYLE, ActiveChip, Panel, BlockTitle, Th, Td, Row, TableFrame, Pagination, EmptyState, SkeletonRows, Bar, Legend, InfoBanner, FilterButton, Caption, fmtNum, fmtDateBR })
