// Rumbo — DatePicker · único componente para los 3 formularios
// Props:
//   label      string          — etiqueta uppercase
//   value      string|number   — YYYY-MM-DD (normal) ó 1-31 (dayOnly)
//   onChange   fn(v)           — devuelve string o number según modo
//   required   bool
//   dayOnly    bool            — modo "día del mes": devuelve 1-31, muestra "Día X de cada mes"

const { useState: useStPK } = React;

const MONTHS_ES = [
  'Enero','Febrero','Marzo','Abril','Mayo','Junio',
  'Julio','Agosto','Septiembre','Octubre','Noviembre','Diciembre'
];
const DAYS_ES = ['Do','Lu','Ma','Mi','Ju','Vi','Sá'];

const DatePicker = ({ label, value, onChange, required = false, dayOnly = false }) => {

  // Inicializar vista del calendario
  const initView = () => {
    if (dayOnly) {
      const n = new Date();
      return { y: n.getFullYear(), m: n.getMonth() };
    }
    const d = value ? new Date(value + 'T00:00:00') : new Date();
    return { y: d.getFullYear(), m: d.getMonth() };
  };

  const [open,  setOpen]  = useStPK(false);
  const [viewY, setViewY] = useStPK(() => initView().y);
  const [viewM, setViewM] = useStPK(() => initView().m);

  const today       = new Date(); today.setHours(0,0,0,0);
  const parsedFull  = (!dayOnly && value) ? new Date(value + 'T00:00:00') : null;
  const firstDay    = new Date(viewY, viewM, 1).getDay();
  const daysInMonth = new Date(viewY, viewM + 1, 0).getDate();

  const prevM = () => { if (viewM===0) { setViewM(11); setViewY(y=>y-1); } else setViewM(m=>m-1); };
  const nextM = () => { if (viewM===11){ setViewM(0);  setViewY(y=>y+1); } else setViewM(m=>m+1); };

  const select = (day) => {
    if (dayOnly) {
      onChange(day);
    } else {
      const d = new Date(viewY, viewM, day);
      onChange(`${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`);
    }
    setOpen(false);
  };

  // Texto del trigger
  const displayText = dayOnly
    ? (value ? `Día ${value} de cada mes` : 'Seleccionar día…')
    : (parsedFull
        ? parsedFull.toLocaleDateString('es-AR', { weekday:'short', day:'numeric', month:'long', year:'numeric' })
        : 'Seleccionar fecha…');

  const hasValue = dayOnly ? !!value : !!parsedFull;

  // ¿está seleccionado este día?
  const isSelected = (day) => {
    if (dayOnly) return Number(value) === day;
    return parsedFull && new Date(viewY, viewM, day).toDateString() === parsedFull.toDateString();
  };

  // ¿es hoy?
  const isToday = (day) => {
    if (dayOnly) return false;
    return new Date(viewY, viewM, day).getTime() === today.getTime();
  };

  return (
    <div style={{
      background: 'var(--surface-2)',
      border: `1.5px solid ${open ? 'var(--accent)' : 'var(--border)'}`,
      borderRadius: 'var(--r-lg)',
      padding: '14px 18px',
      marginBottom: 14,
      boxShadow: open ? '0 0 0 3px var(--accent-muted)' : 'none',
      transition: 'border-color 0.18s, box-shadow 0.18s',
    }}>

      {/* Label */}
      <div style={{ fontSize:11, fontWeight:700, color:'var(--t5)', textTransform:'uppercase', letterSpacing:'0.4px', marginBottom:10 }}>
        {label}{required && <span style={{ color:'var(--danger)', marginLeft:3 }}>*</span>}
      </div>

      {/* Trigger */}
      <button type="button" onClick={() => setOpen(o => !o)}
        style={{ display:'flex', alignItems:'center', gap:10, background:'none', border:'none', cursor:'pointer', width:'100%', padding:0 }}>
        <div style={{
          width:36, height:36, borderRadius:'var(--r-md)',
          background: open ? 'var(--accent-muted)' : 'var(--surface)',
          border: `1px solid ${open ? 'var(--accent)' : 'var(--border)'}`,
          display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0,
          transition:'all 0.18s',
        }}>
          <Icon name="calendar" size={17} color={open ? 'var(--accent)' : 'var(--t4)'} />
        </div>
        <span style={{
          flex: 1, textAlign:'left',
          fontSize: 15, fontWeight: hasValue ? 700 : 400,
          color: hasValue ? 'var(--t1)' : 'var(--t5)',
          letterSpacing: hasValue ? '-0.1px' : '0',
        }}>
          {displayText}
        </span>
        <Icon name={open ? 'chevronUp' : 'chevronDown'} size={15} color="var(--t5)" />
      </button>

      {/* Calendario inline */}
      {open && (
        <div style={{ marginTop:14 }}>
          <div style={{ height:1, background:'var(--border)', marginBottom:14 }} />

          {/* Navegación mes/año */}
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:14 }}>
            <button type="button" onClick={prevM} style={{
              width:34, height:34, borderRadius:'var(--r-md)',
              background:'var(--surface)', border:'1px solid var(--border)',
              display:'flex', alignItems:'center', justifyContent:'center', cursor:'pointer',
              transition:'background 0.15s',
            }}
            onMouseEnter={e=>e.currentTarget.style.background='var(--surface-3)'}
            onMouseLeave={e=>e.currentTarget.style.background='var(--surface)'}>
              <Icon name="chevronLeft" size={17} color="var(--t3)" />
            </button>

            <div style={{ textAlign:'center' }}>
              <div style={{ fontSize:15, fontWeight:800, color:'var(--t1)', letterSpacing:'-0.2px', textTransform:'capitalize' }}>
                {MONTHS_ES[viewM]} {viewY}
              </div>
              {dayOnly && (
                <div style={{ fontSize:11, color:'var(--t5)', marginTop:2 }}>
                  Elige en qué día del mes vence
                </div>
              )}
            </div>

            <button type="button" onClick={nextM} style={{
              width:34, height:34, borderRadius:'var(--r-md)',
              background:'var(--surface)', border:'1px solid var(--border)',
              display:'flex', alignItems:'center', justifyContent:'center', cursor:'pointer',
              transition:'background 0.15s',
            }}
            onMouseEnter={e=>e.currentTarget.style.background='var(--surface-3)'}
            onMouseLeave={e=>e.currentTarget.style.background='var(--surface)'}>
              <Icon name="chevronRight" size={17} color="var(--t3)" />
            </button>
          </div>

          {/* Días de semana */}
          <div style={{ display:'grid', gridTemplateColumns:'repeat(7,1fr)', gap:2, marginBottom:6 }}>
            {DAYS_ES.map(d => (
              <div key={d} style={{ textAlign:'center', fontSize:10, fontWeight:700, color:'var(--t5)', padding:'4px 0', textTransform:'uppercase', letterSpacing:'0.3px' }}>
                {d}
              </div>
            ))}
          </div>

          {/* Grilla de días */}
          <div style={{ display:'grid', gridTemplateColumns:'repeat(7,1fr)', gap:3 }}>
            {Array.from({ length: firstDay }).map((_,i) => <div key={'e'+i} />)}
            {Array.from({ length: daysInMonth }, (_,i) => i+1).map(day => {
              const sel   = isSelected(day);
              const today_ = isToday(day);
              return (
                <button key={day} type="button" onClick={() => select(day)}
                  style={{
                    aspectRatio: '1',
                    borderRadius: 'var(--r-sm)',
                    border: today_ && !sel ? '1.5px solid var(--accent)' : '1.5px solid transparent',
                    cursor: 'pointer',
                    fontSize: 13,
                    fontWeight: sel || today_ ? 700 : 400,
                    background: sel ? 'var(--accent)' : 'none',
                    color: sel ? '#fff' : today_ ? 'var(--accent)' : 'var(--t2)',
                    transition: 'background 0.12s, color 0.12s',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    lineHeight: 1,
                    boxShadow: sel ? 'var(--sh-fab)' : 'none',
                  }}
                  onMouseEnter={e => { if (!sel) e.currentTarget.style.background = 'var(--surface-3)'; }}
                  onMouseLeave={e => { if (!sel) e.currentTarget.style.background = 'none'; }}>
                  {day}
                </button>
              );
            })}
          </div>

          {/* Atajo "Hoy" — solo en modo fecha completa */}
          {!dayOnly && (
            <button type="button"
              onClick={() => {
                const d = new Date();
                onChange(`${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`);
                setOpen(false);
              }}
              style={{
                marginTop: 10, width: '100%',
                background: 'var(--accent-muted)',
                border: '1px solid rgba(37,99,235,0.18)',
                borderRadius: 'var(--r-md)',
                color: 'var(--accent)',
                fontSize: 12, fontWeight: 700, padding: '9px 0', cursor: 'pointer',
                display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
                transition: 'opacity 0.15s',
              }}
              onMouseEnter={e=>e.currentTarget.style.opacity='0.8'}
              onMouseLeave={e=>e.currentTarget.style.opacity='1'}>
              <Icon name="clock" size={14} color="var(--accent)" /> Hoy
            </button>
          )}
        </div>
      )}
    </div>
  );
};

