// ============================================================
// Dashboard — 4 abas (Próximas manutenções / Status / Fluxo / Ativos)
// ============================================================
function Tabs({ tabs, active, onChange, align = 'center' }) {
  return (
    <div style={{ background: '#fff', borderRadius: 'var(--border-radius-default)', boxShadow: 'var(--shadow-card-default)', padding: '0 12px', marginBottom: 32 }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: align === 'center' ? 'space-around' : 'flex-start', gap: align === 'center' ? 0 : 36 }}>
        {tabs.map(t => {
          const on = t.key === active
          return (
            <button key={t.key} onClick={() => onChange(t.key)} style={{ position: 'relative', padding: '24px 16px', border: 0, background: 'transparent', cursor: 'pointer', fontFamily: 'inherit',
              fontSize: 14, fontWeight: on ? 500 : 400, letterSpacing: '0.9px', textTransform: 'uppercase', whiteSpace: 'nowrap', color: on ? 'var(--color-success-dark)' : 'var(--color-grayish)' }}>
              {t.label}
              {on && <span style={{ position: 'absolute', left: 8, right: 8, bottom: 14, height: 2, background: 'var(--color-success-dark)' }} />}
            </button>
          )
        })}
      </div>
    </div>
  )
}

const TOT_STYLE = [
  { key: 'overdue', label: 'Atrasadas', bg: 'var(--color-danger-table)', fg: 'var(--color-danger-dark)' },
  { key: 'dueSoon', label: 'A vencer', bg: 'var(--color-warning-light-100)', fg: 'var(--color-warning)' },
  { key: 'attention', label: 'Atenção', bg: 'var(--color-alert-light-100)', fg: 'var(--color-alert)' },
  { key: 'safe', label: 'Segura', bg: 'var(--color-success-light-100)', fg: 'var(--color-success-dark)' },
]

function NextMaintenances({ state, rows, totals, onOpenMachinery, onRegister, filters, setFilter }) {
  const { Panel, BlockTitle, Field, Select, StatusChip, TypeChip, TypeFilterPills, Th, Td, Row, TableFrame, Pagination, EmptyState, SkeletonRows, Btn, Caption } = window
  const { MAINTENANCES, FARMS, SCHEDULED_TYPES } = window.MAQ
  return (
    <React.Fragment>
      <Panel style={{ marginBottom: 32 }}>
        <BlockTitle>Próximas manutenções programadas</BlockTitle>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 24, marginBottom: 24, alignItems: 'end' }}>
          <Field label="Status"><Select placeholder="Todos os status" options={['Atrasada', 'A vencer', 'Atenção', 'Segura']} value={filters.status} onChange={e => setFilter('status', e.target.value)} /></Field>
          <Field label="Tipo de manutenção"><Select placeholder="Todos os tipos" options={SCHEDULED_TYPES} value={filters.type} onChange={e => setFilter('type', e.target.value)} /></Field>
          <Field label="Manutenção"><Select placeholder="Todas as manutenções" options={MAINTENANCES.map(m => m.name)} value={filters.maintenance} onChange={e => setFilter('maintenance', e.target.value)} /></Field>
          <Field label="Fazenda"><Select placeholder="Todas as fazendas" options={FARMS.map(f => f.name)} value={filters.farm} onChange={e => setFilter('farm', e.target.value)} /></Field>
        </div>
        {state === 'loading' ? <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 24 }}>{TOT_STYLE.map(t => <div key={t.key} style={{ height: 148, borderRadius: 8, background: 'var(--color-neutral-light-200)' }} />)}</div> : (
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 24 }}>
            {TOT_STYLE.map(t => (
              <div key={t.key} style={{ background: t.bg, borderRadius: 'var(--border-radius-default)', boxShadow: 'var(--shadow-card-default)', padding: '16px 24px' }}>
                <div style={{ fontSize: 20, fontWeight: 600, color: 'var(--color-grayish-dark)', borderBottom: '1px solid var(--color-neutral-200)', paddingBottom: 4, marginBottom: 4 }}>{t.label}</div>
                <div style={{ fontSize: 64, fontWeight: 700, lineHeight: 1.2, color: t.fg }}>{totals[t.key]}</div>
              </div>
            ))}
          </div>
        )}
      </Panel>

      <Panel>
        {state === 'loading' ? <SkeletonRows rows={7} height={26} />
          : rows.length === 0 ? <EmptyState message="Nenhuma manutenção programada encontrada." />
            : (
              <React.Fragment>
                <TableFrame>
                  <thead><tr><Th>Status</Th><Th>Tipo de manutenção</Th><Th>Maquinário</Th><Th>Modelo</Th><Th>Fazenda</Th><Th>Manutenção</Th><Th sortable={false} /></tr></thead>
                  <tbody>
                    {rows.map((r, i) => (
                      <Row key={r.id} i={i}>
                        <Td><StatusChip status={r.status} /></Td>
                        <Td><TypeChip type={r.type} variant="text" /></Td>
                        <Td style={{ maxWidth: 240, whiteSpace: 'normal' }}>{window.MAQ.MACHINERY.some(x => x.name === r.machinery)
                          ? <a href="#" onClick={e => { e.preventDefault(); onOpenMachinery && onOpenMachinery(r.machinery) }}>{r.machinery}</a>
                          : r.machinery}</Td>
                        <Td style={{ maxWidth: 150, whiteSpace: 'normal' }}>{r.model}</Td>
                        <Td>{r.farm}</Td>
                        <Td style={{ maxWidth: 230, whiteSpace: 'normal' }}>{r.maintenance}</Td>
                        <Td style={{ textAlign: 'right' }}><Btn type="outline" size="small" style={{ minWidth: 148 }} label={r.type === 'Garantia' ? 'Registrar' : 'Renovar'} icon={r.type === 'Garantia' ? 'add-circle-outline' : 'renew'} upper onClick={() => onRegister(r)} /></Td>
                      </Row>
                    ))}
                  </tbody>
                </TableFrame>
                <Pagination pages={3} page={1} />
              </React.Fragment>
            )}
      </Panel>
    </React.Fragment>
  )
}

