// src/screen-eventos.jsx — §Eventos. "El cuándo": el calendario semanal del agente.
// Una sola fuente (el motor de workflows) proyectada como calendario. Tres tipos
// de evento, visualmente distintos:
//   tarea   — te toca a ti                (acento signal-green, sólido)
//   auto    — Piixi lo hace solo          (gris discreto, punteado — no invade)
//   externo — tu Google Calendar          (info azul, punteado)
// Regla de prior-art: SÓLO entra al calendario lo que ocurre a una HORA fija.
// Las renovaciones sin hora ("vence en 30 días") viven en Pendientes, no aquí.

// "Hoy" del prototipo — mismo ancla que el dashboard (2026-05-18, un lunes).
const EVENTOS_TODAY = new Date('2026-05-18T00:00:00');

// Rejilla de tiempo del calendario.
const GRID_START_H = 8;    // 08:00
const GRID_END_H   = 19;   // 19:00
const HOUR_H       = 56;   // px por hora
const GUTTER_W     = 52;   // ancho de la columna de horas
const GRID_H       = (GRID_END_H - GRID_START_H) * HOUR_H;

const EVENTO_TIPOS = {
  tarea:   { label: 'Te toca',       dot: 'var(--ax-accent)' },
  auto:    { label: 'Piixi lo hace', dot: 'var(--ax-fg-faint)' },
  externo: { label: 'Tu calendario', dot: 'var(--ax-info)' },
};

const DOW_SHORT   = ['LUN', 'MAR', 'MIÉ', 'JUE', 'VIE', 'SÁB', 'DOM'];
const DOW_LONG    = ['lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado', 'domingo'];
const MONTHS_LONG = ['enero','febrero','marzo','abril','mayo','junio','julio','agosto','septiembre','octubre','noviembre','diciembre'];

const cap = (s) => (s ? s.charAt(0).toUpperCase() + s.slice(1) : s);

// Seed de eventos de la semana. dOff = offset de día desde hoy (0=lun..6=dom).
// who = nombre del contratante/lead (seed real por índice); cid = su id.
// tarea con cliente existente -> "Abrir ficha" /clientes/:id
// tarea con lead nuevo        -> "Ver contacto" /contactos/:id (vista aún por traer)
function buildEventos() {
  const C   = (i) => (AdmixData.CONTRATANTES[i] ? AdmixData.CONTRATANTES[i].nombre : 'Cliente');
  const CID = (i) => (AdmixData.CONTRATANTES[i] ? AdmixData.CONTRATANTES[i].id     : 'c0001');
  const ficha   = (i) => ({ action: 'Abrir ficha',  to: '/clientes/'  + CID(i) });
  const contacto = (i) => ({ action: 'Ver contacto', to: '/contactos/' + CID(i) });

  const raw = [
    // Lunes 18 (hoy)
    { dOff: 0, time: '09:00', dur: 0,  type: 'auto',    title: 'Recordatorio de pago enviado',    who: C(2),  channel: 'Telegram' },
    { dOff: 0, time: '10:30', dur: 30, type: 'tarea',   title: 'Llamada de renovación',           who: C(5),  channel: 'Llamada', ...ficha(5) },
    { dOff: 0, time: '13:30', dur: 60, type: 'externo', title: 'Comida',                          who: null,  channel: 'Personal' },
    { dOff: 0, time: '16:00', dur: 45, type: 'tarea',   title: 'Cita: alta de Gastos Médicos',    who: C(8),  channel: 'Cita · lead', ...contacto(8) },
    { dOff: 0, time: '18:00', dur: 0,  type: 'auto',    title: 'Cruce CNSF de cédula programado', who: null,  channel: 'Cumplimiento' },
    // Martes 19
    { dOff: 1, time: '09:30', dur: 45, type: 'tarea',   title: 'Cita: ajuste de suma asegurada',  who: C(12), channel: 'Cita', ...ficha(12) },
    { dOff: 1, time: '12:00', dur: 0,  type: 'auto',    title: 'Aviso de vencimiento enviado',    who: C(15), channel: 'Correo' },
    { dOff: 1, time: '17:00', dur: 60, type: 'externo', title: 'Junta de equipo',                 who: null,  channel: 'Personal' },
    // Miércoles 20
    { dOff: 2, time: '11:00', dur: 30, type: 'tarea',   title: 'Llamada de cobranza',             who: C(20), channel: 'Llamada', ...ficha(20) },
    { dOff: 2, time: '13:00', dur: 60, type: 'externo', title: 'Dentista',                        who: null,  channel: 'Personal' },
    { dOff: 2, time: '15:30', dur: 0,  type: 'auto',    title: 'Re-lectura de documento (Judy)',  who: C(31), channel: 'Enriquecimiento' },
    // Jueves 21
    { dOff: 3, time: '10:00', dur: 45, type: 'tarea',   title: 'Firma de renovación',             who: C(25), channel: 'Cita', ...ficha(25) },
    { dOff: 3, time: '16:30', dur: 0,  type: 'auto',    title: 'Recordatorio enviado',            who: C(3),  channel: 'Telegram' },
    // Viernes 22
    { dOff: 4, time: '09:00', dur: 45, type: 'tarea',   title: 'Cita: nuevo cliente',             who: C(30), channel: 'Cita · lead', ...contacto(30) },
    { dOff: 4, time: '14:00', dur: 0,  type: 'externo', title: 'Salida temprano',                 who: null,  channel: 'Personal' },
    // Sábado 23
    { dOff: 5, time: '11:00', dur: 0,  type: 'auto',    title: 'Felicitación de cumpleaños',      who: C(7),  channel: 'Telegram' },
  ];
  return raw.map((e, i) => {
    const d = new Date(EVENTOS_TODAY);
    d.setDate(d.getDate() + e.dOff);
    return { id: 'ev' + i, iso: d.toISOString().slice(0, 10), ...e };
  });
}