/* ─────────────────────────────────────────────────────────────
   IconPicker — biblioteca de iconos Lucide con buscador y grupos
───────────────────────────────────────────────────────────── */
const ICON_GROUPS = [
  { name: 'Finanzas',           icons: ['creditCard','banknote','piggyBank','dollarSign','percent','receipt','wallet','landmark','target','trending','trendingDown'] },
  { name: 'Casa y servicios',   icons: ['home','building','wifi','zap','flame','droplet','lightbulb','cpu','smartphone','gauge'] },
  { name: 'Transporte y viajes',icons: ['car','bus','plane','compass','globe'] },
  { name: 'Comida y compras',   icons: ['shoppingCart','coffee','package','tag','gift'] },
  { name: 'Entretenimiento',    icons: ['film','music','headphones','gamepad','sparkles','palette','image','camera'] },
  { name: 'Salud y cuidado',    icons: ['heart','pill','shirt'] },
  { name: 'Trabajo y estudio',  icons: ['briefcase','code','bookOpen','fileText','calendar','users'] },
  { name: 'Otros',              icons: ['shield','lock','eye','clock','sun','moon','moonStar','layers','bell'] },
];

const IconPicker = ({ value, onChange, onClose, accentColor = 'var(--accent)' }) => {
  const { useState: useStIP } = React;
  const [q, setQ] = useStIP('');

  const matchesQuery = (name) => {
    if (!q) return true;
    return name.toLowerCase().includes(q.toLowerCase());
  };

  const visibleGroups = ICON_GROUPS
    .map(g => ({ ...g, icons: g.icons.filter(matchesQuery) }))
    .filter(g => g.icons.length > 0);

  const renderIconBtn = (ic) => {
    const active = value === ic;
    return (
      <button key={ic} type="button"
        onClick={() => { onChange(ic); onClose(); }}
        title={ic}
        style={{
          aspectRatio:'1', borderRadius:'var(--r-md)', cursor:'pointer',
          display:'flex', alignItems:'center', justifyContent:'center',
          background: active ? accentColor : 'var(--surface)',
          border: `1.5px solid ${active ? accentColor : 'var(--border)'}`,
          boxShadow: active ? 'var(--sh-fab)' : 'none',
          transition:'all 0.15s',
        }}>
        <Icon name={ic} size={18} color={active ? '#fff' : 'var(--t3)'} strokeWidth={1.7} />
      </button>
    );
  };

  return (
    <>
      <div className="drawer-backdrop" onClick={onClose} style={{ zIndex: 700 }} />
      <div className="drawer" style={{ zIndex: 701, maxHeight: '85vh' }}>
        <div className="drawer-handle" />

        {/* Header */}
        <div style={{ display:'flex', alignItems:'center', gap:12, padding:'10px 20px 16px', borderBottom:'1px solid var(--border)' }}>
          <button onClick={onClose} style={{ width:34,height:34,borderRadius:'var(--r-md)',background:'var(--surface-2)',border:'1px solid var(--border)',display:'flex',alignItems:'center',justifyContent:'center',flexShrink:0 }}>
            <Icon name="x" size={17} color="var(--t3)" />
          </button>
          <div>
            <div style={{ fontSize:16, fontWeight:800, color:'var(--t1)' }}>Elegir ícono</div>
            <div style={{ fontSize:12, color:'var(--t4)' }}>{ICON_GROUPS.reduce((s,g)=>s+g.icons.length,0)} disponibles</div>
          </div>
        </div>

        {/* Buscador */}
        <div style={{ padding:'14px 20px 4px' }}>
          <div style={{ display:'flex', alignItems:'center', gap:8, background:'var(--surface-2)', border:'1.5px solid var(--border)', borderRadius:'var(--r-md)', padding:'9px 14px' }}>
            <Icon name="search" size={15} color="var(--t5)" />
            <input autoFocus type="text" placeholder="Buscar ícono..." value={q}
              onChange={e => setQ(e.target.value)}
              style={{ flex:1, background:'none', border:'none', outline:'none', color:'var(--t1)', fontSize:14, fontFamily:'var(--font)' }} />
            {q && (
              <button type="button" onClick={() => setQ('')}
                style={{ background:'none', border:'none', cursor:'pointer', display:'flex', padding:2 }}>
                <Icon name="x" size={14} color="var(--t4)" />
              </button>
            )}
          </div>
        </div>

        {/* Contenido scrolleable */}
        <div style={{ padding:'10px 20px 20px', overflowY:'auto', maxHeight:'calc(85vh - 160px)' }}>
          {visibleGroups.length === 0 ? (
            <div style={{ textAlign:'center', padding:'40px 20px', color:'var(--t5)', fontSize:13 }}>
              No encontramos íconos para "{q}". Probá con otra palabra.
            </div>
          ) : (
            visibleGroups.map(group => (
              <div key={group.name} style={{ marginBottom:18 }}>
                <div style={{ fontSize:10, fontWeight:700, color:'var(--t5)', textTransform:'uppercase', letterSpacing:'0.5px', marginBottom:8, paddingLeft:2 }}>
                  {group.name}
                </div>
                <div style={{ display:'grid', gridTemplateColumns:'repeat(8, 1fr)', gap:6 }}>
                  {group.icons.map(renderIconBtn)}
                </div>
              </div>
            ))
          )}
        </div>
      </div>
    </>
  );
};