const C = { overdue: 'var(--color-danger)', dueSoon: 'var(--color-warning)', attention: 'var(--color-alert)', safe: 'var(--color-success)' }

const FARM_OPTIONS = ['Guanabara', 'Mateira', 'Paranapanema']

function ChartHead({ title, farm, onFarm, maintType, onMaintType }) {
  const { BlockTitle, Field, Select } = window
  return (
    <React.Fragment>
      <BlockTitle style={{ marginBottom: 20 }}>{title}</BlockTitle>
      <div style={{ display: 'flex', gap: 20, flexWrap: 'wrap' }}>
        <div style={{ flex: 1, minWidth: 240 }}>
          <Field label="Fazenda"><Select placeholder="Todas as fazendas" options={FARM_OPTIONS} value={farm} onChange={e => onFarm(e.target.value)} /></Field>
        </div>
        {onMaintType && (
          <div style={{ flex: 1, minWidth: 240 }}>
            <Field label="Tipo de manutenção"><Select placeholder="Todos os tipos" options={window.MAQ.SCHEDULED_TYPES} value={maintType} onChange={e => onMaintType(e.target.value)} /></Field>
          </div>
        )}
      </div>
    </React.Fragment>
  )
}

function useTip() {
  const [tip, setTip] = React.useState(null)
  const show = (e, title, rows) => {
    const box = e.currentTarget.closest('[data-tipwrap]')
    if (!box) return
    const r = box.getBoundingClientRect()
    setTip({ x: e.clientX - r.left, y: e.clientY - r.top, title, rows: rows || [] })
  }
  return [tip, show, () => setTip(null)]
}

function ChartTip({ tip }) {
  if (!tip) return null
  const flip = tip.x > 520
  return (
    <div style={{ position: 'absolute', left: flip ? undefined : tip.x + 18, right: flip ? 'calc(100% - ' + (tip.x - 18) + 'px)' : undefined, top: tip.y + 10,
      zIndex: 5, pointerEvents: 'none', background: '#fff', borderRadius: 'var(--border-radius-default)', boxShadow: '0 12px 34px rgba(0,0,0,0.16)', padding: '14px 18px', minWidth: 170 }}>
      <div style={{ fontSize: 15, fontWeight: 500, color: 'var(--color-grayish-dark)', marginBottom: tip.rows.length ? 12 : 0, whiteSpace: 'nowrap' }}>{tip.title}</div>
      <div style={{ display: 'grid', gap: 10 }}>
        {tip.rows.map(r => (
          <div key={r.name} style={{ display: 'grid', gap: 2 }}>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8, fontSize: 13, color: 'var(--color-grayish)', whiteSpace: 'nowrap' }}>
              {r.color && <span style={{ width: 10, height: 10, borderRadius: '50%', background: r.color, flex: '0 0 auto' }} />}{r.name}</span>
            <span style={{ fontSize: 15, fontWeight: 600, color: 'var(--color-grayish-dark)', paddingLeft: r.color ? 18 : 0 }}>{r.value}</span>
          </div>
        ))}
      </div>
    </div>
  )
}

function SideLegend({ items, total }) {
  return (
    <div style={{ minWidth: 230, display: 'grid', gap: 14, alignContent: 'start', paddingTop: 8 }}>
      {items.map(i => (
        <div key={i.name} style={{ display: 'flex', alignItems: 'center', gap: 12, fontSize: 15, color: 'var(--color-grayish)' }}>
          <span style={{ width: 11, height: 11, borderRadius: '50%', background: i.color, flex: '0 0 auto' }} />
          <span style={{ flex: 1 }}>{i.name}</span>
          <span style={{ fontWeight: 500, color: 'var(--color-grayish-dark)' }}>{i.value}</span>
        </div>
      ))}
      {total != null && (
        <div style={{ display: 'flex', borderTop: '1px solid var(--color-neutral-100)', paddingTop: 14, fontSize: 15, fontWeight: 500, color: 'var(--color-grayish-dark)' }}>
          <span style={{ flex: 1 }}>Total</span><span>{total}</span>
        </div>
      )}
    </div>
  )
}

