// daily-mood.jsx — Daily mood check-in card.
// Appears once per day at the top of Home until tapped.
// State persisted in localStorage as mamaflow.lastMoodCheck (ISO date).

function DailyMoodCheckin({ theme, onPick, currentMood }) {
  const [dismissed, setDismissed] = React.useState(false);
  const [show, setShow] = React.useState(() => {
    try {
      const last = localStorage.getItem('mamaflow.lastMoodCheck');
      return last !== new Date().toISOString().slice(0, 10);
    } catch { return true; }
  });

  if (!show || dismissed) return null;

  const persist = () => {
    try { localStorage.setItem('mamaflow.lastMoodCheck', new Date().toISOString().slice(0, 10)); } catch {}
  };

  const pick = (id) => {
    onPick(id);
    persist();
    setDismissed(true);
  };
  const skip = () => { persist(); setDismissed(true); };

  const hour = new Date().getHours();
  const prompt = hour < 12 ? '¿Cómo amaneciste?'
              : hour < 18 ? '¿Cómo va el día?'
              : '¿Cómo te ha tratado el día?';

  return (
    <div style={{
      margin: '0 18px 14px',
      background: theme.surface,
      border: `1px solid ${theme.border}`,
      borderRadius: 16,
      padding: '14px 14px 12px',
      position: 'relative',
    }}>
      <button onClick={skip} aria-label="Cerrar"
        style={{
          position: 'absolute', top: 8, right: 8,
          appearance: 'none', cursor: 'pointer',
          background: 'transparent', border: 'none',
          color: theme.textSoft, fontSize: 14,
          width: 22, height: 22, borderRadius: 11,
          fontFamily: 'inherit',
        }}>✕</button>
      <div style={{
        fontSize: 13.5, fontWeight: 700, color: theme.text,
        letterSpacing: -0.1, marginBottom: 10,
      }}>{prompt}</div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 6 }}>
        {MOODS.map(m => {
          const isCurrent = m.id === currentMood;
          return (
            <button key={m.id} onClick={() => pick(m.id)}
              style={{
                appearance: 'none', cursor: 'pointer',
                background: isCurrent ? theme.primarySoft : theme.bg,
                border: `1px solid ${isCurrent ? theme.primaryBorder : theme.border}`,
                borderRadius: 12, padding: '10px 4px 8px',
                display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
                fontFamily: 'inherit',
                transition: 'all .15s ease',
              }}>
              <span style={{ fontSize: 22, lineHeight: 1 }}>{m.emoji}</span>
              <span style={{
                fontSize: 10.5, fontWeight: 600, letterSpacing: 0.1,
                color: isCurrent ? theme.primary : theme.textSoft,
              }}>{m.label}</span>
            </button>
          );
        })}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Weekly balance insight — for Calendar screen
