// logros.jsx — Celebration of completed work. No streaks that punish.
// Counts completed tasks by Día / Semana / Mes, shows top pillar,
// and renders a "jardín" of small flowers earned (one per completed).

// Lightweight "completion log": we don't track per-completion timestamps in
// state — we infer from task.done + task.date. For day/week/month windows we
// filter the same way. Future: store completedAt on toggle for true history.

function LogrosCard({ tasks, theme }) {
  const [period, setPeriod] = React.useState('week');
  const [offsetN, setOffsetN] = React.useState(0); // 0 = current period; negative = past
  const now = new Date();

  let start, end, periodLabel, rangeLabel, emptyMsg;
  if (period === 'day') {
    start = new Date(now); start.setDate(now.getDate() + offsetN); start.setHours(0,0,0,0);
    end = new Date(start); end.setHours(23,59,59,999);
    const MS = ['Ene','Feb','Mar','Abr','May','Jun','Jul','Ago','Sep','Oct','Nov','Dic'];
    rangeLabel = offsetN === 0 ? 'Hoy' : offsetN === -1 ? 'Ayer' : `${start.getDate()} ${MS[start.getMonth()]}`;
    periodLabel = 'Hoy';
    emptyMsg = offsetN === 0 ? 'Aún sin nada hecho hoy. Va a estar bien 🌸' : 'Nada registrado este día.';
  } else if (period === 'month') {
    const base = new Date(now.getFullYear(), now.getMonth() + offsetN, 1);
    start = base;
    end = new Date(base.getFullYear(), base.getMonth()+1, 0, 23,59,59,999);
    const M = ['Enero','Febrero','Marzo','Abril','Mayo','Junio','Julio','Agosto','Septiembre','Octubre','Noviembre','Diciembre'];
    rangeLabel = offsetN === 0 ? `${M[base.getMonth()]}` : `${M[base.getMonth()]} ${base.getFullYear() !== now.getFullYear() ? base.getFullYear() : ''}`.trim();
    periodLabel = 'Este mes';
    emptyMsg = offsetN === 0 ? 'Mes empezando. Cada cosa hecha cuenta 🌸' : 'Sin registros este mes.';
  } else {
    const day = now.getDay();
    const dayOffset = day === 0 ? -6 : 1 - day;
    start = new Date(now); start.setDate(now.getDate() + dayOffset + (offsetN * 7)); start.setHours(0,0,0,0);
    end = new Date(start); end.setDate(start.getDate() + 6); end.setHours(23,59,59,999);
    const MS = ['Ene','Feb','Mar','Abr','May','Jun','Jul','Ago','Sep','Oct','Nov','Dic'];
    const rangeBase = start.getMonth() === end.getMonth()
      ? `${start.getDate()}–${end.getDate()} ${MS[start.getMonth()]}`
      : `${start.getDate()} ${MS[start.getMonth()]} – ${end.getDate()} ${MS[end.getMonth()]}`;
    rangeLabel = offsetN === 0 ? `Esta semana · ${rangeBase}` : offsetN === -1 ? `Semana pasada · ${rangeBase}` : rangeBase;
    periodLabel = 'Esta semana';
    emptyMsg = offsetN === 0 ? 'Semana empezando. Sin presión 🌸' : 'Sin registros esta semana.';
  }

  const done = tasks.filter(t => {
    if (!t.done) return false;
    const d = new Date(t.date + 'T12:00:00');
    return d >= start && d <= end;
  });

  // Pillar tally
  const counts = {};
  done.forEach(t => { counts[t.pillar] = (counts[t.pillar] || 0) + 1; });
  const sorted = Object.entries(counts).sort((a,b) => b[1] - a[1]);
  const topPillar = sorted[0];

  // Soft milestone (celebración, no castigo)
  let milestone = null;
  if (period === 'day' && done.length >= 5) milestone = 'Un día completo 💛';
  else if (period === 'day' && done.length >= 3) milestone = 'Día con momentum ✨';
  else if (period === 'week' && done.length >= 20) milestone = 'Tu mejor semana 🌟';
  else if (period === 'week' && done.length >= 10) milestone = 'Semana con ritmo ✨';
  else if (period === 'month' && done.length >= 60) milestone = 'Mes lleno 🌸';
  else if (period === 'month' && done.length >= 25) milestone = 'Mes con ritmo ✨';

  const PeriodSwitcher = () => (
    <div style={{
      display: 'inline-flex', background: theme.bg,
      borderRadius: 999, padding: 2,
      border: `1px solid ${theme.border}`,
    }}>
      {[
        { id: 'day', label: 'Día' },
        { id: 'week', label: 'Semana' },
        { id: 'month', label: 'Mes' },
      ].map(o => {
        const active = period === o.id;
        return (
          <button key={o.id} onClick={() => setPeriod(o.id)} style={{
            appearance: 'none', cursor: 'pointer',
            background: active ? theme.surface : 'transparent',
            boxShadow: active ? '0 1px 2px rgba(31,21,21,0.08)' : 'none',
            border: 'none', borderRadius: 999,
            padding: '4px 10px', fontSize: 11, fontWeight: 600,
            color: active ? theme.text : theme.textSoft,
            fontFamily: 'inherit', letterSpacing: -0.05,
          }}>{o.label}</button>
        );
      })}
    </div>
  );

  // Garden cap — max 36 flowers visible to avoid runaway
  const flowers = done.slice(0, 36);
  const extra = done.length - flowers.length;

  return (
    <div style={{
      margin: '14px 18px',
      background: 'linear-gradient(160deg, #FFF7F2 0%, #FFEEF3 100%)',
      border: `1px solid ${theme.border}`,
      borderRadius: 16,
      padding: '14px 14px 14px',
      position: 'relative', overflow: 'hidden',
    }}>
      {/* Soft decoration */}
      <div style={{
        position: 'absolute', top: -20, right: -20,
        width: 90, height: 90, borderRadius: '50%',
        background: 'rgba(201,98,107,0.06)',
      }} />

      {/* Title + period switcher */}
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        marginBottom: 10, gap: 8, position: 'relative',
      }}>
        <div style={{
          fontSize: 15, fontWeight: 700, color: theme.text,
          letterSpacing: -0.2,
        }}>Tareas completadas</div>
        <PeriodSwitcher />
      </div>

      {/* Period navigator — prev / range / next */}
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        marginBottom: 12, position: 'relative',
        background: 'rgba(255,255,255,0.55)',
        borderRadius: 10, padding: '4px 6px',
        border: '1px solid rgba(255,255,255,0.8)',
      }}>
        <button onClick={() => setOffsetN(offsetN - 1)} style={{
          appearance: 'none', cursor: 'pointer',
          background: 'transparent', border: 'none',
          width: 26, height: 26, borderRadius: 8,
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          color: theme.textSoft, fontFamily: 'inherit',
        }} aria-label="Anterior">
          <svg width="12" height="12" viewBox="0 0 12 12" fill="none">
            <path d="M7.5 2.5L4 6l3.5 3.5" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </button>
        <div style={{
          fontSize: 12, fontWeight: 600, color: theme.text,
          letterSpacing: -0.05,
        }}>{rangeLabel}</div>
        <button onClick={() => offsetN < 0 && setOffsetN(offsetN + 1)} disabled={offsetN >= 0} style={{
          appearance: 'none', cursor: offsetN < 0 ? 'pointer' : 'default',
          background: 'transparent', border: 'none',
          width: 26, height: 26, borderRadius: 8,
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          color: offsetN < 0 ? theme.textSoft : 'rgba(0,0,0,0.18)',
          fontFamily: 'inherit',
        }} aria-label="Siguiente">
          <svg width="12" height="12" viewBox="0 0 12 12" fill="none">
            <path d="M4.5 2.5L8 6l-3.5 3.5" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </button>
      </div>

      {/* Stat line — small caps label + medium number, no floating */}
      {done.length > 0 && topPillar && (
        <div style={{
          marginBottom: 10, position: 'relative',
          fontSize: 13, color: theme.textSoft, lineHeight: 1.4,
          letterSpacing: -0.05,
        }}>
          <span style={{ color: theme.text, fontWeight: 600 }}>{done.length}</span>{' '}
          {done.length === 1 ? 'cosa resuelta' : 'cosas resueltas'} · {topPillar[1]} para{' '}
          <span style={{ color: PILLARS[topPillar[0]].text, fontWeight: 600 }}>
            {PILLARS[topPillar[0]].label.toLowerCase()}
          </span>
          {topPillar[0] === 'personal' && ' 💛'}
        </div>
      )}

      {/* Task list */}
      {done.length > 0 ? (
        <div style={{
          display: 'flex', flexDirection: 'column',
          background: 'rgba(255,255,255,0.55)',
          border: '1px solid rgba(255,255,255,0.8)',
          borderRadius: 12, overflow: 'hidden',
          marginBottom: milestone ? 10 : 0, position: 'relative',
        }}>
          {done.slice(0, 12).map((t, i) => {
            const p = PILLARS[t.pillar];
            return (
              <div key={t.id} style={{
                display: 'flex', alignItems: 'center', gap: 10,
                padding: '9px 12px',
                borderTop: i === 0 ? 'none' : `1px solid ${theme.borderSoft || 'rgba(0,0,0,0.05)'}`,
                animation: `mf-fade-in .35s ease-out ${i * 0.02}s both`,
              }}>
                <span style={{
                  width: 8, height: 8, borderRadius: 4,
                  background: p.text, flexShrink: 0,
                }} />
                <span style={{
                  flex: 1, minWidth: 0,
                  fontSize: 13, color: theme.text, fontWeight: 500,
                  letterSpacing: -0.05, lineHeight: 1.35,
                  overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
                }}>{t.title}</span>
                <span style={{
                  fontSize: 10.5, color: theme.textSoft, fontWeight: 500,
                  letterSpacing: 0.1, flexShrink: 0,
                }}>{p.label.toLowerCase()}</span>
              </div>
            );
          })}
          {done.length > 12 && (
            <div style={{
              padding: '8px 12px', borderTop: `1px solid ${theme.borderSoft || 'rgba(0,0,0,0.05)'}`,
              fontSize: 11, color: theme.textSoft, fontWeight: 600,
              textAlign: 'center', letterSpacing: 0.05,
            }}>+{done.length - 12} más</div>
          )}
        </div>
      ) : (
        <div style={{
          fontSize: 12.5, lineHeight: 1.45, color: theme.textSoft,
          background: 'rgba(255,255,255,0.55)', borderRadius: 10,
          padding: '10px 12px', position: 'relative',
        }}>{emptyMsg}</div>
      )}

      {/* Milestone */}
      {milestone && (
        <div style={{
          marginTop: 4, fontSize: 12, color: '#C9626B', fontWeight: 700,
          letterSpacing: -0.05, textAlign: 'center',
          padding: '8px 0 2px', position: 'relative',
        }}>{milestone}</div>
      )}

    </div>
  );
}

Object.assign(window, { LogrosCard });