function BottomLegend({ items }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'center', flexWrap: 'wrap', gap: 28, marginTop: 24 }}>
      {items.map(i => (
        <span key={i.name} style={{ display: 'inline-flex', alignItems: 'center', gap: 9, fontSize: 14, color: 'var(--color-grayish)' }}>
          <span style={{ width: 11, height: 11, borderRadius: '50%', background: i.color }} />{i.name}
        </span>
      ))}
    </div>
  )
}

// Colunas verticais com eixo Y e grade tracejada
function ColumnChart({ series, max, ticks, axis = 'Quantidade' }) {
  const H = 320
  const [tip, show, hide] = useTip()
  return (
    <div data-tipwrap style={{ position: 'relative', display: 'flex', gap: 14 }} onMouseLeave={hide}>
      <ChartTip tip={tip} />
      <div style={{ display: 'flex', gap: 10 }}>
        <span style={{ writingMode: 'vertical-rl', transform: 'rotate(180deg)', alignSelf: 'center', fontSize: 13, color: 'var(--color-grayish-light)' }}>{axis}</span>
        <div style={{ height: H, display: 'flex', flexDirection: 'column', justifyContent: 'space-between', alignItems: 'flex-end', fontSize: 13, color: 'var(--color-grayish-light)' }}>
          {[...ticks].reverse().map(t => <span key={t}>{t}</span>)}
        </div>
      </div>
      <div style={{ flex: 1 }}>
        <div style={{ position: 'relative', height: H, borderLeft: '1px solid var(--color-neutral-200)', borderBottom: '1px solid var(--color-neutral-200)' }}>
          {ticks.slice(1).map(t => (
            <span key={t} style={{ position: 'absolute', left: 0, right: 0, bottom: (t / max * 100) + '%', borderTop: '1px dashed var(--color-neutral-100)' }} />
          ))}
          <div style={{ position: 'absolute', inset: 0, display: 'grid', gridTemplateColumns: 'repeat(' + series.length + ', 1fr)', alignItems: 'end', justifyItems: 'center' }}>
            {series.map(p => (
              <span key={p.name} onMouseMove={e => show(e, p.name, [{ name: p.name, value: p.value, color: p.color }])}
                style={{ width: 84, height: Math.max(p.value / max * 100, 0.6) + '%', background: p.color, cursor: 'default' }} />
            ))}
          </div>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(' + series.length + ', 1fr)', marginTop: 10, fontSize: 14, color: 'var(--color-grayish)' }}>
          {series.map(p => <span key={p.name} style={{ textAlign: 'center' }}>{p.name}</span>)}
        </div>
      </div>
    </div>
  )
}

// Barras horizontais empilhadas com eixo X
function StackedBars({ rows, keys, max, ticks }) {
  const [tip, show, hide] = useTip()
  return (
    <div data-tipwrap style={{ position: 'relative' }} onMouseLeave={hide}>
      <ChartTip tip={tip} />
      <div style={{ display: 'grid', gridTemplateColumns: '160px 1fr', gap: '14px 16px', alignItems: 'center' }}>
        {rows.map(r => {
          const segs = keys.filter(k => r[k.key] > 0)
          return (
            <React.Fragment key={r.label}>
              <span style={{ fontSize: 14, color: 'var(--color-grayish)', textAlign: 'right', textWrap: 'pretty' }}>{r.label}</span>
              <div style={{ position: 'relative', height: 34, borderLeft: '1px solid var(--color-neutral-200)' }}>
                {ticks.slice(1).map(t => <span key={t} style={{ position: 'absolute', top: 0, bottom: 0, left: (t / max * 100) + '%', borderLeft: '1px dashed var(--color-neutral-100)' }} />)}
                <div style={{ position: 'absolute', inset: 0, display: 'flex' }}>
                  {segs.map(k => <span key={k.key} onMouseMove={e => show(e, r.label, segs.map(x => ({ name: x.name, value: r[x.key], color: x.color })))}
                    style={{ width: (r[k.key] / max * 100) + '%', background: k.color, cursor: 'default' }} />)}
                </div>
              </div>
            </React.Fragment>
          )
        })}
        <span />
        <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13, color: 'var(--color-grayish-light)', paddingTop: 8 }}>
          {ticks.map(t => <span key={t}>{t}</span>)}
        </div>
      </div>
    </div>
  )
}