// Shows pillar mix for current week, with a soft observation
// ─────────────────────────────────────────────────────────────
function WeeklyBalance({ tasks, theme, featured = false }) {
  const [period, setPeriod] = React.useState('week'); // 'day' | 'week' | 'month'
  const now = new Date();

  // Compute range based on period
  let start, end, rangeLabel, periodLabel, periodWord;
  if (period === 'day') {
    start = new Date(now); start.setHours(0,0,0,0);
    end = new Date(now); end.setHours(23,59,59,999);
    const MON_SHORT = ['Ene','Feb','Mar','Abr','May','Jun','Jul','Ago','Sep','Oct','Nov','Dic'];
    rangeLabel = `${now.getDate()} ${MON_SHORT[now.getMonth()]}`;
    periodLabel = 'Balance hoy';
    periodWord = 'el día';
  } else if (period === 'month') {
    start = new Date(now.getFullYear(), now.getMonth(), 1);
    end = new Date(now.getFullYear(), now.getMonth() + 1, 0, 23, 59, 59, 999);
    const MON = ['Enero','Febrero','Marzo','Abril','Mayo','Junio','Julio','Agosto','Septiembre','Octubre','Noviembre','Diciembre'];
    rangeLabel = MON[now.getMonth()];
    periodLabel = 'Balance mensual';
    periodWord = 'el mes';
  } else {
    const day = now.getDay();
    const mondayOffset = day === 0 ? -6 : 1 - day;
    start = new Date(now); start.setDate(now.getDate() + mondayOffset);
    start.setHours(0,0,0,0);
    end = new Date(start); end.setDate(start.getDate() + 6);
    end.setHours(23,59,59,999);
    const MON_SHORT = ['Ene','Feb','Mar','Abr','May','Jun','Jul','Ago','Sep','Oct','Nov','Dic'];
    rangeLabel = start.getMonth() === end.getMonth()
      ? `${start.getDate()}–${end.getDate()} ${MON_SHORT[start.getMonth()]}`
      : `${start.getDate()} ${MON_SHORT[start.getMonth()]} – ${end.getDate()} ${MON_SHORT[end.getMonth()]}`;
    periodLabel = 'Balance semanal';
    periodWord = 'la semana';
  }

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

  // Period switcher
  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>
  );

  if (inRange.length === 0) {
    return (
      <div style={{
        margin: featured ? '14px 14px 18px' : '14px 18px',
        background: theme.surface,
        border: `1px solid ${featured ? theme.primaryBorder : theme.border}`,
        borderRadius: featured ? 20 : 16,
        padding: featured ? '18px 18px 16px' : '14px 14px 12px',
        boxShadow: featured ? '0 6px 18px rgba(31,21,21,0.06)' : 'none',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: featured ? 12 : 10 }}>
          <div style={{
            fontSize: featured ? 11 : 15,
            fontWeight: 700,
            color: featured ? theme.primary : theme.text,
            letterSpacing: featured ? 1.4 : -0.2,
            textTransform: featured ? 'uppercase' : 'none',
          }}>{featured ? 'Balance de pilares' : periodLabel}</div>
          <PeriodSwitcher />
        </div>
        <div style={{
          fontSize: 12.5, lineHeight: 1.4, color: theme.textSoft,
          background: theme.bg, borderRadius: 10, padding: '10px 12px',
        }}>💭 Sin tareas en {periodWord}. Espacio limpio 🌸</div>
      </div>
    );
  }

  // Count by pillar
  const counts = {};
  inRange.forEach(t => { counts[t.pillar] = (counts[t.pillar] || 0) + 1; });
  const total = inRange.length;
  const sorted = Object.entries(counts).sort((a, b) => b[1] - a[1]);

  // Insight text
  const top = sorted[0];
  const topPct = Math.round((top[1] / total) * 100);
  const hasPersonal = counts['personal'] || 0;
  const personalPct = Math.round((hasPersonal / total) * 100);

  let observation = '';
  if (topPct >= 60) {
    observation = `${topPct}% de ${periodWord} es ${PILLARS[top[0]].label.toLowerCase()}. Ojo con el balance.`;
  } else if (personalPct === 0) {
    observation = `En ${periodWord} no hay nada para ti. ¿Le metemos algo?`;
  } else if (personalPct < 10) {
    observation = `Solo ${personalPct}% de ${periodWord} es para ti. Mereces más.`;
  } else {
    observation = `Buen balance ${period === 'day' ? 'hoy' : period === 'month' ? 'este mes' : 'esta semana'} 🌸`;
  }

  return (
    <div style={{
      margin: featured ? '14px 14px 18px' : '14px 18px',
      background: theme.surface,
      border: `1px solid ${featured ? theme.primaryBorder : theme.border}`,
      borderRadius: featured ? 20 : 16,
      padding: featured ? '18px 18px 16px' : '14px 14px 12px',
      boxShadow: featured ? '0 6px 18px rgba(31,21,21,0.06), 0 1px 2px rgba(31,21,21,0.04)' : 'none',
      position: 'relative', overflow: 'hidden',
    }}>
      {featured && (
        <div style={{
          position: 'absolute', top: -40, right: -40,
          width: 120, height: 120, borderRadius: '50%',
          background: theme.primarySoft, opacity: 0.55,
          pointerEvents: 'none',
        }} />
      )}
      <div style={{
        position: 'relative',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        marginBottom: featured ? 4 : 10, gap: 8,
      }}>
        <div style={{
          fontSize: featured ? 11 : 15,
          fontWeight: 700, color: featured ? theme.primary : theme.text,
          letterSpacing: featured ? 1.4 : -0.2,
          textTransform: featured ? 'uppercase' : 'none',
        }}>{featured ? 'Balance de pilares' : periodLabel}</div>
        <PeriodSwitcher />
      </div>

      {featured && (
        <div style={{
          fontSize: 20, fontWeight: 700, color: theme.text,
          letterSpacing: -0.4, lineHeight: 1.15,
          marginBottom: 2, position: 'relative',
        }}>{periodLabel.replace('Balance ', '').replace(/^./, c => c.toUpperCase())}</div>
      )}

      {/* Range subtitle, consistente con Tareas completadas */}
      <div style={{
        position: 'relative',
        fontSize: featured ? 12.5 : 12, fontWeight: 500, color: theme.textSoft,
        letterSpacing: -0.05, marginBottom: featured ? 14 : 10,
      }}>{rangeLabel}</div>

      {/* Stacked bar */}
      <div style={{
        position: 'relative',
        display: 'flex',
        height: featured ? 14 : 10,
        borderRadius: featured ? 7 : 5, overflow: 'hidden',
        background: theme.borderSoft || theme.border,
        marginBottom: featured ? 14 : 10,
      }}>
        {sorted.map(([pid, n]) => {
          const p = PILLARS[pid];
          const pct = (n / total) * 100;
          return (
            <div key={pid} title={`${p.label}: ${n}`}
              style={{
                width: `${pct}%`,
                background: p.text,
                opacity: 0.85,
              }} />
          );
        })}
      </div>

      {/* Legend */}
      <div style={{
        position: 'relative',
        display: 'flex', flexWrap: 'wrap',
        gap: featured ? '8px 14px' : '6px 12px',
        marginBottom: featured ? 14 : 10,
      }}>
        {sorted.map(([pid, n]) => {
          const p = PILLARS[pid];
          const pct = Math.round((n / total) * 100);
          return (
            <div key={pid} style={{
              display: 'inline-flex', alignItems: 'center', gap: 5,
              fontSize: featured ? 12.5 : 11.5, fontWeight: 600, color: theme.text,
            }}>
              <span style={{
                width: featured ? 10 : 8, height: featured ? 10 : 8,
                borderRadius: featured ? 5 : 4,
                background: p.text, opacity: 0.85,
              }} />
              {p.emoji} {p.label} <span style={{ color: theme.textSoft, fontWeight: 500 }}>{pct}%</span>
            </div>
          );
        })}
      </div>

      {/* Observation */}
      <div style={{
        position: 'relative',
        fontSize: featured ? 13 : 12.5, lineHeight: 1.45,
        color: featured ? theme.text : theme.textSoft,
        background: featured ? theme.primarySoft : theme.bg,
        border: featured ? `1px solid ${theme.primaryBorder}` : 'none',
        borderRadius: featured ? 12 : 10,
        padding: featured ? '11px 12px' : '8px 10px',
        letterSpacing: -0.05,
        fontWeight: featured ? 500 : 400,
      }}>
        💭 {observation}
      </div>
    </div>
  );
}

Object.assign(window, { DailyMoodCheckin, WeeklyBalance });
