
// ── Progress Screen — Responsive ─────────────────────────────────────────────
const { useState: useStateProgress, useRef: useRefProgress } = React;

function WeightChart({ weights }) {
  if (weights.length < 2) return null;
  const W = 560, H = 140, PAD = { t: 12, r: 20, b: 28, l: 42 };
  const vals = weights.map(w => w.kg);
  const min = Math.min(...vals) - 0.5, max = Math.max(...vals) + 0.5;
  const xS = i => PAD.l + (i/(weights.length-1))*(W-PAD.l-PAD.r);
  const yS = v => PAD.t + (1-(v-min)/(max-min))*(H-PAD.t-PAD.b);
  const pts = weights.map((w,i) => `${xS(i)},${yS(w.kg)}`).join(' ');
  const area = `M${xS(0)},${yS(weights[0].kg)} ` + weights.map((w,i) => `L${xS(i)},${yS(w.kg)}`).join(' ') + ` L${xS(weights.length-1)},${H-PAD.b} L${xS(0)},${H-PAD.b}Z`;
  return (
    <svg width="100%" viewBox={`0 0 ${W} ${H}`} style={{ overflow:'visible' }}>
      <defs>
        <linearGradient id="wg" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="#FF6B35" stopOpacity=".25"/>
          <stop offset="100%" stopColor="#FF6B35" stopOpacity="0"/>
        </linearGradient>
      </defs>
      {[min+0.5,(min+max)/2,max-0.5].map((v,i) => (
        <g key={i}>
          <line x1={PAD.l} y1={yS(v)} x2={W-PAD.r} y2={yS(v)} stroke="#F0F0F0" strokeWidth="1"/>
          <text x={PAD.l-5} y={yS(v)+4} textAnchor="end" fontSize="10" fill="#AEAEB2">{v.toFixed(1)}</text>
        </g>
      ))}
      <path d={area} fill="url(#wg)"/>
      <polyline points={pts} fill="none" stroke="#FF6B35" strokeWidth="2.5" strokeLinejoin="round" strokeLinecap="round"/>
      {weights.map((w,i) => <circle key={i} cx={xS(i)} cy={yS(w.kg)} r="4" fill="#FF6B35" stroke="#fff" strokeWidth="2"/>)}
      {[0,Math.floor((weights.length-1)/2),weights.length-1].map(i => (
        <text key={i} x={xS(i)} y={H-6} textAnchor="middle" fontSize="10" fill="#AEAEB2">
          {new Date(weights[i].date+'T12:00').toLocaleDateString('es-ES',{day:'numeric',month:'short'})}
        </text>
      ))}
    </svg>
  );
}