const EVENTOS_SEED = buildEventos();

function isoOf(date) { return date.toISOString().slice(0, 10); }
function minutesOf(hhmm) { const [h, m] = hhmm.split(':').map(Number); return h * 60 + m; }
function topFor(hhmm) { return (minutesOf(hhmm) - GRID_START_H * 60) / 60 * HOUR_H; }
function heightFor(dur) { return Math.max((dur / 60) * HOUR_H, 28); }

function startOfWeekMon(date) {
  const d = new Date(date);
  const wd = (d.getDay() + 6) % 7; // 0 = lunes
  d.setDate(d.getDate() - wd);
  d.setHours(0, 0, 0, 0);
  return d;
}

// ─────────────────────────────────────────────────────────────
// SCREEN
// ─────────────────────────────────────────────────────────────
function EventosScreen() {
  const { navigate } = useHashRoute();
  const [weekOffset, setWeekOffset] = useState(0);

  const weekStart = useMemo(() => {
    const s = startOfWeekMon(EVENTOS_TODAY);
    s.setDate(s.getDate() + weekOffset * 7);
    return s;
  }, [weekOffset]);

  const todayISO = isoOf(EVENTOS_TODAY);

  const days = useMemo(() => {
    return Array.from({ length: 7 }, (_, i) => {
      const d = new Date(weekStart);
      d.setDate(d.getDate() + i);
      const iso = isoOf(d);
      const evs = EVENTOS_SEED.filter((e) => e.iso === iso).sort((a, b) => a.time.localeCompare(b.time));
      return { iso, dow: DOW_SHORT[i], num: d.getDate(), isToday: iso === todayISO, evs };
    });
  }, [weekStart, todayISO]);

  const todayEvs = useMemo(
    () => EVENTOS_SEED.filter((e) => e.iso === todayISO).sort((a, b) => a.time.localeCompare(b.time)),
    [todayISO]
  );
  const todayTareas = todayEvs.filter((e) => e.type === 'tarea').length;

  const rangeLabel = useMemo(() => {
    const a = weekStart;
    const b = new Date(weekStart); b.setDate(b.getDate() + 6);
    const ma = MONTHS_LONG[a.getMonth()], mb = MONTHS_LONG[b.getMonth()];
    return ma === mb ? `${a.getDate()}–${b.getDate()} ${ma}` : `${a.getDate()} ${ma} – ${b.getDate()} ${mb}`;
  }, [weekStart]);

  const todayLong = cap(`${DOW_LONG[(EVENTOS_TODAY.getDay() + 6) % 7]} ${EVENTOS_TODAY.getDate()} de ${MONTHS_LONG[EVENTOS_TODAY.getMonth()]}`);
  const hours = Array.from({ length: GRID_END_H - GRID_START_H + 1 }, (_, i) => GRID_START_H + i);

  return (
    <div style={{ flex: 1, overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
      <AxPageHeader
        eyebrow="Trabajo del día · el cuándo"
        title="Eventos"
        subtitle="Lo que ocurre a una hora fija. Las renovaciones sin hora viven en Pendientes."
        actions={
          <>
            <div style={{ display: 'flex', alignItems: 'center', gap: 4, marginRight: 4 }}>
              <button className="ax-btn ax-btn--tertiary" style={{ height: 32, width: 32, padding: 0 }}
                onClick={() => setWeekOffset((w) => w - 1)} title="Semana anterior">
                <AxIcon name="arrow-left" size={15}/>
              </button>
              <button className="ax-btn ax-btn--secondary ax-btn--sm" onClick={() => setWeekOffset(0)}>Hoy</button>
              <button className="ax-btn ax-btn--tertiary" style={{ height: 32, width: 32, padding: 0 }}
                onClick={() => setWeekOffset((w) => w + 1)} title="Semana siguiente">
                <AxIcon name="arrow-right" size={15}/>
              </button>
            </div>
            <AxButton variant="secondary" icon="cal">Conectar Google Calendar</AxButton>
          </>
        }
      />

      <div style={{ flex: 1, overflow: 'hidden', display: 'flex', minHeight: 0 }}>
        {/* ─── MAIN: calendario semanal (rejilla de tiempo) ─── */}
        <div style={{ flex: 1, overflow: 'auto', minWidth: 0, display: 'flex', flexDirection: 'column' }}>
          <div style={{ padding: '16px 24px 10px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16, flexWrap: 'wrap' }}>
            <div style={{ fontSize: 14, color: 'var(--ax-fg-strong)', fontWeight: 500, textTransform: 'capitalize' }}>{rangeLabel}</div>
            <EventosLegend/>
          </div>

          {/* cabecera de días (sticky) */}
          <div style={{ position: 'sticky', top: 0, zIndex: 3, background: 'var(--ax-bg)', padding: '0 24px', borderBottom: '1px solid var(--ax-border)' }}>
            <div style={{ display: 'flex' }}>
              <div style={{ width: GUTTER_W, flexShrink: 0 }}/>
              <div style={{ flex: 1, display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)' }}>
                {days.map((d) => <DayHeader key={d.iso} day={d}/>)}
              </div>
            </div>
          </div>

          {/* rejilla */}
          <div style={{ padding: '0 24px 28px' }}>
            <div style={{ display: 'flex' }}>
              {/* columna de horas */}
              <div style={{ width: GUTTER_W, flexShrink: 0, position: 'relative', height: GRID_H }}>
                {hours.map((h) => (
                  <div key={h} style={{
                    position: 'absolute', top: (h - GRID_START_H) * HOUR_H - 6, right: 10,
                    fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--ax-fg-faint)', fontVariantNumeric: 'tabular-nums',
                  }}>{String(h).padStart(2, '0')}:00</div>
                ))}
              </div>
              {/* área de días */}
              <div style={{ flex: 1, position: 'relative', display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', height: GRID_H }}>
                {/* líneas de hora */}
                {hours.map((h) => (
                  <div key={'l' + h} style={{ position: 'absolute', left: 0, right: 0, top: (h - GRID_START_H) * HOUR_H, borderTop: '1px solid var(--ax-border)' }}/>
                ))}
                {/* columnas por día */}
                {days.map((d, i) => (
                  <div key={d.iso} style={{
                    position: 'relative', height: GRID_H,
                    borderLeft: i > 0 ? '1px solid var(--ax-border)' : 'none',
                    background: d.isToday ? 'rgba(0,255,136,0.05)' : 'transparent',
                  }}>
                    {d.evs.map((ev) => <EventBlock key={ev.id} ev={ev}/>)}
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>

        {/* ─── RAIL: eventos Piixi de hoy ─── */}
        <aside style={{
          width: 322, flexShrink: 0, borderLeft: '1px solid var(--ax-border)',
          background: 'var(--ax-bg-1)', overflow: 'auto',
          display: 'flex', flexDirection: 'column',
        }}>
          <div style={{ padding: '18px 18px 14px', borderBottom: '1px solid var(--ax-border)' }}>
            <AxEyebrow style={{ color: 'var(--ax-accent)' }}>Eventos Piixi de hoy</AxEyebrow>
            <div style={{ marginTop: 8, fontSize: 14, color: 'var(--ax-fg-strong)' }}>{todayLong}</div>
            <div style={{ marginTop: 4, fontSize: 12, color: 'var(--ax-fg-muted)' }}>
              {todayEvs.length} eventos · <span style={{ color: 'var(--ax-accent)' }}>{todayTareas} te {todayTareas === 1 ? 'toca' : 'tocan'}</span>
            </div>
          </div>

          <div style={{ flex: 1, padding: 12, display: 'flex', flexDirection: 'column', gap: 8 }}>
            {todayEvs.length === 0
              ? <AxEmpty icon="cal" title="Nada agendado hoy" body="Cuando programes una cita o un envío con hora, aparece aquí."/>
              : todayEvs.map((e) => <RailEvent key={e.id} ev={e} navigate={navigate}/>)}
          </div>

          {/* pie → cumplimiento */}
          <div style={{ padding: 14, borderTop: '1px solid var(--ax-border)' }}>
            <button onClick={() => navigate('/cumplimiento')} style={{
              appearance: 'none', width: '100%', textAlign: 'left', cursor: 'default',
              background: 'var(--ax-bg-2)', border: '1px solid var(--ax-border)', borderRadius: 10,
              padding: '12px 14px', color: 'inherit', display: 'flex', alignItems: 'center', gap: 12,
              transition: 'background 150ms, border-color 150ms',
            }}
              onMouseEnter={(e) => { e.currentTarget.style.background = 'var(--ax-bg-3)'; e.currentTarget.style.borderColor = 'var(--ax-border-strong)'; }}
              onMouseLeave={(e) => { e.currentTarget.style.background = 'var(--ax-bg-2)'; e.currentTarget.style.borderColor = 'var(--ax-border)'; }}
            >
              <div style={{
                width: 30, height: 30, borderRadius: 8, flexShrink: 0,
                background: 'var(--ax-accent-soft)', color: 'var(--ax-accent)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}><AxIcon name="shield" size={15}/></div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 12.5, color: 'var(--ax-fg-strong)', fontWeight: 500 }}>Eventos = el cuándo.</div>
                <div style={{ fontSize: 12, color: 'var(--ax-fg-muted)' }}>Cumplimiento = el qué te falta.</div>
              </div>
              <AxIcon name="arrow-right" size={14} style={{ color: 'var(--ax-fg-faint)' }}/>
            </button>
          </div>
        </aside>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// LEGEND — los 3 tipos
// ─────────────────────────────────────────────────────────────
function EventosLegend() {
  const swatch = {
    tarea:   { background: 'var(--ax-accent)', border: 'none' },
    auto:    { background: 'transparent', border: '1px dashed var(--ax-fg-faint)' },
    externo: { background: 'transparent', border: '1px dotted var(--ax-info)' },
  };
  return (
    <div style={{ display: 'flex', gap: 16, flexWrap: 'wrap' }}>
      {Object.keys(EVENTO_TIPOS).map((k) => (
        <span key={k} style={{ display: 'inline-flex', alignItems: 'center', gap: 7, fontSize: 11, color: 'var(--ax-fg-muted)' }}>
          <span style={{ width: 9, height: 9, borderRadius: 2, ...swatch[k] }}/>
          {EVENTO_TIPOS[k].label}
        </span>
      ))}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// DAY HEADER
// ─────────────────────────────────────────────────────────────
function DayHeader({ day }) {
  return (
    <div style={{ padding: '10px 8px', textAlign: 'center', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4 }}>
      <span style={{ fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.12em', color: day.isToday ? 'var(--ax-accent)' : 'var(--ax-fg-faint)' }}>{day.dow}</span>
      {day.isToday ? (
        <span style={{
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          width: 26, height: 26, borderRadius: '50%', background: 'var(--ax-accent)',
          color: '#0A0A0A', fontSize: 14, fontWeight: 700,
        }}>{day.num}</span>
      ) : (
        <span style={{ fontSize: 16, fontWeight: 600, color: 'var(--ax-fg-strong)', height: 26, display: 'inline-flex', alignItems: 'center' }}>{day.num}</span>
      )}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// EVENT BLOCK — posicionado por su hora real en la rejilla
// ─────────────────────────────────────────────────────────────
function EventBlock({ ev }) {
  const styleByType = {
    tarea:   { background: 'var(--ax-accent-soft)', border: '1px solid var(--ax-accent-line)', borderLeft: '2px solid var(--ax-accent)' },
    auto:    { background: 'var(--ax-bg-2)', border: '1px dashed var(--ax-border-strong)' },
    externo: { background: 'var(--ax-bg-2)', border: '1px dotted var(--ax-info-line)' },
  };
  const timeColor = ev.type === 'tarea' ? 'var(--ax-accent)' : ev.type === 'externo' ? 'var(--ax-info)' : 'var(--ax-fg-muted)';
  const titleColor = ev.type === 'auto' ? 'var(--ax-fg-muted)' : 'var(--ax-fg)';
  const h = heightFor(ev.dur);
  return (
    <div title={ev.time + ' · ' + ev.title + (ev.who ? ' · ' + ev.who : '')} style={{
      position: 'absolute', top: topFor(ev.time), height: h, left: 3, right: 3,
      ...styleByType[ev.type], borderRadius: 6, padding: '3px 6px', overflow: 'hidden',
      display: 'flex', flexDirection: 'column', gap: 1,
    }}>
      <span style={{ fontFamily: 'var(--font-mono)', fontSize: 9.5, color: timeColor, fontVariantNumeric: 'tabular-nums', lineHeight: 1.1 }}>{ev.time}</span>
      <span style={{
        fontSize: 11, color: titleColor, lineHeight: 1.2,
        display: '-webkit-box', WebkitLineClamp: h > 40 ? 2 : 1, WebkitBoxOrient: 'vertical', overflow: 'hidden',
      }}>{ev.title}</span>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// RAIL EVENT — detalle de un evento de hoy
// ─────────────────────────────────────────────────────────────
function RailEvent({ ev, navigate }) {
  const barColor = ev.type === 'tarea' ? 'var(--ax-accent)' : ev.type === 'externo' ? 'var(--ax-info)' : 'var(--ax-fg-faint)';
  const dashed = ev.type !== 'tarea';
  return (
    <div style={{
      background: ev.type === 'tarea' ? 'var(--ax-accent-soft)' : 'var(--ax-bg-2)',
      border: '1px solid ' + (ev.type === 'tarea' ? 'var(--ax-accent-line)' : 'var(--ax-border)'),
      borderLeft: '2px ' + (dashed ? 'dotted' : 'solid') + ' ' + barColor,
      borderRadius: 8, padding: '10px 12px',
      display: 'flex', flexDirection: 'column', gap: 6,
    }}>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
        <span style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: barColor, fontVariantNumeric: 'tabular-nums', fontWeight: 600 }}>{ev.time}</span>
        <span style={{ fontSize: 9, fontFamily: 'var(--font-mono)', letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--ax-fg-faint)', marginLeft: 'auto' }}>
          {EVENTO_TIPOS[ev.type].label}
        </span>
      </div>
      <div style={{ fontSize: 13, color: 'var(--ax-fg-strong)', lineHeight: 1.35 }}>{ev.title}</div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 11, color: 'var(--ax-fg-muted)' }}>
        {ev.who ? <span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{ev.who}</span> : <span>{ev.channel}</span>}
        {ev.who ? <span style={{ color: 'var(--ax-fg-faint)' }}>· {ev.channel}</span> : null}
      </div>
      {ev.action ? (
        <div style={{ marginTop: 2 }}>
          <AxButton variant="secondary" size="sm" iconRight="arrow-right" onClick={() => navigate(ev.to || '/inicio')}>{ev.action}</AxButton>
        </div>
      ) : null}
    </div>
  );
}

// Expuesto para que el resumen de Inicio lea los eventos de hoy sin recalcular.
window.AdmixEventos = {
  TODAY: EVENTOS_TODAY,
  hoyISO: isoOf(EVENTOS_TODAY),
  seed: EVENTOS_SEED,
  deHoy: function () {
    var iso = isoOf(EVENTOS_TODAY);
    return EVENTOS_SEED.filter(function (e) { return e.iso === iso; }).sort(function (a, b) { return a.time.localeCompare(b.time); });
  },
};

window.EventosScreen = EventosScreen;