function Donut({ slices, total }) {
  const [tip, show, hide] = useTip()
  const W = 760, H = 460, cx = 300, cy = 230, R = 126, r = 70
  const pt = (rad, ang) => [cx + rad * Math.cos(ang), cy + rad * Math.sin(ang)]
  const GAP = 0.012
  let acc = 0
  let small = 0
  const arcs = slices.map(s2 => {
    const a0 = (acc / total) * Math.PI * 2 - Math.PI / 2 + GAP
    acc += s2.value
    const a1 = (acc / total) * Math.PI * 2 - Math.PI / 2 - GAP
    const mid = (a0 + a1) / 2
    const large = a1 - a0 > Math.PI ? 1 : 0
    const [x0, y0] = pt(R, a0), [x1, y1] = pt(R, a1), [x2, y2] = pt(r, a1), [x3, y3] = pt(r, a0)
    // fatias pequenas ganham "leader" mais longo, alternado, para os rótulos não colidirem
    const tiny = s2.value / total < 0.08
    const reach = tiny ? 44 + (small++ % 2) * 34 : 30
    const [lx0, ly0] = pt(R + 4, mid)
    const [lx1, ly1] = pt(R + reach, mid)
    const right = Math.cos(mid) >= 0
    const lx2 = right ? lx1 + 24 : lx1 - 24
    return { ...s2, right, lx0, ly0, lx1, ly1, lx2,
      d: 'M' + x0 + ' ' + y0 + ' A' + R + ' ' + R + ' 0 ' + large + ' 1 ' + x1 + ' ' + y1 + ' L' + x2 + ' ' + y2 + ' A' + r + ' ' + r + ' 0 ' + large + ' 0 ' + x3 + ' ' + y3 + ' Z' }
  })
  return (
    <div data-tipwrap style={{ position: 'relative', width: '100%', maxWidth: W, margin: '0 auto', aspectRatio: W + ' / ' + H }} onMouseLeave={hide}>
      <ChartTip tip={tip} />
      <svg viewBox={'0 0 ' + W + ' ' + H} preserveAspectRatio="xMidYMid meet" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%' }}>
        {arcs.map(a => (
          <g key={a.name}>
            <path d={a.d} fill={a.color} onMouseMove={e => show(e, a.name, [{ name: a.name, value: a.value, color: a.color }])} style={{ cursor: 'default' }} />
            <polyline points={a.lx0 + ',' + a.ly0 + ' ' + a.lx1 + ',' + a.ly1 + ' ' + a.lx2 + ',' + a.ly1} fill="none" stroke="var(--color-neutral-300)" strokeWidth="1" vectorEffect="non-scaling-stroke" />
          </g>
        ))}
      </svg>
      {arcs.map(a => (
        <span key={a.name} style={{ position: 'absolute', top: (a.ly1 / H * 100) + '%', transform: 'translateY(-50%)',
          left: a.right ? (a.lx2 / W * 100) + '%' : 0, right: a.right ? 0 : (100 - a.lx2 / W * 100) + '%',
          textAlign: a.right ? 'left' : 'right', paddingLeft: a.right ? 6 : 0, paddingRight: a.right ? 0 : 6,
          fontSize: 13, lineHeight: 1.25, color: 'var(--color-grayish)', textWrap: 'pretty', pointerEvents: 'none' }}>{a.name}: {a.value}</span>
      ))}
    </div>
  )
}

function StatusTab() {
  const { Panel } = window
  const { STATUS_BY_TYPE, TOTALIZERS } = window.MAQ
  const [farmA, setFarmA] = React.useState('')
  const [farmB, setFarmB] = React.useState('')
  const [farmC, setFarmC] = React.useState('')
  const [mtA, setMtA] = React.useState('')
  const [mtB, setMtB] = React.useState('')
  const [mtC, setMtC] = React.useState('')

  const crit = [
    { name: 'Segura', value: TOTALIZERS.safe, color: C.safe },
    { name: 'Atenção', value: TOTALIZERS.attention, color: C.attention },
    { name: 'A vencer', value: TOTALIZERS.dueSoon, color: C.dueSoon },
    { name: 'Atrasada', value: TOTALIZERS.overdue, color: C.overdue },
  ]
  const critTotal = crit.reduce((a, b) => a + b.value, 0)

  const statusKeys = [{ key: 'safe', name: 'Segura', color: C.safe }, { key: 'attention', name: 'Atenção', color: C.attention },
    { key: 'dueSoon', name: 'A vencer', color: C.dueSoon }, { key: 'overdue', name: 'Atrasada', color: C.overdue }]
  const byType = [...STATUS_BY_TYPE].sort((a, b) => (b.safe + b.attention + b.dueSoon + b.overdue) - (a.safe + a.attention + a.dueSoon + a.overdue))
  const maxType = Math.max(...byType.map(r => r.safe + r.attention + r.dueSoon + r.overdue))
  const maxRounded = Math.ceil(maxType / 5) * 5

  const DONUT = window.MAQ.CHART_PALETTE
  const pieSlices = byType.map((r, i) => ({ name: r.label, value: r.safe + r.attention + r.dueSoon + r.overdue, color: DONUT[i % DONUT.length] }))
  const pieTotal = pieSlices.reduce((a, b) => a + b.value, 0)

  return (
    <div style={{ display: 'grid', gap: 32 }}>
      <Panel>
        <ChartHead title="Manutenções pendentes por criticidade" farm={farmA} onFarm={setFarmA} maintType={mtA} onMaintType={setMtA} />
        <div style={{ display: 'flex', gap: 40, marginTop: 28, flexWrap: 'wrap' }}>
          <div style={{ flex: 1, minWidth: 420 }}>
            <ColumnChart series={crit} max={Math.ceil(critTotal / 20) * 20} ticks={[0, 15, 30, 45, 60]} />
          </div>
          <SideLegend items={crit} total={critTotal} />
        </div>
      </Panel>

      <Panel>
        <ChartHead title="Classificação de tipos maquinários por status" farm={farmB} onFarm={setFarmB} maintType={mtB} onMaintType={setMtB} />
        <div style={{ marginTop: 28 }}>
          <StackedBars rows={byType} keys={statusKeys} max={maxRounded} ticks={[0, 5, 10, 15, 20].filter(t => t <= maxRounded)} />
          <BottomLegend items={statusKeys} />
        </div>
      </Panel>

      <Panel>
        <ChartHead title="Manutenções pendentes por tipo de maquinário" farm={farmC} onFarm={setFarmC} maintType={mtC} onMaintType={setMtC} />
        <div style={{ display: 'flex', gap: 40, marginTop: 28, flexWrap: 'wrap', alignItems: 'center' }}>
          <div style={{ flex: 1, minWidth: 420 }}><Donut slices={pieSlices} total={pieTotal} /></div>
          <SideLegend items={pieSlices} total={pieTotal} />
        </div>
      </Panel>
    </div>
  )
}

