/* global React, Icon, Badge, Button, brl */

// ─── Period helpers ───────────────────────────────────────────────────────────

const PERIODOS_PRESET = [
  { id: 'hoje',    label: 'Hoje'            },
  { id: '7d',      label: 'Últimos 7 dias'  },
  { id: 'mes',     label: 'Este mês'        },
  { id: 'mes_ant', label: 'Mês anterior'    },
  { id: '30d',     label: 'Últimos 30 dias' },
  { id: '90d',     label: 'Últimos 90 dias' },
  { id: 'ano',     label: 'Este ano'        },
  { id: 'custom',  label: 'Personalizado'   },
];

function calcPeriod(id, cStart, cEnd) {
  const t = new Date(), y = t.getFullYear(), m = t.getMonth(), d = t.getDate();
  switch (id) {
    case 'hoje':    return { start: new Date(y, m, d, 0, 0, 0), end: t };
    case '7d':      return { start: new Date(y, m, d - 7),       end: t };
    case 'mes':     return { start: new Date(y, m, 1),            end: t };
    case 'mes_ant': return { start: new Date(y, m - 1, 1),        end: new Date(y, m, 0) };
    case '30d':     return { start: new Date(y, m, d - 30),       end: t };
    case '90d':     return { start: new Date(y, m, d - 90),       end: t };
    case 'ano':     return { start: new Date(y, 0, 1),            end: t };
    case 'custom':  return {
      start: cStart ? new Date(cStart) : new Date(y, m, 1),
      end:   cEnd   ? new Date(cEnd)   : t,
    };
    default:        return { start: new Date(y, m, 1), end: t };
  }
}

function calcPreviousPeriod(start, end) {
  const diff = end.getTime() - start.getTime();
  return { start: new Date(start.getTime() - diff), end: new Date(start.getTime() - 1) };
}

const fmtShort = (d) => d.toLocaleDateString('pt-BR', { day: '2-digit', month: '2-digit' });
const fmtFull  = (d) => d.toLocaleDateString('pt-BR', { day: '2-digit', month: '2-digit', year: 'numeric' });

