// StarThink — Health & Fitness Tracker
// Combines: Narcolepsy Tracker, Fitness Planner (both), 30-Day Push-Up Challenge,
// Body Measurement Tracker, Fueling Journal, 42 Easy Tracker

function HealthTracker() {
  const today = new Date().toISOString().split('T')[0];
  const [tab, setTab] = React.useState('daily');
  const tabs = [{ id:'daily', label:'Daily Log' }, { id:'weekly', label:'Weekly Fitness' },
    { id:'sleep', label:'Sleep & Energy' }, { id:'body', label:'Body Tracker' }, { id:'challenge', label:'30-Day Challenge' }];

  const useHealth = (name, def = {}) => {
    const key = `health_${name}_${today}`;
    const [d, setD] = React.useState(() => ST.get(key, def));
    const upd = (f, v) => { const n = {...d,[f]:v}; setD(n); ST.set(key, n); };
    return [d, upd];
  };

  const [dl, dlUpd] = useHealth('daily', { wakeUp:'', sleepQ:'', mood:'', todayGoal:'', meals:{breakfast:'',lunch:'',snacks:'',dinner:''}, exercise:[], water:0, calories:{in:'',out:''}, sleep:'', notes:'' });
  const [wk, wkUpd] = useHealth('weekly', { days:{} });
  const [sl, slUpd] = useHealth('sleep', { week:'', days:{} });

  const bodyKey = 'health_body';
  const [body, setBody] = React.useState(() => ST.get(bodyKey, { startDate:'', endDate:'', measurements:[], weekly:[] }));
  const updBody = (f, v) => { const n = {...body,[f]:v}; setBody(n); ST.set(bodyKey, n); };

  const challengeKey = 'health_challenge';
  const [challenge, setChallenge] = React.useState(() => ST.get(challengeKey, { startDate:'', days:{} }));
  const updChallenge = (f, v) => { const n = {...challenge,[f]:v}; setChallenge(n); ST.set(challengeKey, n); };

  const weekDays = ['Mon','Tue','Wed','Thu','Fri','Sat','Sun'];
  const measurements = ['Neck','Chest','Waist','Hips','Arm (L)','Arm (R)','Thigh (L)','Thigh (R)','Weight'];

  const TA = ({ value, onChange, placeholder, rows=3 }) => (
    <textarea value={value||''} onChange={e=>onChange(e.target.value)} placeholder={placeholder}
      style={{ width:'100%',minHeight:rows*22+'px',border:'1px solid #e8e8e8',borderRadius:'3px',padding:'6px',fontSize:'12px',fontFamily:'inherit',resize:'none',outline:'none',boxSizing:'border-box',color:'#333' }} />
  );

  return (
    <div className="planner-page">
      <div style={{ borderBottom:'2px solid #111', marginBottom:'16px', paddingBottom:'10px' }}>
        <div style={{ fontSize:'22px', fontWeight:'800', letterSpacing:'-0.5px' }}>Health & Fitness</div>
        <div style={{ fontSize:'11px', color:'#888', letterSpacing:'1px', textTransform:'uppercase', marginTop:'2px' }}>StarThink · {today}</div>
      </div>

      <div style={{ display:'flex', gap:'2px', marginBottom:'20px', borderBottom:'2px solid #111' }}>
        {tabs.map(t => (
          <button key={t.id} onClick={() => setTab(t.id)}
            style={{ padding:'6px 14px', fontSize:'12px', fontWeight:tab===t.id?'700':'400', border:'none', cursor:'pointer',
              background:tab===t.id?'#111':'transparent', color:tab===t.id?'#fff':'#666', fontFamily:'inherit' }}>
            {t.label}
          </button>
        ))}
      </div>

      {tab === 'daily' && (
        <div>
          {/* Pre-workout check-in */}
          <div style={{ background:'#f8f8f8', border:'1px solid #e8e8e8', borderRadius:'4px', padding:'12px 16px', marginBottom:'20px' }}>
            <div style={{ fontSize:'11px', fontWeight:'700', letterSpacing:'1px', color:'#888', marginBottom:'10px' }}>PRE-BREAKFAST CHECK-IN</div>
            <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr 1fr 1fr', gap:'12px' }}>
              {[['wakeUp','Wake-Up Time'],['weight','Body Weight'],['sleep','Hours Slept'],['sleepQ','Sleep Quality']].map(([k,label]) => (
                <div key={k}>
                  <div style={{ fontSize:'10px', color:'#888', marginBottom:'3px' }}>{label}</div>
                  <input value={dl[k]||''} onChange={e=>dlUpd(k,e.target.value)}
                    style={{ width:'100%',border:'1px solid #e0e0e0',borderRadius:'3px',padding:'5px 8px',fontSize:'12px',fontFamily:'inherit',outline:'none',boxSizing:'border-box' }} />
                </div>
              ))}
            </div>
            <div style={{ marginTop:'10px' }}>
              <div style={{ fontSize:'10px', color:'#888', marginBottom:'4px' }}>MOOD / ENERGY</div>
              <STMood value={dl.mood} onChange={v => dlUpd('mood', v)} />
            </div>
          </div>

          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:'20px' }}>
            {/* Meals */}
            <div>
              <STSection title="Meal & Nutrition Log">
                {['Breakfast','Lunch','Snacks','Dinner'].map(meal => (
                  <div key={meal} style={{ marginBottom:'10px' }}>
                    <div style={{ fontSize:'10px', fontWeight:'700', color:'#888', letterSpacing:'1px', marginBottom:'3px' }}>{meal.toUpperCase()}</div>
                    <TA value={dl.meals[meal.toLowerCase()]} onChange={v => dlUpd('meals',{...dl.meals,[meal.toLowerCase()]:v})} placeholder="Foods & portions..." rows={2} />
                  </div>
                ))}
              </STSection>
              <STSection title="Today's Goal">
                <TA value={dl.todayGoal} onChange={v => dlUpd('todayGoal',v)} placeholder="What's your focus today?" rows={2} />
              </STSection>
            </div>

            {/* Exercise */}
            <div>
              <STSection title="Exercise / Movement">
                {[0,1,2,3,4].map(i => {
                  const ex = (dl.exercise||[])[i] || { name:'', duration:'', intensity:'' };
                  return (
                    <div key={i} style={{ marginBottom:'8px', padding:'8px', background:'#fafafa', borderRadius:'3px', border:'1px solid #f0f0f0' }}>
                      <input value={ex.name} onChange={e => { const arr=[...(dl.exercise||[])]; if(!arr[i]) arr[i]={name:'',duration:'',intensity:''}; arr[i]={...arr[i],name:e.target.value}; dlUpd('exercise',arr); }}
                        placeholder={`Exercise ${i+1}...`} style={{ width:'100%',border:'none',borderBottom:'1px solid #e8e8e8',outline:'none',fontSize:'13px',color:'#111',background:'transparent',fontFamily:'inherit',marginBottom:'4px',padding:'2px 0',boxSizing:'border-box' }} />
                      <div style={{ display:'flex', gap:'8px' }}>
                        <input value={ex.duration} onChange={e => { const arr=[...(dl.exercise||[])]; if(!arr[i]) arr[i]={name:'',duration:'',intensity:''}; arr[i]={...arr[i],duration:e.target.value}; dlUpd('exercise',arr); }}
                          placeholder="Duration" style={{ flex:1,border:'none',borderBottom:'1px solid #e8e8e8',outline:'none',fontSize:'11px',color:'#666',background:'transparent',fontFamily:'inherit',padding:'2px 0' }} />
                        <select value={ex.intensity} onChange={e => { const arr=[...(dl.exercise||[])]; if(!arr[i]) arr[i]={name:'',duration:'',intensity:''}; arr[i]={...arr[i],intensity:e.target.value}; dlUpd('exercise',arr); }}
                          style={{ border:'1px solid #e0e0e0',borderRadius:'2px',fontSize:'11px',fontFamily:'inherit',color:'#666',background:'transparent',padding:'1px 4px' }}>
                          <option value="">Intensity</option>
                          <option>Low</option><option>Moderate</option><option>High</option>
                        </select>
                      </div>
                    </div>
                  );
                })}
              </STSection>
            </div>

            {/* Tracking */}
            <div>
              <STSection title="Water Intake">
                <STWater value={dl.water} onChange={v => dlUpd('water',v)} />
                <div style={{ fontSize:'11px', color:'#aaa', marginTop:'4px' }}>{dl.water}/8 glasses</div>
              </STSection>
              <STSection title="Calories">
                <div style={{ display:'flex', gap:'12px' }}>
                  {['in','out'].map(k => (
                    <div key={k} style={{ flex:1 }}>
                      <div style={{ fontSize:'10px', color:'#888', marginBottom:'4px' }}>CALORIES {k.toUpperCase()}</div>
                      <input value={dl.calories[k]||''} onChange={e=>dlUpd('calories',{...dl.calories,[k]:e.target.value})}
                        placeholder="0 kcal" style={{ width:'100%',border:'1px solid #e0e0e0',borderRadius:'3px',padding:'5px',fontSize:'12px',fontFamily:'inherit',outline:'none',boxSizing:'border-box' }} />
                    </div>
                  ))}
                </div>
              </STSection>
              <STSection title="Supplements & Medications">
                <STLineList items={dl.supplements||[]} count={4} onChange={v=>dlUpd('supplements',v)} placeholder="Name, dosage, time..." />
              </STSection>
              <STSection title="Mood & Energy Reflections">
                <div style={{ marginBottom:'6px' }}>
                  {['Best Energy Time','Low Energy Time','Overall Mood'].map(label => (
                    <div key={label} style={{ display:'flex',alignItems:'center',gap:'8px',marginBottom:'5px' }}>
                      <span style={{ fontSize:'11px',color:'#888',width:'110px',flexShrink:0 }}>{label}:</span>
                      <input value={dl[label.replace(/ /g,'')]||''} onChange={e=>dlUpd(label.replace(/ /g,''),e.target.value)}
                        style={{ flex:1,border:'none',borderBottom:'1px solid #e8e8e8',outline:'none',fontSize:'12px',color:'#333',background:'transparent',fontFamily:'inherit',padding:'2px 0' }} />
                    </div>
                  ))}
                </div>
              </STSection>
              <STSection title="What I'll Adjust Tomorrow">
                <TA value={dl.adjust} onChange={v=>dlUpd('adjust',v)} placeholder="One tweak for tomorrow..." rows={2} />
              </STSection>
              <STSection title="Notes">
                <TA value={dl.notes} onChange={v=>dlUpd('notes',v)} placeholder="Anything else..." rows={3} />
              </STSection>
            </div>
          </div>
        </div>
      )}

      {tab === 'weekly' && (
        <div>
          <div style={{ marginBottom:'16px', display:'flex', alignItems:'center', gap:'12px' }}>
            <span style={{ fontSize:'13px', color:'#888' }}>Week of:</span>
            <input type="date" value={wk.weekOf||''} onChange={e=>wkUpd('weekOf',e.target.value)}
              style={{ border:'1px solid #ccc',borderRadius:'3px',padding:'4px 8px',fontSize:'13px',fontFamily:'inherit' }} />
          </div>
          <div style={{ display:'grid', gridTemplateColumns:'repeat(7,1fr)', gap:'8px', marginBottom:'20px' }}>
            {weekDays.map(day => (
              <div key={day}>
                <div style={{ background:'#111',color:'#fff',padding:'6px',fontSize:'11px',fontWeight:'700',textAlign:'center',letterSpacing:'1px' }}>{day}</div>
                <div style={{ border:'1px solid #e8e8e8',borderTop:'none',padding:'8px',minHeight:'140px' }}>
                  <TA value={(wk.days||{})[day]||''} onChange={v=>wkUpd('days',{...wk.days,[day]:v})} placeholder="Workout..." rows={5} />
                </div>
              </div>
            ))}
          </div>
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:'20px' }}>
            <STSection title="Water Intake Goal">
              <STLineList items={wk.waterGoal||[]} count={3} onChange={v=>wkUpd('waterGoal',v)} placeholder="..." />
            </STSection>
            <STSection title="Long Term Goals">
              <TA value={wk.longGoals} onChange={v=>wkUpd('longGoals',v)} placeholder="Your fitness goals..." rows={4} />
            </STSection>
            <STSection title="Achievements">
              <TA value={wk.achievements} onChange={v=>wkUpd('achievements',v)} placeholder="What you accomplished..." rows={4} />
            </STSection>
          </div>
        </div>
      )}

      {tab === 'sleep' && (
        <div>
          <div style={{ marginBottom:'16px' }}>
            <div style={{ fontSize:'13px', color:'#888', marginBottom:'8px' }}>Week of: <input type="date" value={sl.week||''} onChange={e=>slUpd('week',e.target.value)} style={{ border:'1px solid #ccc',borderRadius:'3px',padding:'3px 8px',fontSize:'13px',fontFamily:'inherit' }} /></div>
          </div>
          <table style={{ width:'100%', borderCollapse:'collapse', marginBottom:'20px' }}>
            <thead>
              <tr style={{ background:'#111', color:'#fff' }}>
                {['DAY','SLEEP QUALITY','HRS SLEPT','ENERGY LEVEL','NOTES'].map(h => (
                  <th key={h} style={{ padding:'8px 12px',fontSize:'11px',letterSpacing:'1px',fontWeight:'700',textAlign:'left' }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {weekDays.map((day, i) => {
                const d = (sl.days||{})[day] || { quality:'', hours:'', energy:'', notes:'' };
                return (
                  <tr key={day} style={{ background:i%2===0?'#fafafa':'#fff', borderBottom:'1px solid #eee' }}>
                    <td style={{ padding:'8px 12px',fontWeight:'700',fontSize:'13px' }}>{day}</td>
                    <td style={{ padding:'8px 12px' }}>
                      <div style={{ display:'flex', gap:'4px' }}>
                        {['😴','😪','😐','🙂','😄'].map((e,j) => (
                          <span key={j} onClick={() => { const days={...sl.days}; days[day]={...d,quality:e}; slUpd('days',days); }}
                            style={{ fontSize:'18px',cursor:'pointer',opacity:d.quality===e?1:0.25 }}>{e}</span>
                        ))}
                      </div>
                    </td>
                    <td style={{ padding:'8px 12px' }}>
                      <input value={d.hours} onChange={e=>{ const days={...sl.days}; days[day]={...d,hours:e.target.value}; slUpd('days',days); }}
                        placeholder="hrs" style={{ width:'50px',border:'1px solid #e0e0e0',borderRadius:'3px',padding:'4px',fontSize:'12px',fontFamily:'inherit',outline:'none',textAlign:'center' }} />
                    </td>
                    <td style={{ padding:'8px 12px' }}>
                      <div style={{ display:'flex', gap:'3px' }}>
                        {[1,2,3,4,5].map(n => (
                          <div key={n} onClick={() => { const days={...sl.days}; days[day]={...d,energy:n}; slUpd('days',days); }}
                            style={{ width:'20px',height:'20px',borderRadius:'50%',border:'1.5px solid',cursor:'pointer',
                              borderColor:d.energy>=n?'#111':'#ddd',background:d.energy>=n?'#111':'transparent' }} />
                        ))}
                      </div>
                    </td>
                    <td style={{ padding:'8px 12px' }}>
                      <input value={d.notes} onChange={e=>{ const days={...sl.days}; days[day]={...d,notes:e.target.value}; slUpd('days',days); }}
                        style={{ width:'100%',border:'none',borderBottom:'1px solid #e8e8e8',outline:'none',fontSize:'12px',color:'#333',background:'transparent',fontFamily:'inherit',padding:'2px 0' }} />
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
          <STSection title="Notes">
            <TA value={sl.notes} onChange={v=>slUpd('notes',v)} placeholder="General sleep notes, patterns, observations..." rows={3} />
          </STSection>
        </div>
      )}

      {tab === 'body' && (
        <div>
          <div style={{ display:'flex', gap:'16px', marginBottom:'20px' }}>
            {[['startDate','Start Date','date'],['endDate','End Date','date']].map(([k,label,type]) => (
              <div key={k}>
                <div style={{ fontSize:'11px',color:'#888',marginBottom:'4px' }}>{label.toUpperCase()}</div>
                <input type={type} value={body[k]||''} onChange={e=>updBody(k,e.target.value)}
                  style={{ border:'1px solid #ccc',borderRadius:'3px',padding:'5px 8px',fontSize:'13px',fontFamily:'inherit',outline:'none' }} />
              </div>
            ))}
          </div>

          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:'24px' }}>
            <div>
              <STSection title="Before & After Measurements">
                <table style={{ width:'100%', borderCollapse:'collapse' }}>
                  <thead>
                    <tr>
                      {['MEASUREMENT','BEFORE','AFTER'].map(h => <th key={h} style={{ padding:'6px 8px',fontSize:'11px',letterSpacing:'1px',fontWeight:'700',borderBottom:'2px solid #111',textAlign:'left' }}>{h}</th>)}
                    </tr>
                  </thead>
                  <tbody>
                    {measurements.map((m, i) => {
                      const row = (body.measurements||[])[i] || { before:'', after:'' };
                      return (
                        <tr key={m} style={{ background:i%2===0?'#fafafa':'#fff' }}>
                          <td style={{ padding:'6px 8px',fontSize:'13px',fontWeight:'500' }}>{m}</td>
                          {['before','after'].map(k => (
                            <td key={k} style={{ padding:'6px 8px' }}>
                              <input value={row[k]||''} onChange={e=>{ const ms=[...(body.measurements||[])]; if(!ms[i]) ms[i]={before:'',after:''}; ms[i]={...ms[i],[k]:e.target.value}; updBody('measurements',ms); }}
                                style={{ width:'80px',border:'1px solid #e0e0e0',borderRadius:'3px',padding:'4px',fontSize:'12px',fontFamily:'inherit',outline:'none',textAlign:'center' }} />
                            </td>
                          ))}
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </STSection>
            </div>
            <div>
              <STSection title="Weekly Progress (4 Weeks)">
                <table style={{ width:'100%', borderCollapse:'collapse' }}>
                  <thead>
                    <tr>
                      {['MEASUREMENT','WK 1','WK 2','WK 3','WK 4'].map(h => <th key={h} style={{ padding:'5px 6px',fontSize:'10px',letterSpacing:'1px',fontWeight:'700',borderBottom:'2px solid #111',textAlign:'left' }}>{h}</th>)}
                    </tr>
                  </thead>
                  <tbody>
                    {['Weight','Waist','Hips'].map((m, i) => (
                      <tr key={m} style={{ background:i%2===0?'#fafafa':'#fff' }}>
                        <td style={{ padding:'5px 6px',fontSize:'12px',fontWeight:'500' }}>{m}</td>
                        {[0,1,2,3].map(w => {
                          const val = ((body.weekly||[])[i]||[])[w]||'';
                          return (
                            <td key={w} style={{ padding:'5px 6px' }}>
                              <input value={val} onChange={e=>{ const wk=[...(body.weekly||[])]; if(!wk[i]) wk[i]=['','','','']; wk[i]=[...wk[i]]; wk[i][w]=e.target.value; updBody('weekly',wk); }}
                                style={{ width:'50px',border:'1px solid #e0e0e0',borderRadius:'3px',padding:'3px',fontSize:'11px',fontFamily:'inherit',outline:'none',textAlign:'center' }} />
                            </td>
                          );
                        })}
                      </tr>
                    ))}
                  </tbody>
                </table>
              </STSection>
              <STSection title="Notes">
                <TA value={body.notes} onChange={v=>updBody('notes',v)} placeholder="Progress notes, observations..." rows={4} />
              </STSection>
            </div>
          </div>
        </div>
      )}

      {tab === 'challenge' && (
        <div>
          <div style={{ marginBottom:'16px' }}>
            <div style={{ fontSize:'16px', fontWeight:'700', marginBottom:'4px' }}>30-Day Fitness Challenge</div>
            <div style={{ fontSize:'13px', color:'#888', marginBottom:'12px' }}>Track your daily habits for 30 days. Click each day to mark complete.</div>
            <div style={{ display:'flex', gap:'16px', marginBottom:'16px' }}>
              {[['startDate','Start Date'],['endDate','End Date']].map(([k,l]) => (
                <div key={k} style={{ display:'flex', alignItems:'center', gap:'8px' }}>
                  <span style={{ fontSize:'12px', color:'#888' }}>{l}:</span>
                  <input type="date" value={challenge[k]||''} onChange={e=>updChallenge(k,e.target.value)}
                    style={{ border:'1px solid #ccc',borderRadius:'3px',padding:'4px 8px',fontSize:'12px',fontFamily:'inherit',outline:'none' }} />
                </div>
              ))}
            </div>
          </div>
          {/* Habits to track */}
          <div style={{ marginBottom:'16px' }}>
            <div style={{ fontSize:'11px', color:'#888', fontWeight:'700', letterSpacing:'1px', marginBottom:'8px' }}>DAILY HABITS TO TRACK</div>
            <div style={{ display:'flex', gap:'8px', flexWrap:'wrap' }}>
              {(challenge.habits||['Workout','Drink 1L Water','Eat Clean','Journal','Stretch']).map((h, i) => (
                <input key={i} value={h} onChange={e=>{ const hs=[...(challenge.habits||['Workout','Drink 1L Water','Eat Clean','Journal','Stretch'])]; hs[i]=e.target.value; updChallenge('habits',hs); }}
                  style={{ border:'1px solid #ccc',borderRadius:'20px',padding:'5px 14px',fontSize:'12px',fontFamily:'inherit',outline:'none',color:'#333' }} />
              ))}
            </div>
          </div>
          {/* 30-day grid */}
          <div style={{ display:'grid', gridTemplateColumns:'repeat(5, 1fr)', gap:'8px' }}>
            {Array.from({ length: 30 }, (_, i) => {
              const day = i + 1;
              const done = (challenge.days||{})[day];
              return (
                <div key={day} onClick={() => updChallenge('days',{...challenge.days,[day]:!done})}
                  style={{ border:'2px solid', borderRadius:'6px', padding:'12px 8px', cursor:'pointer', textAlign:'center',
                    borderColor:done?'#111':'#e0e0e0', background:done?'#111':'#fafafa', transition:'all 0.15s' }}>
                  <div style={{ fontSize:'11px', fontWeight:'700', letterSpacing:'1px', color:done?'#aaa':'#888', marginBottom:'4px' }}>DAY</div>
                  <div style={{ fontSize:'22px', fontWeight:'800', color:done?'#fff':'#333' }}>{day}</div>
                  {done && <div style={{ fontSize:'16px', marginTop:'4px' }}>✓</div>}
                </div>
              );
            })}
          </div>
          <div style={{ marginTop:'16px', fontSize:'13px', color:'#888' }}>
            Completed: <strong style={{ color:'#111' }}>{Object.values(challenge.days||{}).filter(Boolean).length}/30</strong> days
          </div>
        </div>
      )}
    </div>
  );
}

window.HealthTracker = HealthTracker;
