// ─── Calendario propio (selector de fecha · un día o rango) ──────────────
// Usado por Consultas para filtrar registros por fecha.

const MESES_LARGOS = [
  'Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio',
  'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre',
];
const MESES_CORTOS = ['Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic'];
const DIAS_CORTOS = ['L', 'M', 'X', 'J', 'V', 'S', 'D'];

function startOfDay(d) {
  return d ? new Date(d.getFullYear(), d.getMonth(), d.getDate()) : null;
}
function sameISO(a, b) {
  return a && b && window.isoOf(a) === window.isoOf(b);
}

// ── Cuadrícula de un mes ─────────────────────────────────────────────────
function MiniCalendar({ mode, day, from, to, onPick }) {
  const today = new Date();
  const base = day || from || to || today;
  const [view, setView] = React.useState(new Date(base.getFullYear(), base.getMonth(), 1));
  // Navegación jerárquica: null = días · 'month' = rejilla de meses · 'year' = rejilla de años
  const [pick, setPick] = React.useState(null);

  const y = view.getFullYear();
  const m = view.getMonth();
  const first = new Date(y, m, 1);
  const offset = (first.getDay() + 6) % 7; // lunes primero
  const daysInMonth = new Date(y, m + 1, 0).getDate();

  const cells = [];
  for (let i = 0; i < offset; i++) cells.push(null);
  for (let d = 1; d <= daysInMonth; d++) cells.push(new Date(y, m, d));
  while (cells.length % 7 !== 0) cells.push(null);

  const lo = startOfDay(from);
  const hi = startOfDay(to);

  const stateOf = (date) => {
    const sd = startOfDay(date);
    if (mode === 'dia') {
      return { selected: sameISO(date, day), inRange: false, edge: false };
    }
    const isFrom = sameISO(date, from);
    const isTo = sameISO(date, to);
    let inRange = false;
    if (lo && hi) inRange = sd > lo && sd < hi;
    return { selected: isFrom || isTo, inRange, edge: isFrom || isTo };
  };

  const navStyle = {
    width: 34, height: 34, borderRadius: 9, border: `1px solid ${TOKENS.border}`,
    background: TOKENS.surface, cursor: 'pointer', display: 'flex',
    alignItems: 'center', justifyContent: 'center', flexShrink: 0,
  };

  // Vista de años (rejilla)
  if (pick === 'year') {
    const years = [];
    for (let yr = today.getFullYear() + 1; yr >= today.getFullYear() - 12; yr--) years.push(yr);
    return (
      <div>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 12 }}>
          <div style={{ fontSize: 13.5, fontWeight: 700, color: TOKENS.text }}>Selecciona el año</div>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8, maxHeight: 236, overflowY: 'auto' }}>
          {years.map((yr) => {
            const active = yr === y;
            return (
              <button key={yr} onClick={() => { setView(new Date(yr, m, 1)); setPick('month'); }} style={{
                padding: '11px 0', borderRadius: 10, fontSize: 14, fontWeight: 700,
                fontFamily: 'inherit', cursor: 'pointer',
                border: `1px solid ${active ? TOKENS.primary : TOKENS.border}`,
                background: active ? TOKENS.primary : TOKENS.surface,
                color: active ? '#fff' : TOKENS.text,
              }}>{yr}</button>
            );
          })}
        </div>
      </div>
    );
  }

  // Vista de meses (rejilla, con navegación de año)
  if (pick === 'month') {
    return (
      <div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12 }}>
          <button onClick={() => setView(new Date(y - 1, m, 1))} style={navStyle} aria-label="Año anterior">{I.chevLeft(18, TOKENS.text)}</button>
          <button onClick={() => setPick('year')} style={{
            flex: 1, textAlign: 'center', background: 'transparent', border: 'none', cursor: 'pointer',
            fontFamily: 'inherit', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6, padding: '6px 0',
          }}>
            <span style={{ fontSize: 14.5, fontWeight: 700, color: TOKENS.text }}>{y}</span>
            {I.chev(15, TOKENS.textMuted)}
          </button>
          <button onClick={() => setView(new Date(y + 1, m, 1))} style={navStyle} aria-label="Año siguiente">{I.chevRight(18, TOKENS.text)}</button>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8 }}>
          {MESES_CORTOS.map((mes, idx) => {
            const active = idx === m;
            return (
              <button key={idx} onClick={() => { setView(new Date(y, idx, 1)); setPick(null); }} style={{
                padding: '12px 0', borderRadius: 10, fontSize: 13.5, fontWeight: 700,
                fontFamily: 'inherit', cursor: 'pointer',
                border: `1px solid ${active ? TOKENS.primary : TOKENS.border}`,
                background: active ? TOKENS.primary : TOKENS.surface,
                color: active ? '#fff' : TOKENS.text,
              }}>{mes}</button>
            );
          })}
        </div>
      </div>
    );
  }

  return (
    <div>
      {/* Header con navegación de mes */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
        <button onClick={() => setView(new Date(y, m - 1, 1))} style={navStyle} aria-label="Mes anterior">
          {I.chevLeft(18, TOKENS.text)}
        </button>
        <button onClick={() => setPick('month')} style={{
          flex: 1, textAlign: 'center', background: 'transparent', border: 'none',
          cursor: 'pointer', fontFamily: 'inherit', display: 'flex', alignItems: 'center',
          justifyContent: 'center', gap: 6, padding: '6px 0',
        }}>
          <span style={{ fontSize: 14.5, fontWeight: 700, color: TOKENS.text }}>
            {MESES_LARGOS[m]} {y}
          </span>
          {I.chev(15, TOKENS.textMuted)}
        </button>
        <button onClick={() => setView(new Date(y, m + 1, 1))} style={navStyle} aria-label="Mes siguiente">
          {I.chevRight(18, TOKENS.text)}
        </button>
      </div>

      {/* Días de la semana */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', marginBottom: 4 }}>
        {DIAS_CORTOS.map((d, i) => (
          <div key={i} style={{
            textAlign: 'center', fontSize: 10.5, fontWeight: 700, color: TOKENS.textMuted,
            letterSpacing: '0.04em', padding: '4px 0',
          }}>{d}</div>
        ))}
      </div>

      {/* Celdas */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: '2px 0' }}>
        {cells.map((date, i) => {
          if (!date) return <div key={i} />;
          const { selected, inRange } = stateOf(date);
          const isToday = sameISO(date, today);
          return (
            <div key={i} style={{
              display: 'flex', justifyContent: 'center', padding: '1px 0',
              background: inRange ? TOKENS.surfaceContainer : 'transparent',
            }}>
              <button onClick={() => onPick(date)} style={{
                width: 34, height: 34, borderRadius: 9, cursor: 'pointer', fontFamily: 'inherit',
                fontSize: 13.5, fontWeight: selected ? 700 : 600,
                border: isToday && !selected ? `1.5px solid ${TOKENS.primary}` : '1px solid transparent',
                background: selected ? TOKENS.primary : 'transparent',
                color: selected ? '#fff' : TOKENS.text,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}>{date.getDate()}</button>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ── Popover completo: modo + calendario + acciones ───────────────────────
function CalendarPopover({ mode, day, from, to, onChange, onClose }) {
  const ref = React.useRef(null);
  React.useEffect(() => {
    const onDown = (e) => {
      if (ref.current && !ref.current.contains(e.target) && !e.target.closest('[data-cal-toggle]')) onClose();
    };
    document.addEventListener('mousedown', onDown);
    return () => document.removeEventListener('mousedown', onDown);
  }, [onClose]);

  const setMode = (next) => {
    if (next === mode) return;
    // Al cambiar de modo, sembramos un punto de partida razonable
    if (next === 'dia') onChange({ mode: 'dia', day: day || from || to || null, from: null, to: null });
    else onChange({ mode: 'rango', day: null, from: day || from || null, to: to || null });
  };

  const handlePick = (date) => {
    if (mode === 'dia') {
      onChange({ mode, day: date, from: null, to: null });
      onClose();
      return;
    }
    // rango
    if (!from || (from && to)) {
      onChange({ mode, day: null, from: date, to: null });
    } else {
      if (startOfDay(date) < startOfDay(from)) {
        onChange({ mode, day: null, from: date, to: null });
      } else {
        onChange({ mode, day: null, from, to: date });
        onClose();
      }
    }
  };

  const rangeHint = mode === 'rango'
    ? (from && to
        ? `${window.fechaCorta(from)} – ${window.fechaCorta(to)}`
        : from
          ? `Desde ${window.fechaCorta(from)} · elige el fin`
          : 'Elige la fecha de inicio')
    : null;

  return (
    <div ref={ref} style={{
      position: 'absolute', top: 'calc(100% + 6px)', left: 0, right: 0, zIndex: 60,
      background: TOKENS.surface, border: `1px solid ${TOKENS.border}`,
      borderRadius: 14, padding: 14, boxShadow: '0 18px 40px rgba(11,28,48,0.18)',
    }}>
      {/* Modo */}
      <div style={{
        display: 'flex', gap: 4, padding: 4, background: TOKENS.surfaceLow,
        borderRadius: 10, marginBottom: 12,
      }}>
        {[['dia', 'Un día'], ['rango', 'Rango']].map(([val, label]) => {
          const active = mode === val;
          return (
            <button key={val} onClick={() => setMode(val)} style={{
              flex: 1, padding: '8px 0', borderRadius: 8, fontSize: 12.5, fontWeight: 700,
              border: 'none', cursor: 'pointer', fontFamily: 'inherit',
              background: active ? TOKENS.surface : 'transparent',
              color: active ? TOKENS.primary : TOKENS.textMuted,
              boxShadow: active ? '0 1px 3px rgba(11,28,48,0.12)' : 'none',
            }}>{label}</button>
          );
        })}
      </div>

      {rangeHint && (
        <div style={{
          fontSize: 12, color: TOKENS.textMuted, fontWeight: 600,
          marginBottom: 10, textAlign: 'center',
        }}>{rangeHint}</div>
      )}

      <MiniCalendar mode={mode} day={day} from={from} to={to} onPick={handlePick} />

      {/* Acciones */}
      <div style={{ display: 'flex', gap: 8, marginTop: 12 }}>
        <button onClick={() => { onChange({ mode, day: null, from: null, to: null }); onClose(); }} style={{
          flex: 1, padding: '10px 0', borderRadius: 10, fontSize: 13, fontWeight: 700,
          border: `1px solid ${TOKENS.border}`, background: TOKENS.surface,
          color: TOKENS.textMuted, cursor: 'pointer', fontFamily: 'inherit',
        }}>Limpiar</button>
        <button onClick={onClose} style={{
          flex: 1, padding: '10px 0', borderRadius: 10, fontSize: 13, fontWeight: 700,
          border: 'none', background: TOKENS.primary, color: '#fff',
          cursor: 'pointer', fontFamily: 'inherit',
        }}>Listo</button>
      </div>
    </div>
  );
}

Object.assign(window, { CalendarPopover, MiniCalendar, startOfDay, sameISO });