function PeriodDropdown({ periodId, setPeriodId, customStart, setCustomStart, customEnd, setCustomEnd, onClose }) {
  const [tStart, setTStart] = React.useState(customStart);
  const [tEnd,   setTEnd]   = React.useState(customEnd);

  const choose = (id) => { setPeriodId(id); if (id !== 'custom') onClose(); };

  const applyCustom = () => {
    setCustomStart(tStart);
    setCustomEnd(tEnd);
    onClose();
  };

  return (
    <>
      <div style={{ position: 'fixed', inset: 0, zIndex: 498 }} onClick={onClose} />
      <div style={{
        position: 'absolute', top: 'calc(100% + 6px)', right: 0, width: 232,
        background: 'var(--tm-bg-1)', borderRadius: 10,
        border: '1px solid var(--tm-line-2)', overflow: 'hidden',
        boxShadow: '0 12px 40px rgba(0,0,0,0.32)', zIndex: 499,
      }}>
        <div style={{ padding: '10px 12px 4px', fontSize: 10.5, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--tm-fg-4)' }}>
          Período de análise
        </div>
        {PERIODOS_PRESET.map(p => (
          <div
            key={p.id}
            onClick={() => choose(p.id)}
            style={{
              display: 'flex', alignItems: 'center', justifyContent: 'space-between',
              padding: '9px 12px', cursor: 'pointer', fontSize: 13,
              background: periodId === p.id ? 'color-mix(in srgb, var(--tm-brand-champagne) 10%, var(--tm-bg-2))' : 'transparent',
              color: periodId === p.id ? 'var(--tm-brand-champagne)' : 'var(--tm-fg-2)',
            }}
          >
            <span>{p.label}</span>
            {periodId === p.id && <Icon name="check" size={13} />}
          </div>
        ))}
        {periodId === 'custom' && (
          <div style={{ padding: '10px 12px 12px', borderTop: '1px solid var(--tm-line-1)' }}>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              <div className="field" style={{ margin: 0 }}>
                <label>De</label>
                <input className="input" type="date" value={tStart} onChange={e => setTStart(e.target.value)} />
              </div>
              <div className="field" style={{ margin: 0 }}>
                <label>Até</label>
                <input className="input" type="date" value={tEnd} onChange={e => setTEnd(e.target.value)} />
              </div>
              <Button variant="primary" size="sm" style={{ width: '100%' }} onClick={applyCustom}>
                Aplicar
              </Button>
            </div>
          </div>
        )}
      </div>
    </>
  );
}

// ─── Relative time helper ─────────────────────────────────────────────────────
function tempoAtras(iso) {
  if (!iso) return '';
  const agora = Date.now();
  const dt = new Date(iso).getTime();
  const diff = agora - dt;
  const min = Math.floor(diff / 60000);
  if (min < 1) return 'agora';
  if (min < 60) return `há ${min}min`;
  const hrs = Math.floor(min / 60);
  if (hrs < 24) return `há ${hrs}h`;
  const dias = Math.floor(hrs / 24);
  if (dias === 1) return 'ontem';
  if (dias < 30) return `há ${dias}d`;
  const meses = Math.floor(dias / 30);
  return `há ${meses} ${meses === 1 ? 'mês' : 'meses'}`;
}

// ─── Stat component ───────────────────────────────────────────────────────────
function Stat({ label, v, sub, tone }) {
  return (
    <div style={{ borderLeft: "1px solid var(--tm-line-1)", paddingLeft: 12 }}>
      <div style={{ fontSize: 10, letterSpacing: "0.12em", textTransform: "uppercase", color: "var(--tm-fg-3)" }}>{label}</div>
      <div style={{ fontSize: 16, fontWeight: 600, fontVariantNumeric: "tabular-nums", marginTop: 4,
                    color: tone === "up" ? "var(--tm-success)" : "var(--tm-fg-1)" }}>{v}</div>
      {sub && <div style={{ fontSize: 11, color: "var(--tm-fg-3)" }}>{sub}</div>}
    </div>
  );
}

// ─── Quick Actions Strip ──────────────────────────────────────────────────────
function QuickActions({ onNav }) {
  const actions = [
    { icon: 'shopping-cart', label: 'Novo Pedido',      nav: 'pedidos/criar' },
    { icon: 'dollar-sign',  label: 'Lançar Conta',      nav: 'financeiro/entradas' },
    { icon: 'user-plus',    label: 'Novo Cliente',       nav: 'crm/clientes-finais' },
    { icon: 'file-check',   label: 'Emitir NF',         nav: 'nf/emissao' },
    { icon: 'package-plus', label: 'Cadastrar Produto',  nav: 'produtos/lista' },
    { icon: 'columns',      label: 'Nova Tarefa',        nav: 'kanban' },
  ];

  return (
    <div style={{
      display: 'flex', gap: 8, flexWrap: 'wrap',
    }}>
      {actions.map(a => (
        <button
          key={a.nav}
          onClick={() => onNav(a.nav)}
          style={{
            display: 'flex', alignItems: 'center', gap: 7,
            padding: '8px 14px', borderRadius: 8,
            background: 'var(--tm-bg-1)', border: '1px solid var(--tm-line-1)',
            color: 'var(--tm-fg-2)', fontSize: 12.5, fontWeight: 500,
            cursor: 'pointer', transition: 'all .15s',
            fontFamily: 'inherit',
          }}
          onMouseEnter={e => { e.currentTarget.style.borderColor = 'var(--tm-brand-champagne)'; e.currentTarget.style.color = 'var(--tm-brand-champagne)'; }}
          onMouseLeave={e => { e.currentTarget.style.borderColor = 'var(--tm-line-1)'; e.currentTarget.style.color = 'var(--tm-fg-2)'; }}
        >
          <Icon name={a.icon} size={14} />
          {a.label}
        </button>
      ))}
    </div>
  );
}

// ─── Clickable KPI wrapper ────────────────────────────────────────────────────
function ClickableKPI({ onClick, children }) {
  return (
    <div
      onClick={onClick}
      style={{ cursor: onClick ? 'pointer' : 'default', transition: 'transform .12s' }}
      onMouseEnter={e => { if (onClick) e.currentTarget.style.transform = 'translateY(-2px)'; }}
      onMouseLeave={e => { e.currentTarget.style.transform = 'none'; }}
    >
      {children}
    </div>
  );
}

// ─── Chart.js Canvas Wrapper ─────────────────────────────────────────────────
function ChartCanvas({ type, data, options, height }) {
  const canvasRef = React.useRef(null);
  const chartRef  = React.useRef(null);

  React.useEffect(() => {
    if (!canvasRef.current || !window.Chart) return;
    if (chartRef.current) chartRef.current.destroy();

    chartRef.current = new window.Chart(canvasRef.current, {
      type,
      data,
      options: {
        responsive: true,
        maintainAspectRatio: false,
        animation: { duration: 400 },
        plugins: {
          legend: { display: false },
          tooltip: {
            backgroundColor: 'rgba(11,11,13,0.92)',
            titleFont: { size: 11 },
            bodyFont: { size: 12 },
            padding: 10,
            cornerRadius: 6,
          },
        },
        ...options,
      },
    });

    return () => {
      if (chartRef.current) { chartRef.current.destroy(); chartRef.current = null; }
    };
  }, [type, JSON.stringify(data), JSON.stringify(options)]);

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

// ─── Section Card (reusable widget card) ─────────────────────────────────────
function SectionCard({ title, action, children, style }) {
  return (
    <div className="card" style={style}>
      {title && (
        <div className="card-head">
          <h3>{title}</h3>
          {action && <div>{action}</div>}
        </div>
      )}
      <div style={{ padding: 16 }}>{children}</div>
    </div>
  );
}

Object.assign(window, {
  PERIODOS_PRESET, calcPeriod, calcPreviousPeriod, fmtShort, fmtFull,
  PeriodDropdown, tempoAtras, Stat, QuickActions, ClickableKPI,
  ChartCanvas, SectionCard,
});
