// Caririaçu Guincho — Componentes compartilhados das tabs de Frota

const { useState: useStateCF, useEffect: useEffectCF, useRef: useRefCF } = React;

// ── MetricCard ─────────────────────────────────────────────────
const MetricCard = ({ label, total, porDia, porKm, color = '#0F172A' }) => (
  <div style={{
    background: '#fff', border: '1px solid #E2E8F0', borderRadius: 10,
    padding: 12, display: 'flex', flexDirection: 'column', gap: 4
  }}>
    <div style={{ fontSize: 10, color: '#64748B', textTransform: 'uppercase',
                  letterSpacing: 0.5, fontWeight: 600 }}>{label}</div>
    <div style={{ fontSize: 18, fontWeight: 700, color }}>{fmtBRL(total)}</div>
    {(porDia != null || porKm != null) && (
      <div style={{ fontSize: 10, color: '#94A3B8', marginTop: 2 }}>
        {porDia != null && <div>{fmtBRL(porDia)} / dia</div>}
        {porKm != null && <div>{fmtBRL(porKm)} / km</div>}
      </div>
    )}
  </div>
);

// ── FabAdicionar ──────────────────────────────────────────────
const FabAdicionar = ({ onClick, icon = '+' }) => (
  <button onClick={onClick} style={{
    position: 'fixed', right: 'calc(20px + var(--safe-right))',
    bottom: 'calc(20px + var(--safe-bottom))',
    width: 56, height: 56, borderRadius: '50%', border: 'none', cursor: 'pointer',
    background: '#F59E0B', color: '#fff', fontSize: 28, fontWeight: 300,
    boxShadow: '0 6px 16px rgba(245,158,11,0.4)', zIndex: 50
  }}>{icon}</button>
);

// ── PeriodoPicker ─────────────────────────────────────────────
// Default: últimos 6 meses
const PeriodoPicker = ({ inicio, fim, onChange, total }) => {
  const [open, setOpen] = useStateCF(false);
  const fmt = d => new Date(d).toLocaleDateString('pt-BR');
  return (
    <div style={{
      background: '#fff', padding: '10px 14px', borderBottom: '1px solid #F1F5F9',
      display: 'flex', alignItems: 'center', justifyContent: 'space-between', fontSize: 12
    }}>
      <div style={{ color: '#64748B' }}>
        {total != null && <strong style={{ color: '#0F172A' }}>{total} registros · </strong>}
        {fmt(inicio)} — {fmt(fim)}
      </div>
      <button onClick={() => setOpen(true)} style={{
        background: 'none', border: 'none', color: '#3B82F6', fontWeight: 600,
        fontSize: 12, cursor: 'pointer'
      }}>📅 Filtrar</button>
      {open && (
        <Modal open={open} onClose={() => setOpen(false)} title="Filtrar período" width={360}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
            <Input label="De" type="date" value={inicio}
                   onChange={e => onChange({ inicio: e.target.value, fim })} />
            <Input label="Até" type="date" value={fim}
                   onChange={e => onChange({ inicio, fim: e.target.value })} />
            <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
              {[
                { label: 'Mês atual', dias: 30 },
                { label: 'Últimos 3 meses', dias: 90 },
                { label: 'Últimos 6 meses', dias: 180 },
                { label: 'Último ano', dias: 365 },
              ].map(p => (
                <button key={p.label} onClick={() => {
                  const f = new Date(); const i = new Date(); i.setDate(i.getDate() - p.dias);
                  onChange({ inicio: i.toISOString().slice(0, 10), fim: f.toISOString().slice(0, 10) });
                }} style={{
                  padding: '6px 10px', border: '1px solid #E2E8F0', borderRadius: 6,
                  background: '#F8FAFC', fontSize: 11, cursor: 'pointer'
                }}>{p.label}</button>
              ))}
            </div>
            <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
              <Btn variant="primary" onClick={() => setOpen(false)}>Aplicar</Btn>
            </div>
          </div>
        </Modal>
      )}
    </div>
  );
};