function PeriodFilters({ withPeriod, withType, farm, onFarm, type, onType, from = '2026-08-08', to = '2026-09-07' }) {
  const { Field, Select, Input } = window
  return (
    <div style={{ display: 'flex', gap: 20, flexWrap: 'wrap', alignItems: 'flex-end' }}>
      {withPeriod && (
        <div style={{ display: 'grid', gap: 8 }}>
          <span style={{ fontSize: 13, fontWeight: 500, color: 'var(--color-grayish-dark)' }}>Período</span>
          <div style={{ display: 'flex', gap: 12 }}>
            <div style={{ width: 180 }}><Input type="date" defaultValue={from} /></div>
            <div style={{ width: 180 }}><Input type="date" defaultValue={to} /></div>
          </div>
        </div>
      )}
      {withType && (
        <div style={{ flex: 1, minWidth: 240 }}>
          <Field label="Tipo de Maquinário"><Select placeholder="Todos os tipos" options={window.MAQ.MACHINERY_TYPES} value={type} onChange={e => onType(e.target.value)} /></Field>
        </div>
      )}
      <div style={{ flex: 1, minWidth: 240 }}>
        <Field label="Fazenda"><Select placeholder="Todas as fazendas" options={FARM_OPTIONS} value={farm} onChange={e => onFarm(e.target.value)} /></Field>
      </div>
    </div>
  )
}

function PanelHead({ title, subtitle }) {
  return (
    <div style={{ marginBottom: 20 }}>
      <h2 style={{ margin: 0, fontSize: 22, fontWeight: 600, color: 'var(--color-grayish-dark)' }}>{title}</h2>
      {subtitle && <p style={{ margin: '6px 0 0', fontSize: 14, color: 'var(--color-grayish-light)' }}>{subtitle}</p>}
    </div>
  )
}

// Colunas agrupadas por mês (corretiva / preventiva)
function GroupedColumns({ rows, keys, max, ticks, axis = 'Quantidade' }) {
  const H = 300
  const [tip, show, hide] = useTip()
  return (
    <div data-tipwrap style={{ position: 'relative', display: 'flex', gap: 12 }} onMouseLeave={hide}>
      <ChartTip tip={tip} />
      <div style={{ display: 'flex', gap: 10 }}>
        <span style={{ writingMode: 'vertical-rl', transform: 'rotate(180deg)', alignSelf: 'center', fontSize: 13, color: 'var(--color-grayish-light)' }}>{axis}</span>
        <div style={{ height: H, display: 'flex', flexDirection: 'column', justifyContent: 'space-between', alignItems: 'flex-end', fontSize: 13, color: 'var(--color-grayish-light)' }}>
          {[...ticks].reverse().map(t => <span key={t}>{t}</span>)}
        </div>
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ position: 'relative', height: H, borderLeft: '1px solid var(--color-neutral-200)', borderBottom: '1px solid var(--color-neutral-200)' }}>
          {ticks.slice(1).map(t => <span key={t} style={{ position: 'absolute', left: 0, right: 0, bottom: (t / max * 100) + '%', borderTop: '1px dashed var(--color-neutral-100)' }} />)}
          <div style={{ position: 'absolute', inset: 0, display: 'grid', gridTemplateColumns: 'repeat(' + rows.length + ', 1fr)', alignItems: 'end' }}>
            {rows.map(r => (
              <span key={r.label} onMouseMove={e => show(e, r.label, keys.map(k => ({ name: k.name, value: r[k.key] || 0, color: k.color })))}
                style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'center', gap: 3, height: '100%', cursor: 'default' }}>
                {keys.map(k => r[k.key] > 0 && <span key={k.key} style={{ width: 11, height: (r[k.key] / max * 100) + '%', background: k.color }} />)}
              </span>
            ))}
          </div>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(' + rows.length + ', 1fr)', marginTop: 10, fontSize: 13, color: 'var(--color-grayish)' }}>
          {rows.map(r => <span key={r.label} style={{ textAlign: 'center' }}>{r.label}</span>)}
        </div>
      </div>
    </div>
  )
}