function ScreenProgress() {
  const { state, addWeight, uploadPhoto, deletePhoto } = useSalud();
  const [tab, setTab] = useStateProgress('peso');
  const [showAddWeight, setShowAddWeight] = useStateProgress(false);
  const [newKg, setNewKg] = useStateProgress('');
  const [newDate, setNewDate] = useStateProgress(new Date().toISOString().split('T')[0]);
  const [saving, setSaving] = useStateProgress(false);
  const fileRef = useRefProgress(null);

  const sorted = [...state.weights].sort((a,b) => a.date.localeCompare(b.date));
  const first = sorted[0], last = sorted[sorted.length-1];
  const change = last && first ? (last.kg - first.kg).toFixed(1) : null;
  const days = first && last ? Math.max(1, (new Date(last.date)-new Date(first.date))/86400000) : 1;

  const handleAdd = async () => {
    if (!newKg) return;
    setSaving(true);
    await addWeight(newDate, parseFloat(newKg));
    setSaving(false); setNewKg(''); setShowAddWeight(false);
  };

  const handlePhoto = async (e) => {
    const file = e.target.files[0];
    if (!file) return;
    await uploadPhoto(file, new Date().toISOString().split('T')[0], '');
  };

  return (
    <div className="page">
      <div className="page-header"><h1>Progreso</h1></div>

      <div className="tabs">
        {[['peso','⚖️ Peso'],['fotos','📸 Fotos'],['stats','📊 Stats']].map(([k,l]) => (
          <button key={k} className={`tab-btn${tab===k?' active':''}`} onClick={() => setTab(k)}>{l}</button>
        ))}
      </div>

      {tab === 'peso' && (
        <>
          {/* Stats */}
          <div className="grid-3" style={{ marginBottom: 16 }}>
            <div className="stat-card">
              <div className="stat-val">{last?last.kg:'—'}</div>
              <div className="stat-label">kg actual</div>
            </div>
            <div className="stat-card">
              <div className="stat-val">{first?first.kg:'—'}</div>
              <div className="stat-label">kg inicial</div>
            </div>
            <div className="stat-card">
              <div className="stat-val" style={{ color: change<0?'#16A34A':'#FF3B30' }}>{change!==null?(change>0?'+':'')+change:'—'}</div>
              <div className="stat-label">kg cambio</div>
            </div>
          </div>

          {/* Chart */}
          {sorted.length >= 2 && (
            <div className="card">
              <div className="card-title">Evolución del peso</div>
              <WeightChart weights={sorted.slice(-14)} />
            </div>
          )}

          {/* Add weight */}
          {showAddWeight ? (
            <div className="card">
              <div className="card-title">Registrar peso</div>
              <div className="form-row">
                <div className="form-group">
                  <label className="form-label">Peso (kg)</label>
                  <input className="form-input" type="number" step="0.1" placeholder="80.5" value={newKg} onChange={e => setNewKg(e.target.value)} />
                </div>
                <div className="form-group">
                  <label className="form-label">Fecha</label>
                  <input className="form-input" type="date" value={newDate} onChange={e => setNewDate(e.target.value)} />
                </div>
              </div>
              <div style={{ display:'flex', gap:10 }}>
                <button className="btn-secondary" style={{ flex:1 }} onClick={() => setShowAddWeight(false)}>Cancelar</button>
                <button className="btn-primary" style={{ flex:2 }} onClick={handleAdd} disabled={saving}>{saving?'Guardando…':'Guardar'}</button>
              </div>
            </div>
          ) : (
            <button className="btn-primary" style={{ width:'100%', marginBottom:16 }} onClick={() => setShowAddWeight(true)}>+ Registrar peso</button>
          )}

          {/* History */}
          <div className="card">
            <div className="card-title">Historial</div>
            {[...sorted].reverse().slice(0,15).map((w,i,arr) => (
              <div key={w.id} className="list-row" style={{ borderBottom: i===arr.length-1?'none':'1px solid #F2F2F7' }}>
                <div style={{ flex:1, color:'#8E8E93', fontSize:14 }}>
                  {new Date(w.date+'T12:00').toLocaleDateString('es-ES',{weekday:'short',day:'numeric',month:'short',year:'numeric'})}
                </div>
                <div style={{ fontWeight:700, fontSize:18 }}>{w.kg} <span style={{ fontSize:13, fontWeight:400, color:'#8E8E93' }}>kg</span></div>
              </div>
            ))}
          </div>
        </>
      )}

      {tab === 'fotos' && (
        <>
          <button className="btn-primary" style={{ width:'100%', marginBottom:16 }} onClick={() => fileRef.current.click()}>
            📷 Añadir foto de progreso
          </button>
          <input ref={fileRef} type="file" accept="image/*" style={{ display:'none' }} onChange={handlePhoto} />
          {state.photos.length === 0 ? (
            <div className="empty"><div className="empty-icon">📸</div><div className="empty-title">Sin fotos aún</div><div className="empty-sub">Añade fotos para ver tu evolución</div></div>
          ) : (
            <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fill,minmax(160px,1fr))', gap:10 }}>
              {[...state.photos].reverse().map(p => (
                <div key={p.id} style={{ borderRadius:12, overflow:'hidden', position:'relative', aspectRatio:'3/4', background:'#F0F0F0' }}>
                  <img src={p.url} alt="" style={{ width:'100%', height:'100%', objectFit:'cover' }} />
                  <div style={{ position:'absolute', bottom:0, left:0, right:0, background:'linear-gradient(transparent,rgba(0,0,0,.6))', padding:'20px 10px 10px' }}>
                    <div style={{ fontSize:12, color:'#fff', fontWeight:600 }}>
                      {new Date(p.date+'T12:00').toLocaleDateString('es-ES',{day:'numeric',month:'short'})}
                    </div>
                  </div>
                  <button style={{ position:'absolute', top:8, right:8, background:'rgba(0,0,0,.5)', border:'none', color:'#fff', borderRadius:20, width:28, height:28, cursor:'pointer', fontSize:14 }}
                    onClick={() => deletePhoto(p.id)}>×</button>
                </div>
              ))}
            </div>
          )}
        </>
      )}

      {tab === 'stats' && (
        <div className="card">
          <div className="card-title">Resumen general</div>
          {[
            ['Pesajes registrados', state.weights.length],
            ['Días con comida', [...new Set(state.meals.map(m=>m.date))].length],
            ['Total entrenos', state.workouts.length],
            ['Kcal quemadas (total)', state.workouts.reduce((a,w)=>a+w.kcal,0)],
            ['Alimentos en biblioteca', state.foods.length],
            ['Velocidad de pérdida', change!==null?`${((last.kg-first.kg)/days*7).toFixed(2)} kg/sem`:'—'],
          ].map(([l,v]) => (
            <div key={l} className="list-row">
              <div style={{ flex:1, fontSize:15 }}>{l}</div>
              <div style={{ fontWeight:700, fontSize:18, color:'#FF6B35' }}>{v}</div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

Object.assign(window, { ScreenProgress });