// ── Util de formatação ────────────────────────────────────────
const fmtBRL = v => 'R$ ' + Number(v || 0).toLocaleString('pt-BR', {
  minimumFractionDigits: 2, maximumFractionDigits: 2
});

const fmtKM = v => Number(v || 0).toLocaleString('pt-BR') + ' km';

const fmtKML = v => v == null ? '—' : Number(v).toFixed(2).replace('.', ',') + ' km/L';

// ── GraficoBarrasMensal ──────────────────────────────────────
// dados: { '2026-01': { abast: 320, desp: 50, receita: 450 }, ... }
// series: array de { key, label, color }
const GraficoBarrasMensal = ({ dados, series, height = 200 }) => {
  const canvasRef = useRefCF(null);
  const chartRef = useRefCF(null);

  useEffectCF(() => {
    if (!canvasRef.current || !window.Chart) return;
    if (chartRef.current) { chartRef.current.destroy(); chartRef.current = null; }

    const labels = Object.keys(dados).sort();
    const datasets = series.map(s => ({
      label: s.label,
      data: labels.map(m => dados[m]?.[s.key] || 0),
      backgroundColor: s.color,
      borderRadius: 4,
    }));

    chartRef.current = new window.Chart(canvasRef.current, {
      type: 'bar',
      data: { labels: labels.map(m => {
        const [y, mm] = m.split('-');
        return mm + '/' + y.slice(2);
      }), datasets },
      options: {
        responsive: true, maintainAspectRatio: false,
        plugins: { legend: { position: 'bottom', labels: { boxWidth: 10, font: { size: 10 } } } },
        scales: {
          x: { grid: { display: false }, ticks: { font: { size: 10 } } },
          y: { ticks: { font: { size: 10 }, callback: v => 'R$ ' + v } },
        },
      },
    });

    return () => { if (chartRef.current) { chartRef.current.destroy(); chartRef.current = null; } };
  }, [JSON.stringify(dados), JSON.stringify(series)]);

  return <div style={{ height, position: 'relative' }}><canvas ref={canvasRef} /></div>;
};

// ── BadgeLembrete ────────────────────────────────────────────
// count = quantidade de lembretes amarelo+vermelho; clique navega
const BadgeLembrete = ({ count, onClick, size = 'sm' }) => {
  if (!count) return null;
  const isLarge = size === 'lg';
  return (
    <button onClick={onClick} style={{
      background: 'rgba(245,158,11,.2)', color: '#F59E0B',
      padding: isLarge ? '6px 12px' : '4px 8px',
      borderRadius: 8, fontSize: isLarge ? 13 : 11, fontWeight: 600,
      display: 'flex', alignItems: 'center', gap: 4,
      border: 'none', cursor: 'pointer'
    }}>🔔 {count}</button>
  );
};

// ── BadgeLembreteGlobal ──────────────────────────────────────
// Conta lembretes amarelo+vermelho de toda a frota
const BadgeLembreteGlobal = ({ onClick }) => {
  const [count, setCount] = useStateCF(0);

  useEffectCF(() => {
    let alive = true;
    let runId = 0;
    const calcular = async () => {
      const myRun = ++runId;
      const [lembretes, frota] = await Promise.all([
        db.list('lembretes', { eq: { status: 'ativo' } }),
        db.list('frota'),
      ]);
      if (!alive || myRun !== runId) return;
      const fmap = Object.fromEntries(frota.map(g => [g.id, g.km_atual || 0]));
      let n = 0;
      for (const l of lembretes) {
        const st = window.statusLembrete(l, fmap[l.guincho_id]);
        if (st.estado !== 'ativo') n++;
      }
      setCount(n);
    };
    calcular();
    const id = setInterval(calcular, 60000); // recalcula a cada minuto
    return () => { alive = false; clearInterval(id); };
  }, []);

  return <BadgeLembrete count={count} onClick={onClick} size="sm" />;
};

Object.assign(window, { MetricCard, FabAdicionar, PeriodoPicker, GraficoBarrasMensal, BadgeLembrete, BadgeLembreteGlobal, fmtBRL, fmtKM, fmtKML });