// Barras horizontais simples (uma cor por item)
function RankBars({ rows, max, ticks, axisLabel }) {
  const [tip, show, hide] = useTip()
  return (
    <div data-tipwrap style={{ position: 'relative', display: 'grid', gridTemplateColumns: '200px 1fr', gap: '16px 16px', alignItems: 'center' }} onMouseLeave={hide}>
      <ChartTip tip={tip} />
      {rows.map(r => (
        <React.Fragment key={r.label}>
          <span style={{ fontSize: 13, color: 'var(--color-grayish)', textAlign: 'right', textWrap: 'pretty' }}>{r.label}</span>
          <div style={{ position: 'relative', height: 38, borderLeft: '1px solid var(--color-neutral-200)' }}>
            {ticks.slice(1).map(t => <span key={t} style={{ position: 'absolute', top: 0, bottom: 0, left: (t / max * 100) + '%', borderLeft: '1px dashed var(--color-neutral-100)' }} />)}
            <span onMouseMove={e => show(e, r.label, [{ name: r.label, value: r.value.toLocaleString('pt-BR') + (r.unit ? ' ' + r.unit : ''), color: r.color }])}
              style={{ position: 'absolute', top: 0, bottom: 0, left: 0, width: (r.value / max * 100) + '%', background: r.color, cursor: 'default' }} />
          </div>
        </React.Fragment>
      ))}
      <span />
      <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13, color: 'var(--color-grayish-light)' }}>
        {ticks.map(t => <span key={t}>{t.toLocaleString('pt-BR')}</span>)}
      </div>
      {axisLabel && <React.Fragment><span /><span style={{ textAlign: 'center', fontSize: 13, color: 'var(--color-grayish-light)', paddingTop: 6 }}>{axisLabel}</span></React.Fragment>}
    </div>
  )
}

// Linhas de uso mensal (SVG)
function LineChart({ months, series, max, ticks }) {
  const W = 1000, H = 300
  const x = i => (i / (months.length - 1)) * W
  const y = v => H - (v / max) * H
  const [tip, show, hide] = useTip()
  return (
    <div data-tipwrap style={{ position: 'relative', display: 'flex', gap: 12 }} onMouseLeave={hide}>
      <ChartTip tip={tip} />
      <div style={{ display: 'flex', gap: 10 }}>
        <span style={{ writingMode: 'vertical-rl', transform: 'rotate(180deg)', alignSelf: 'center', fontSize: 13, color: 'var(--color-grayish-light)' }}>Horas/KM</span>
        <div style={{ height: H, display: 'flex', flexDirection: 'column', justifyContent: 'space-between', alignItems: 'flex-end', fontSize: 13, color: 'var(--color-grayish-light)' }}>
          {[...ticks].reverse().map(t => <span key={t}>{t.toLocaleString('pt-BR')}</span>)}
        </div>
      </div>
      <div style={{ flex: 1, minWidth: 0, position: 'relative' }}>
        <svg viewBox={'0 0 ' + W + ' ' + H} preserveAspectRatio="none" style={{ width: '100%', height: H, borderLeft: '1px solid var(--color-neutral-200)', borderBottom: '1px solid var(--color-neutral-200)', overflow: 'visible' }}>
          {ticks.slice(1).map(t => <line key={t} x1="0" x2={W} y1={y(t)} y2={y(t)} stroke="var(--color-neutral-100)" strokeDasharray="4 6" />)}
          {series.map(s => (
            <polyline key={s.label} fill="none" stroke={s.color} strokeWidth="2.5" vectorEffect="non-scaling-stroke"
              points={s.values.map((v, i) => x(i) + ',' + y(v)).join(' ')} />
          ))}
        </svg>
        <div style={{ position: 'absolute', inset: 0, display: 'grid', gridTemplateColumns: 'repeat(' + months.length + ', 1fr)' }}>
          {months.map((m, i) => (
            <span key={m} onMouseMove={e => show(e, m, series.map(sr => ({ name: sr.label + ' - ' + (sr.unit === 'h' ? 'H' : 'KM'), value: sr.values[i].toLocaleString('pt-BR') + ' ' + sr.unit, color: sr.color })))}
              style={{ cursor: 'default' }} />
          ))}
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 10, fontSize: 13, color: 'var(--color-grayish)' }}>
          {months.map(m => <span key={m}>{m}</span>)}
        </div>
      </div>
    </div>
  )
}

