
// ── Dashboard Screen — Responsive ────────────────────────────────────────────
function CalorieRing({ consumed, goal }) {
  const r = 52, cx = 64, cy = 64;
  const circ = 2 * Math.PI * r;
  const pct = Math.min(consumed / goal, 1);
  return (
    <svg width={128} height={128} style={{ flexShrink: 0 }}>
      <circle cx={cx} cy={cy} r={r} fill="none" stroke="#F0F0F0" strokeWidth={12} />
      <circle cx={cx} cy={cy} r={r} fill="none" stroke="#FF6B35" strokeWidth={12}
        strokeDasharray={`${pct * circ} ${circ}`} strokeLinecap="round"
        transform={`rotate(-90 ${cx} ${cy})`}
        style={{ transition: 'stroke-dasharray .6s cubic-bezier(.4,0,.2,1)' }} />
      <text x={cx} y={cy - 6} textAnchor="middle" style={{ fontSize: 20, fontWeight: 700, fill: '#1C1C1E', fontFamily: 'system-ui' }}>{Math.round(pct * 100)}%</text>
      <text x={cx} y={cy + 14} textAnchor="middle" style={{ fontSize: 11, fill: '#8E8E93', fontFamily: 'system-ui' }}>objetivo</text>
    </svg>
  );
}

function ScreenDashboard({ onNavigate }) {
  const { state, calcDayNutrition, getMealsForDate, getWeightForDate, getWorkoutsForDate, calcMealNutrition } = useSalud();
  const today = new Date().toISOString().split('T')[0];
  const nutrition  = calcDayNutrition(today);
  const todayWeight = getWeightForDate(today);
  const todayWorkouts = getWorkoutsForDate(today);
  const meals = getMealsForDate(today);
  const { goals } = state;
  const remaining = Math.max(goals.kcal - nutrition.kcal, 0);
  const burned = todayWorkouts.reduce((a, w) => a + w.kcal, 0);

  const weekDays = Array.from({ length: 7 }, (_, i) => {
    const d = new Date(); d.setDate(d.getDate() - (6 - i));
    const key = d.toISOString().split('T')[0];
    const n = calcDayNutrition(key);
    const pct = Math.min(n.kcal / goals.kcal, 1);
    return { key, pct, isToday: key === today, label: d.toLocaleDateString('es-ES', { weekday: 'narrow' }) };
  });

  const MEAL_ORDER = ['Desayuno', 'Almuerzo', 'Comida', 'Merienda', 'Cena'];
  const sortedMeals = [...meals].sort((a, b) => MEAL_ORDER.indexOf(a.type) - MEAL_ORDER.indexOf(b.type));
  const dateStr = new Date().toLocaleDateString('es-ES', { weekday: 'long', day: 'numeric', month: 'long' });

  return (
    <div className="page">
      {/* Header */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 24 }}>
        <div>
          <h1 style={{ fontSize: 26, fontWeight: 700, color: '#1C1C1E' }}>Buenos días, Rubén</h1>
          <p style={{ fontSize: 14, color: '#8E8E93', marginTop: 4, textTransform: 'capitalize' }}>{dateStr}</p>
        </div>
        <div className="avatar">{burned > 0 ? '🔥' : 'R'}</div>
      </div>

      {/* Top stats */}
      <div className="grid-4" style={{ marginBottom: 16 }}>
        {[
          { label: 'Kcal ingeridas', val: Math.round(nutrition.kcal), color: '#FF6B35', unit: '' },
          { label: 'Restantes', val: Math.round(remaining), color: '#1C1C1E', unit: '' },
          { label: 'Quemadas', val: burned, color: '#34C759', unit: '' },
          { label: 'Peso actual', val: todayWeight ? `${todayWeight.kg}` : '—', color: '#007AFF', unit: todayWeight ? 'kg' : '' },
        ].map(s => (
          <div key={s.label} className="stat-card">
            <div className="stat-val" style={{ color: s.color }}>{s.val}<span style={{ fontSize: 14, fontWeight: 400, color: '#8E8E93' }}>{s.unit}</span></div>
            <div className="stat-label">{s.label}</div>
          </div>
        ))}
      </div>

      {/* Calorie + macros */}
      <div className="card">
        <div className="card-title">Calorías de hoy</div>
        <div style={{ display: 'flex', gap: 24, alignItems: 'center', flexWrap: 'wrap' }}>
          <CalorieRing consumed={nutrition.kcal} goal={goals.kcal} />
          <div style={{ flex: 1, minWidth: 200 }}>
            {[
              { label: 'Proteína', val: nutrition.prot, goal: goals.prot, color: '#FF6B35' },
              { label: 'Carbohidratos', val: nutrition.carbs, goal: goals.carbs, color: '#FF9500' },
              { label: 'Grasa', val: nutrition.fat, goal: goals.fat, color: '#FFD60A' },
            ].map(m => (
              <div key={m.label} style={{ marginBottom: 14 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13, marginBottom: 4 }}>
                  <span style={{ fontWeight: 600, color: '#1C1C1E' }}>{m.label}</span>
                  <span style={{ color: '#8E8E93' }}>{Math.round(m.val)}g / {m.goal}g</span>
                </div>
                <div className="prog-bar"><div className="prog-fill" style={{ width: `${Math.min(m.val/m.goal*100,100)}%`, background: m.color }} /></div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Week chart */}
      <div className="card">
        <div className="card-title">Esta semana</div>
        <div style={{ display: 'flex', gap: 8, alignItems: 'flex-end', height: 72 }}>
          {weekDays.map(day => (
            <div key={day.key} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4 }}>
              <div style={{ width: '100%', height: 52, display: 'flex', alignItems: 'flex-end' }}>
                <div style={{ width: '100%', height: `${Math.max(day.pct * 52, 4)}px`, background: day.isToday ? '#FF6B35' : day.pct > 0 ? '#FFD6C4' : '#F0F0F0', borderRadius: '4px 4px 0 0', transition: 'height .4s' }} />
              </div>
              <div style={{ fontSize: 11, color: day.isToday ? '#FF6B35' : '#8E8E93', fontWeight: day.isToday ? 700 : 400 }}>{day.label}</div>
            </div>
          ))}
        </div>
      </div>

      {/* Today's meals */}
      <div className="card">
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
          <div className="card-title" style={{ marginBottom: 0 }}>Comidas de hoy</div>
          <button className="btn-primary" style={{ fontSize: 13, padding: '8px 14px' }} onClick={() => onNavigate(1)}>+ Añadir</button>
        </div>
        {sortedMeals.length === 0 ? (
          <div className="empty" style={{ padding: '24px 0' }}>
            <div className="empty-icon">🍽</div>
            <div className="empty-title">Sin comidas registradas</div>
          </div>
        ) : sortedMeals.map(meal => {
          const n = calcMealNutrition(meal);
          return (
            <div key={meal.id} className="list-row">
              <div style={{ flex: 1 }}>
                <div style={{ fontWeight: 600, fontSize: 15 }}>{meal.type}</div>
                <div style={{ fontSize: 13, color: '#8E8E93' }}>{meal.items?.length || 0} alimentos · {Math.round(n.prot)}g prot</div>
              </div>
              <div style={{ textAlign: 'right' }}>
                <div style={{ fontWeight: 700, color: '#FF6B35', fontSize: 16 }}>{Math.round(n.kcal)}</div>
                <div style={{ fontSize: 11, color: '#8E8E93' }}>kcal</div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

Object.assign(window, { ScreenDashboard });