/* ─────────────────────────────────────────────────────────────
   MonthSwitcher — selector global de mes ("rumbo temporal")
   Props:
     value         string YYYY-MM
     onChange      fn(YYYY-MM)
     transactions  array opcional para mostrar saldo neto del mes en el dropdown
     monthsBack    número de meses hacia atrás (default 12)
     monthsForward número de meses hacia adelante (default 6)
     compact       bool — versión sin label expandido (solo flechas + chip)
───────────────────────────────────────────────────────────── */
const MonthSwitcher = ({ value, onChange, transactions = [], monthsBack = 12, monthsForward = 6, compact = false }) => {
  const [open, setOpen] = useStPK(false);
  // Auto-compact en mobile (< 600px) si no se forzó manualmente
  const [isNarrow, setIsNarrow] = useStPK(() => typeof window !== 'undefined' && window.innerWidth < 600);
  React.useEffect(() => {
    const onResize = () => setIsNarrow(window.innerWidth < 600);
    window.addEventListener('resize', onResize);
    return () => window.removeEventListener('resize', onResize);
  }, []);
  const useCompact = compact || isNarrow;

  const [refY, refM] = (value || `${new Date().getFullYear()}-${String(new Date().getMonth()+1).padStart(2,'0')}`).split('-').map(Number);
  const todayKey = `${new Date().getFullYear()}-${String(new Date().getMonth()+1).padStart(2,'0')}`;

  const months = [];
  for (let i = monthsForward; i >= -monthsBack; i--) {
    const d = new Date(refY, refM - 1 + i, 1);
    months.push(`${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}`);
  }

  const shiftMonth = (delta) => {
    const d = new Date(refY, refM - 1 + delta, 1);
    onChange(`${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}`);
  };

  const summaryFor = (yyyymm) => {
    const txs = transactions.filter(t => (t.date||'').startsWith(yyyymm));
    if (!txs.length) return null;
    const inc = txs.filter(t => t.type === 'income').reduce((s,t) => s+t.amount, 0);
    const exp = txs.filter(t => t.type === 'expense').reduce((s,t) => s+t.amount, 0);
    return { net: inc - exp, hasData: true };
  };

  // Capitaliza solo la primera letra (no cada palabra como text-transform:capitalize).
  const cap = (s) => s ? s.charAt(0).toUpperCase() + s.slice(1) : s;

  const labelFor = (yyyymm) => {
    const [y, m] = yyyymm.split('-').map(Number);
    return cap(new Date(y, m-1, 1).toLocaleDateString('es-AR', { month: 'long', year: 'numeric' }));
  };

  const shortLabelFor = (yyyymm) => {
    const [y, m] = yyyymm.split('-').map(Number);
    // Año en 4 dígitos para no confundir con "May 26" (parece día 26)
    return cap(new Date(y, m-1, 1).toLocaleDateString('es-AR', { month: 'short', year: 'numeric' }));
  };

  return (
    <>
      <div className="month-switcher" style={{ display:'inline-flex', alignItems:'center', gap:4, background:'var(--surface)', border:'1px solid var(--border)', borderRadius:'var(--r-md)', padding:'2px', boxShadow:'var(--sh-xs)' }}>
        <button type="button" onClick={() => shiftMonth(-1)}
          style={{ width:28, height:28, borderRadius:'var(--r-sm)', background:'none', border:'none', display:'flex', alignItems:'center', justifyContent:'center', cursor:'pointer', color:'var(--t4)' }}
          title="Mes anterior">
          <Icon name="chevronLeft" size={15} color="var(--t3)" />
        </button>
        <button type="button" onClick={() => setOpen(true)}
          style={{ background:'none', border:'none', padding:'4px 10px', cursor:'pointer', color:'var(--t2)', fontSize:13, fontWeight:700, fontFamily:'var(--font)', display:'flex', alignItems:'center', gap:6, whiteSpace:'nowrap' }}>
          <Icon name="calendar" size={13} color="var(--t4)" />
          {useCompact ? shortLabelFor(value) : labelFor(value)}
          <Icon name="chevronDown" size={12} color="var(--t5)" />
        </button>
        <button type="button" onClick={() => shiftMonth(1)}
          style={{ width:28, height:28, borderRadius:'var(--r-sm)', background:'none', border:'none', display:'flex', alignItems:'center', justifyContent:'center', cursor:'pointer', color:'var(--t4)' }}
          title="Mes siguiente">
          <Icon name="chevronRight" size={15} color="var(--t3)" />
        </button>
      </div>

      {open && (
        <>
          <div className="drawer-backdrop" onClick={() => setOpen(false)} style={{ zIndex:750 }} />
          <div className="drawer" style={{ zIndex:751, maxHeight:'70vh' }}>
            <div className="drawer-handle" />
            <div style={{ padding:'12px 20px 0' }}>
              <div style={{ fontSize:15, fontWeight:800, color:'var(--t1)', marginBottom:4 }}>Navegar por mes</div>
              <div style={{ fontSize:12, color:'var(--t4)', marginBottom:12 }}>De dónde venís y a dónde vas</div>
            </div>
            <div style={{ overflowY:'auto', maxHeight:'calc(70vh - 100px)', padding:'0 12px 16px' }}>
              {months.map(m => {
                const isSel = m === value;
                const isToday = m === todayKey;
                const isFuture = m > todayKey;
                const sum = summaryFor(m);
                return (
                  <button key={m}
                    onClick={() => { onChange(m); setOpen(false); }}
                    style={{
                      width:'100%', display:'flex', alignItems:'center', gap:10,
                      padding:'12px 14px', marginBottom:4,
                      background: isSel ? 'var(--accent-muted)' : 'none',
                      border: `1px solid ${isSel ? 'var(--accent)' : 'transparent'}`,
                      borderRadius:'var(--r-md)', cursor:'pointer',
                      transition:'background 0.15s',
                    }}
                    onMouseEnter={e => { if (!isSel) e.currentTarget.style.background='var(--surface-2)'; }}
                    onMouseLeave={e => { if (!isSel) e.currentTarget.style.background='none'; }}>
                    <div style={{ flex:1, textAlign:'left' }}>
                      <div style={{ fontSize:14, fontWeight:isSel?800:600, color:'var(--t1)', display:'flex', alignItems:'center', gap:8 }}>
                        {labelFor(m)}
                        {isToday && <span className="badge" style={{ background:'var(--accent-muted)', color:'var(--accent)', fontSize:9, padding:'1px 7px' }}>Hoy</span>}
                        {isFuture && !isToday && <span className="badge" style={{ background:'var(--warning-bg)', color:'var(--warning-text)', fontSize:9, padding:'1px 7px' }}>Futuro</span>}
                      </div>
                      {sum ? (
                        <div style={{ fontSize:11, color:'var(--t5)', marginTop:2, fontVariantNumeric:'tabular-nums' }}>
                          Saldo neto: <span style={{ color: sum.net >= 0 ? 'var(--success)' : 'var(--danger)', fontWeight:700 }}>
                            {sum.net >= 0 ? '+' : ''}{fmt(sum.net)}
                          </span>
                        </div>
                      ) : (
                        <div style={{ fontSize:11, color:'var(--t6)', marginTop:2, fontStyle:'italic' }}>
                          {isFuture ? 'Aún no llegó' : 'Sin movimientos'}
                        </div>
                      )}
                    </div>
                    {isSel && <Icon name="checkCircle" size={18} color="var(--accent)" />}
                  </button>
                );
              })}
            </div>
          </div>
        </>
      )}
    </>
  );
};

Object.assign(window, { DatePicker, IconPicker, ICON_GROUPS, MonthSwitcher });