function FlowTab() {
  const { Panel } = window
  const { MONTHLY_BY_TYPE, TOP_FAILURES, FAILURE_COLORS, USAGE_MONTHS, USAGE_BY_TYPE, TOTALIZERS } = window.MAQ
  const [f1, setF1] = React.useState('')
  const [f2, setF2] = React.useState('')
  const [f3, setF3] = React.useState('')
  const [f4, setF4] = React.useState('')

  const TS = window.TYPE_STYLE
  const typeKeys = [
    { key: 'preventive', name: 'Preventiva', color: TS['Preventiva'].bg },
    { key: 'periodic', name: 'Periódica', color: TS['Periódica'].bg },
    { key: 'warranty', name: 'Garantia', color: TS['Garantia'].bg },
    { key: 'corrective', name: 'Corretiva', color: TS['Corretiva'].bg },
  ]
  const sumOf = k => MONTHLY_BY_TYPE.reduce((a, b) => a + (b[k] || 0), 0)
  const grandTotal = typeKeys.reduce((a, k) => a + sumOf(k.key), 0)
  const pct = v => Math.round(v / grandTotal * 100) + '%'

  const prazo = [
    { name: 'Segura', value: TOTALIZERS.safe, color: C.safe },
    { name: 'Atenção', value: TOTALIZERS.attention, color: C.attention },
    { name: 'A vencer', value: TOTALIZERS.dueSoon, color: C.dueSoon },
    { name: 'Atrasada', value: TOTALIZERS.overdue, color: C.overdue },
  ]
  const prazoTotal = prazo.reduce((a, b) => a + b.value, 0)

  const failures = TOP_FAILURES.map((f, i) => ({ ...f, color: FAILURE_COLORS[i % FAILURE_COLORS.length] }))
  const maxFail = Math.ceil(Math.max(...failures.map(f => f.value)) / 4) * 4
  const failTicks = [0, maxFail / 4, maxFail / 2, maxFail * 3 / 4, maxFail]

  const usageMax = 200000

  return (
    <div style={{ display: 'grid', gap: 32 }}>
      <Panel>
        <PanelHead title="Histórico de manutenções realizadas" subtitle="Tendência mensal dos últimos 12 meses" />
        <PeriodFilters farm={f1} onFarm={setF1} />
        <div style={{ marginTop: 28 }}>
          <GroupedColumns rows={MONTHLY_BY_TYPE} keys={typeKeys} max={24} ticks={[0, 6, 12, 18, 24]} />
          <BottomLegend items={typeKeys.map(k => ({ name: k.name + ' (' + pct(sumOf(k.key)) + ')', color: k.color }))} />
        </div>
      </Panel>

      <Panel>
        <PanelHead title="Cumprimento do prazo das manutenções" />
        <PeriodFilters withPeriod farm={f2} onFarm={setF2} />
        <div style={{ display: 'flex', gap: 40, marginTop: 28, flexWrap: 'wrap' }}>
          <div style={{ flex: 1, minWidth: 420 }}>
            <ColumnChart series={prazo} max={Math.ceil(prazoTotal / 20) * 20} ticks={[0, 15, 30, 45, 60]} />
          </div>
          <SideLegend items={prazo} total={prazoTotal} />
        </div>
      </Panel>

      <Panel>
        <PanelHead title="Top 5 tipos de falhas" subtitle="Manutenções corretivas mais frequentes" />
        <PeriodFilters withPeriod farm={f3} onFarm={setF3} />
        <div style={{ marginTop: 28 }}>
          <RankBars rows={failures} max={maxFail} ticks={failTicks} />
        </div>
      </Panel>

      <Panel>
        <PanelHead title="Histórico mensal de uso por tipo de maquinário (KM/Horímetro)" subtitle="Tendência mensal dos últimos 12 meses" />
        <PeriodFilters withPeriod farm={f4} onFarm={setF4} />
        <div style={{ marginTop: 28 }}>
          <LineChart months={USAGE_MONTHS} series={USAGE_BY_TYPE} max={usageMax} ticks={[0, 50000, 100000, 150000, 200000]} />
          <BottomLegend items={USAGE_BY_TYPE.map(s => ({ name: s.label, color: s.color }))} />
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(190px, 1fr))', gap: 16, marginTop: 28 }}>
            {USAGE_BY_TYPE.map(s => (
              <div key={s.label} style={{ background: 'var(--color-background-dark-1)', borderRadius: 'var(--border-radius-default)', padding: '16px 18px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12 }}>
                <span style={{ display: 'inline-flex', alignItems: 'center', gap: 9, fontSize: 14, fontWeight: 500, color: 'var(--color-grayish-dark)' }}>
                  <span style={{ width: 9, height: 9, borderRadius: '50%', background: s.color, flex: '0 0 auto' }} />{s.label}
                </span>
                <span style={{ fontSize: 16, fontWeight: 600, color: 'var(--color-grayish-dark)', whiteSpace: 'nowrap' }}>{s.total.toLocaleString('pt-BR')} {s.unit}</span>
              </div>
            ))}
          </div>
        </div>
      </Panel>
    </div>
  )
}

function ActiveTab() {
  const { Panel } = window
  const { FLEET_COMPOSITION, TOP_BY_MAINTENANCE, TOP_BY_USAGE, CHART_PALETTE } = window.MAQ
  const [farmA, setFarmA] = React.useState('')
  const [farmB, setFarmB] = React.useState('')
  const [farmC, setFarmC] = React.useState('')
  const [typeB, setTypeB] = React.useState('')
  const [typeC, setTypeC] = React.useState('')

  const fleet = [...FLEET_COMPOSITION].sort((a, b) => b.value - a.value)
    .map((f, i) => ({ name: f.label, value: f.value, color: CHART_PALETTE[i % CHART_PALETTE.length] }))
  const fleetMax = Math.ceil(Math.max(...fleet.map(f => f.value)) / 4) * 4

  const TS = window.TYPE_STYLE
  const maintKeys = [
    { key: 'preventive', name: 'Preventivas', color: TS['Preventiva'].bg },
    { key: 'periodic', name: 'Periódicas', color: TS['Periódica'].bg },
    { key: 'warranty', name: 'Garantias', color: TS['Garantia'].bg },
    { key: 'corrective', name: 'Corretivas', color: TS['Corretiva'].bg },
  ]
  const volume = [...TOP_BY_MAINTENANCE].sort((a, b) => b.value - a.value)
  const volMax = Math.ceil(Math.max(...volume.map(m => m.value)) / 4) * 4

  const usage = TOP_BY_USAGE.map((m, i) => ({ ...m, color: CHART_PALETTE[i % CHART_PALETTE.length] }))
  const useMax = 6000

  return (
    <div style={{ display: 'grid', gap: 32 }}>
      <Panel>
        <PanelHead title="Composição da Frota" />
        <PeriodFilters farm={farmA} onFarm={setFarmA} />
        <div style={{ marginTop: 28 }}>
          <ColumnChart series={fleet} max={fleetMax} ticks={[0, fleetMax / 4, fleetMax / 2, fleetMax * 3 / 4, fleetMax]} />
        </div>
      </Panel>

      <Panel>
        <PanelHead title="Maquinários com Maior Volume de Manutenção" />
        <PeriodFilters withPeriod withType farm={farmB} onFarm={setFarmB} type={typeB} onType={setTypeB} from="2026-08-01" to="2026-09-30" />
        <div style={{ marginTop: 28 }}>
          <StackedBars rows={volume} keys={maintKeys} max={volMax} ticks={[0, volMax / 4, volMax / 2, volMax * 3 / 4, volMax]} />
          <BottomLegend items={maintKeys} />
        </div>
      </Panel>

      <Panel>
        <PanelHead title="Top 10 Maquinários Mais Utilizados" />
        <PeriodFilters withPeriod withType farm={farmC} onFarm={setFarmC} type={typeC} onType={setTypeC} from="2026-09-01" to="2026-09-30" />
        <div style={{ marginTop: 28 }}>
          <RankBars rows={usage} max={useMax} ticks={[0, 1500, 3000, 4500, 6000]} axisLabel="Quilometragem / Horímetro" />
        </div>
      </Panel>
    </div>
  )
}

function DashboardPage({ state, tab, onTab, onRegister, onOpenMachinery, hideTabs }) {
  const { NEXT_MAINTENANCES, TOTALIZERS } = window.MAQ
  const [filters, setFilters] = React.useState({ status: '', maintenance: '', farm: '', type: '' })
  const setFilter = (k, v) => setFilters(f => ({ ...f, [k]: v }))
  const STATUS_ORDER = { 'Atrasada': 0, 'A vencer': 1, 'Atenção': 2, 'Segura': 3 }
  let rows = state === 'empty' ? [] : NEXT_MAINTENANCES
  if (filters.type) rows = rows.filter(r => r.type === filters.type)
  if (filters.status) rows = rows.filter(r => r.status === filters.status)
  if (filters.maintenance) rows = rows.filter(r => r.maintenance === filters.maintenance)
  if (filters.farm) rows = rows.filter(r => r.farm === filters.farm)
  rows = [...rows].sort((a, b) => STATUS_ORDER[a.status] - STATUS_ORDER[b.status])
  return (
    <React.Fragment>
      {!hideTabs && <Tabs active={tab} onChange={onTab} tabs={[
        { key: 'next', label: 'Próximas manutenções' }, { key: 'status', label: 'Status' }, { key: 'flow', label: 'Fluxo' }, { key: 'active', label: 'Ativos' }]} />}
      {tab === 'next' && <NextMaintenances state={state} onOpenMachinery={onOpenMachinery} rows={rows} totals={TOTALIZERS} onRegister={onRegister} filters={filters} setFilter={setFilter} />}
      {tab === 'status' && <StatusTab />}
      {tab === 'flow' && <FlowTab />}
      {tab === 'active' && <ActiveTab />}
    </React.Fragment>
  )
}

Object.assign(window, { DashboardPage, Tabs })
