// StarThink — Daily Master Planner (v4)
// Dynamic meals, 2-tier mood, water stepper, for-tomorrow + button,
// dotted-circle schedule mood, adjustable gratitude, reset, save/load .splan

function useSpeech(onResult) {
  const [listening, setListening] = React.useState(false);
  const recRef = React.useRef(null);
  const start = () => {
    const SR = window.SpeechRecognition || window.webkitSpeechRecognition;
    if (!SR) return alert('Speech recognition not supported. Try Chrome.');
    const rec = new SR();
    rec.continuous = true; rec.interimResults = false; rec.lang = 'en-US';
    rec.onresult = e => { const t = Array.from(e.results).map(r => r[0].transcript).join(' '); onResult(t); };
    rec.onend = () => setListening(false);
    rec.start(); recRef.current = rec; setListening(true);
  };
  const stop = () => { recRef.current?.stop(); setListening(false); };
  return { listening, start, stop, toggle: () => listening ? stop() : start() };
}

function MicButton({ onResult, style = {} }) {
  const { listening, toggle } = useSpeech(onResult);
  return (
    <button onClick={toggle} title={listening ? 'Stop' : 'Speak'}
      style={{ background: listening ? '#c00' : '#ebebeb', color: listening ? '#fff' : '#777', border: 'none', borderRadius: '50%',
        width: '26px', height: '26px', cursor: 'pointer', fontSize: '12px', display: 'inline-flex', alignItems: 'center',
        justifyContent: 'center', flexShrink: 0, transition: 'all 0.15s', ...style }}>
      {listening ? '⏹' : '🎙'}
    </button>
  );
}

function SpeechTextarea({ value, onChange, placeholder, rows = 4, style = {} }) {
  return (
    <div style={{ position: 'relative' }}>
      <textarea value={value || ''} onChange={e => onChange(e.target.value)} placeholder={placeholder} rows={rows}
        style={{ width: '100%', border: '1px solid #e8e8e8', borderRadius: '4px', padding: '8px 36px 8px 8px',
          fontSize: '13px', fontFamily: 'inherit', resize: 'vertical', outline: 'none', boxSizing: 'border-box',
          color: '#333', lineHeight: '1.7', ...style }} />
      <div style={{ position: 'absolute', top: '8px', right: '8px' }}>
        <MicButton onResult={t => onChange((value ? value + ' ' : '') + t)} />
      </div>
    </div>
  );
}

function Divider({ title }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: '12px', marginBottom: '16px', marginTop: '4px' }}>
      <div style={{ flex: 1, height: '1px', background: '#e8e8e8' }} />
      <span style={{ fontSize: '10px', fontWeight: '800', letterSpacing: '2.5px', color: '#bbb', textTransform: 'uppercase', whiteSpace: 'nowrap' }}>{title}</span>
      <div style={{ flex: 1, height: '1px', background: '#e8e8e8' }} />
    </div>
  );
}

const MEAL_OPTIONS = [
  'Breakfast','Brunch','Lunch','Snack','Dinner','Supper','Pre-workout','Post-workout','Dessert','Other'
];

const EXERCISE_SUGGESTIONS = [
  'Push-ups','Pull-ups','Squats','Lunges','Plank','Burpees','Jumping Jacks','Mountain Climbers',
  'Deadlift','Bench Press','Overhead Press','Rows','Dips','Running','Walking','Cycling',
  'Swimming','Jump Rope','Yoga','Stretching','HIIT','Pilates','Kettlebell Swings','Box Jumps','Crunches','Leg Raises'
];

// 2-tier mood system
const MOOD_TIERS = {
  Great:   { emoji: '😄', secondaries: ['Excited 🤩','Motivated 💪','Inspired ✨','Joyful 🌟','Grateful 🙏'] },
  Good:    { emoji: '🙂', secondaries: ['Calm 😌','Focused 🎯','Content 😊','Hopeful 🌱','Relaxed 🧘'] },
  Okay:    { emoji: '😐', secondaries: ['Neutral 😶','Distracted 💭','Tired 😪','Bored 🥱','Uncertain 🤔'] },
  Low:     { emoji: '😔', secondaries: ['Sad 😢','Drained 😮‍💨','Lonely 💔','Disappointed 😞','Unmotivated 🌧️'] },
  Stressed:{ emoji: '😤', secondaries: ['Anxious 😰','Overwhelmed 🌊','Frustrated 😠','Pressured 😬','Restless 😣'] },
};

function DailyPlanner() {
  const today = new Date().toISOString().split('T')[0];
  const [date, setDate] = React.useState(ST.get('daily_date', today));
  const key = d => `daily_${d}`;

  const defaultData = () => ({
    affirmation: '', showAffirmation: true,
    scheduleHours: ['5 AM','6 AM','7 AM','8 AM','9 AM','10 AM','11 AM','12 PM',
      '1 PM','2 PM','3 PM','4 PM','5 PM','6 PM','7 PM','8 PM','9 PM','10 PM','11 PM','12 AM'],
    schedule: {}, scheduleMoods: {},
    priorityCount: 3, priorities: Array(8).fill(''),
    todos: [],
    waterTarget: 8, water: 0,
    calorieTarget: 2000, calorieBurnTarget: 500,
    meals: [
      { name: 'Breakfast', foods: '', calories: '', time: '' },
      { name: 'Lunch', foods: '', calories: '', time: '' },
      { name: 'Snack', foods: '', calories: '', time: '' },
      { name: 'Dinner', foods: '', calories: '', time: '' },
    ],
    exercise: [],
    moodPrimary: '', moodSecondary: '',
    brainDump: '',
    forTomorrow: [{ text: '', done: false }, { text: '', done: false }],
    gratitudeCount: 3, gratitude: Array(8).fill(''),
    reward: '', rating: 0, reflection: '', notes: ''
  });

  const sanitize = (d) => {
    if (!d) return defaultData();
    const def = defaultData();
    if (!Array.isArray(d.meals)) d.meals = def.meals;
    if (!Array.isArray(d.exercise)) d.exercise = def.exercise;
    if (!Array.isArray(d.todos)) d.todos = [];
    if (!Array.isArray(d.forTomorrow)) d.forTomorrow = def.forTomorrow;
    if (!Array.isArray(d.priorities)) d.priorities = def.priorities;
    if (!Array.isArray(d.gratitude)) d.gratitude = def.gratitude;
    if (!Array.isArray(d.scheduleHours)) d.scheduleHours = def.scheduleHours;
    if (!d.priorityCount || d.priorityCount < 1) d.priorityCount = 3;
    if (!d.gratitudeCount || d.gratitudeCount < 1) d.gratitudeCount = 3;
    if (!d.waterTarget) d.waterTarget = 8;
    return { ...def, ...d };
  };

  const [data, setData] = React.useState(() => sanitize(ST.get(key(date))));
  const [isMobile, setIsMobile] = React.useState(() => window.matchMedia('(max-width: 900px)').matches);
  React.useEffect(() => { setData(sanitize(ST.get(key(date)))); }, [date]);
  React.useEffect(() => {
    const onResize = () => setIsMobile(window.matchMedia('(max-width: 900px)').matches);
    window.addEventListener('resize', onResize);
    return () => window.removeEventListener('resize', onResize);
  }, []);

  const save = u => { setData(u); ST.set(key(date), u); };
  const upd = (f, v) => save({ ...data, [f]: v });

  React.useEffect(() => { if (data.meals) ST.set(`health_meals_${date}`, data.meals); }, [data.meals, date]);

  const saveForTomorrow = (items) => {
    save({ ...data, forTomorrow: items });
    const tomorrow = new Date(date + 'T12:00:00');
    tomorrow.setDate(tomorrow.getDate() + 1);
    const tKey = key(tomorrow.toISOString().split('T')[0]);
    const tData = sanitize(ST.get(tKey));
    const toAdd = items.filter(i => i?.text?.trim()).map(i => ({ text: i.text, done: false, fromYesterday: true }));
    const existing = (tData.todos || []).filter(t => !t?.fromYesterday);
    ST.set(tKey, { ...tData, todos: [...toAdd, ...existing] });
  };

  // Save as .splan file
  const saveSplan = () => {
    const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
    const a = document.createElement('a');
    a.href = URL.createObjectURL(blob);
    a.download = `starThink_${date}.splan`;
    a.click();
    URL.revokeObjectURL(a.href);
  };

  // Load from .splan file
  const loadSplan = (e) => {
    const file = e.target.files[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = ev => {
      try {
        const loaded = JSON.parse(ev.target.result);
        save(sanitize(loaded));
      } catch { alert('Invalid .splan file.'); }
    };
    reader.readAsText(file);
    e.target.value = '';
  };

  // Reset current day
  const resetDay = () => {
    if (!confirm(`Reset all data for ${date}? This cannot be undone.`)) return;
    save(defaultData());
  };

  const totalCal = data.meals.reduce((s, m) => s + (parseFloat(m?.calories) || 0), 0);
  const exerciseCal = data.exercise.filter(e => e?.done).reduce((s, e) => s + (parseFloat(e?.calories) || 0), 0);
  const excessEnergy = totalCal - exerciseCal;

  // Eating/fasting window calculation
  const mealTimes = data.meals.map(m => m?.time).filter(Boolean).map(t => {
    const [h, min] = t.split(':').map(Number);
    return h * 60 + (min || 0);
  }).sort((a, b) => a - b);
  const eatingWindowMins = mealTimes.length >= 2 ? mealTimes[mealTimes.length - 1] - mealTimes[0] : null;
  const fastingWindowMins = eatingWindowMins !== null ? 24 * 60 - eatingWindowMins : null;
  const fmtMins = (m) => `${Math.floor(m/60)}h ${m%60 > 0 ? (m%60)+'m' : ''}`.trim();
  const todoDone = data.todos.filter(t => t?.done).length;
  const todoTotal = data.todos.filter(t => t?.text).length;
  const waterPct = Math.min(100, Math.round((data.water / data.waterTarget) * 100));
  const calInPct = Math.min(100, Math.round((totalCal / data.calorieTarget) * 100));
  const calBurnPct = Math.min(100, Math.round((exerciseCal / data.calorieBurnTarget) * 100));

  const dayNames = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
  const d = new Date(date + 'T12:00:00');
  const allHours = ['12 AM','1 AM','2 AM','3 AM','4 AM','5 AM','6 AM','7 AM','8 AM','9 AM','10 AM','11 AM',
    '12 PM','1 PM','2 PM','3 PM','4 PM','5 PM','6 PM','7 PM','8 PM','9 PM','10 PM','11 PM'];
  const addHour = () => {
    const next = allHours.find(h => !data.scheduleHours.includes(h));
    if (next) upd('scheduleHours', [...data.scheduleHours, next].sort((a,b) => allHours.indexOf(a)-allHours.indexOf(b)));
  };
  const moveTask = (from, to) => {
    const todos = [...data.todos];
    const [item] = todos.splice(from, 1);
    todos.splice(to, 0, item);
    upd('todos', todos);
  };

  const pCount = data.priorityCount;
  const gCount = data.gratitudeCount;

  return (
    <div className="planner-page" style={{ maxWidth: isMobile ? '100%' : '800px', overflowX: 'hidden' }}>

      {/* ── HEADER ── */}
      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-start', marginBottom:'20px', gap:'10px', flexWrap:'wrap' }}>
        <div>
          <div style={{ fontSize:'28px', fontWeight:'800', letterSpacing:'-0.5px' }}>Daily Planner</div>
          <div style={{ fontSize:'11px', color:'#999', letterSpacing:'2px', textTransform:'uppercase', marginTop:'3px' }}>StarThink</div>
        </div>
        <div style={{ display:'flex', flexDirection:'column', alignItems:isMobile?'stretch':'flex-end', gap:'8px', width:isMobile?'100%':'auto' }}>
          <div style={{ display:'flex', gap:'8px', alignItems:'center', flexWrap:'wrap' }}>
            <input type="date" value={date} onChange={e => { setDate(e.target.value); ST.set('daily_date', e.target.value); }}
              style={{ border:'1px solid #e0e0e0', borderRadius:'4px', padding:'6px 10px', fontSize:'13px', fontFamily:'inherit', color:'#333', outline:'none' }} />
            {/* Reset + Save/Load */}
            <button onClick={resetDay} title="Reset today's data"
              style={{ padding:'6px 10px', fontSize:'11px', fontFamily:'inherit', border:'1px solid #e8e8e8', borderRadius:'4px', background:'none', color:'#bbb', cursor:'pointer' }}>
              ↺ Reset
            </button>
            <button onClick={saveSplan} title="Save as .splan file"
              style={{ padding:'6px 10px', fontSize:'11px', fontFamily:'inherit', border:'1px solid #e8e8e8', borderRadius:'4px', background:'none', color:'#bbb', cursor:'pointer' }}>
              ↓ Save
            </button>
            <label title="Load .splan file" style={{ padding:'6px 10px', fontSize:'11px', fontFamily:'inherit', border:'1px solid #e8e8e8', borderRadius:'4px', background:'none', color:'#bbb', cursor:'pointer' }}>
              ↑ Load
              <input type="file" accept=".splan,.json" onChange={loadSplan} style={{ display:'none' }} />
            </label>
          </div>
          <div style={{ display:'flex', gap:'4px', justifyContent:isMobile?'space-between':'flex-end' }}>
            {dayNames.map((day, i) => (
              <div key={day} style={{ width:'28px', height:'28px', borderRadius:'50%', display:'flex', alignItems:'center', justifyContent:'center',
                background: d.getDay()===i ? '#111' : 'transparent', color: d.getDay()===i ? '#fff' : '#ccc',
                border:'1.5px solid', borderColor: d.getDay()===i ? '#111' : '#e8e8e8', fontSize:'9px', fontWeight:'700' }}>
                {day[0]}
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Affirmation */}
      <div style={{ marginBottom:'24px', display:'flex', alignItems:'center', gap:'8px', flexWrap:'wrap' }}>
        {data.showAffirmation && (
          <div style={{ flex:1, background:'#fafafa', border:'1px solid #e8e8e8', borderRadius:'6px', padding:'10px 14px', display:'flex', alignItems:'center', gap:'10px' }}>
            <span style={{ fontSize:'14px', color:'#ccc' }}>✦</span>
            <input value={data.affirmation} onChange={e => upd('affirmation', e.target.value)}
              placeholder="Today's affirmation..."
              style={{ flex:1, border:'none', outline:'none', background:'transparent', fontSize:'14px', fontStyle:'italic', color:'#444', fontFamily:'inherit' }} />
            <MicButton onResult={t => upd('affirmation', t)} />
          </div>
        )}
        <button onClick={() => upd('showAffirmation', !data.showAffirmation)}
          style={{ fontSize:'11px', color:'#bbb', background:'none', border:'1px solid #eee', borderRadius:'4px', padding:'4px 8px', cursor:'pointer', fontFamily:'inherit', whiteSpace:'nowrap' }}>
          {data.showAffirmation ? 'Hide' : '✦ Affirmation'}
        </button>
      </div>

      {/* ── PLANNING ── */}
      <Divider title="Planning" />
      <div style={{ display:'grid', gridTemplateColumns:isMobile?'1fr':'1fr 1fr', gap:'24px', marginBottom:'28px' }}>
        {/* Priorities */}
        <div>
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:'10px' }}>
            <div style={{ fontSize:'11px', fontWeight:'800', letterSpacing:'1.5px', color:'#888' }}>TOP PRIORITIES</div>
            <div style={{ display:'flex', alignItems:'center', gap:'4px' }}>
              <button onClick={() => upd('priorityCount', Math.max(1, pCount-1))} style={{ width:'22px',height:'22px',border:'1px solid #e0e0e0',borderRadius:'3px',background:'none',cursor:'pointer',fontSize:'14px',display:'flex',alignItems:'center',justifyContent:'center',color:'#888' }}>−</button>
              <span style={{ fontSize:'11px', color:'#aaa', minWidth:'16px', textAlign:'center' }}>{pCount}</span>
              <button onClick={() => upd('priorityCount', Math.min(8, pCount+1))} style={{ width:'22px',height:'22px',border:'1px solid #e0e0e0',borderRadius:'3px',background:'none',cursor:'pointer',fontSize:'14px',display:'flex',alignItems:'center',justifyContent:'center',color:'#888' }}>+</button>
            </div>
          </div>
          {Array.from({length: pCount}, (_, i) => (
            <div key={i} style={{ display:'flex', alignItems:'center', gap:'8px', marginBottom:'7px' }}>
              <div style={{ width:'20px', height:'20px', borderRadius:'50%', background: i===0?'#111':i===1?'#555':'#aaa',
                color:'#fff', fontSize:'10px', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0, fontWeight:'800' }}>{i+1}</div>
              <input value={(data.priorities||[])[i]||''} onChange={e => { const p=[...data.priorities]; p[i]=e.target.value; upd('priorities',p); }}
                placeholder={`Priority ${i+1}`}
                style={{ flex:1, border:'none', borderBottom:'1.5px solid #e8e8e8', outline:'none', fontSize:'13px', color:'#111', background:'transparent', fontFamily:'inherit', padding:'3px 0' }} />
            </div>
          ))}
        </div>

        {/* To-Do */}
        <div>
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:'10px' }}>
            <div style={{ fontSize:'11px', fontWeight:'800', letterSpacing:'1.5px', color:'#888' }}>TO-DO LIST</div>
            <span style={{ fontSize:'11px', color: todoDone===todoTotal&&todoTotal>0?'#2a7a2a':'#bbb', fontWeight:'600' }}>{todoDone}/{todoTotal}</span>
          </div>
          {data.todos.map((item, i) => {
            const it = (item && typeof item==='object') ? item : {text:'',done:false};
            return (
              <div key={i} style={{ display:'flex', alignItems:'center', gap:'6px', padding:'3px 0', borderBottom:'1px solid #f8f8f8' }}>
                <div onClick={() => { const t=[...data.todos]; t[i]={...it,done:!it.done}; upd('todos',t); }}
                  style={{ width:'15px',height:'15px',border:'2px solid',flexShrink:0,cursor:'pointer',borderRadius:'3px',
                    borderColor:it.done?'#111':'#ccc',background:it.done?'#111':'transparent',display:'flex',alignItems:'center',justifyContent:'center' }}>
                  {it.done&&<span style={{color:'#fff',fontSize:'9px'}}>✓</span>}
                </div>
                <input value={it.text||''} onChange={e => { const t=[...data.todos]; t[i]={...it,text:e.target.value}; upd('todos',t); }}
                  placeholder="Task..." style={{ flex:1,border:'none',outline:'none',fontSize:'13px',
                    color:it.done?'#bbb':'#111',textDecoration:it.done?'line-through':'none',
                    background:'transparent',fontFamily:'inherit',padding:'2px 0' }} />
                {it.fromYesterday && <span title="Carried from yesterday" style={{fontSize:'11px',color:'#bbb',flexShrink:0}}>↩</span>}
                <div style={{display:'flex',gap:'2px',flexShrink:0}}>
                  {i>0&&<button onClick={()=>moveTask(i,i-1)} style={{background:'none',border:'none',color:'#ddd',cursor:'pointer',fontSize:'12px',padding:'0 1px'}}>↑</button>}
                  {i<data.todos.length-1&&<button onClick={()=>moveTask(i,i+1)} style={{background:'none',border:'none',color:'#ddd',cursor:'pointer',fontSize:'12px',padding:'0 1px'}}>↓</button>}
                  <button onClick={()=>upd('todos',data.todos.filter((_,j)=>j!==i))} style={{background:'none',border:'none',color:'#e0e0e0',cursor:'pointer',fontSize:'14px',padding:'0 1px'}}>×</button>
                </div>
              </div>
            );
          })}
          <button onClick={() => upd('todos', [...data.todos, {text:'',done:false}])}
            style={{ marginTop:'8px',background:'none',border:'1px dashed #e0e0e0',borderRadius:'4px',padding:'4px 12px',fontSize:'12px',color:'#bbb',cursor:'pointer',fontFamily:'inherit',width:'100%' }}>
            + Add task
          </button>
        </div>
      </div>

      {/* ── SCHEDULE ── */}
      <Divider title="Schedule" />
      <div style={{ marginBottom:'28px' }}>
        <div style={{ columnCount:isMobile ? 1 : 2, columnGap:'24px', columnFill:'auto', height:isMobile ? 'auto' : `${Math.ceil(data.scheduleHours.length/2)*36}px` }}>
          {data.scheduleHours.map(h => {
            const moodVal = (data.scheduleMoods||{})[h];
            return (
              <div key={h} style={{ display:'flex', alignItems:'center', borderBottom:'1px solid #f5f5f5', minHeight:'34px', gap:'6px', breakInside:'avoid' }}>
                <span style={{ fontSize:'10px', color:'#bbb', width:'42px', flexShrink:0, fontWeight:'600' }}>{h}</span>
                <input value={data.schedule[h]||''} onChange={e => upd('schedule',{...data.schedule,[h]:e.target.value})}
                  style={{ flex:1, border:'none', outline:'none', fontSize:'12px', color:'#333', background:'transparent', fontFamily:'inherit', padding:'3px 0' }} />
                {/* Dotted circle mood indicator */}
                <div style={{ position:'relative', flexShrink:0 }}>
                  <select value={moodVal||''} onChange={e => upd('scheduleMoods',{...(data.scheduleMoods||{}),[h]:e.target.value})}
                    title="Log mood at this time"
                    style={{ position:'absolute', top:0, left:0, width:'100%', height:'100%', opacity:0, cursor:'pointer', fontSize:'13px' }}>
                    <option value="">No mood</option>
                    {Object.entries(MOOD_TIERS).map(([k,v]) => <option key={k} value={v.emoji}>{v.emoji} {k}</option>)}
                  </select>
                  <div style={{ width:'22px', height:'22px', borderRadius:'50%', border:`2px ${moodVal?'solid':'dashed'}`, borderColor: moodVal?'#888':'#ccc',
                    display:'flex', alignItems:'center', justifyContent:'center', fontSize:'13px', background: moodVal?'#f5f5f5':'transparent', pointerEvents:'none' }}>
                    {moodVal || <span style={{fontSize:'8px',color:'#ddd'}}>●</span>}
                  </div>
                </div>
                <button onClick={() => upd('scheduleHours', data.scheduleHours.filter(x=>x!==h))} style={{background:'none',border:'none',color:'#e8e8e8',cursor:'pointer',fontSize:'13px',padding:'0 2px',flexShrink:0}}>×</button>
              </div>
            );
          })}
        </div>
        <button onClick={addHour} style={{marginTop:'10px',background:'none',border:'1px dashed #e0e0e0',borderRadius:'4px',padding:'5px 14px',fontSize:'12px',color:'#bbb',cursor:'pointer',fontFamily:'inherit'}}>
          + Add hour
        </button>
      </div>

      {/* ── MEALS ── */}
      <Divider title="Meals & Nutrition" />
      <div style={{ marginBottom:'28px' }}>
        <div style={{ overflowX:'auto' }}>
        <table style={{ width:'100%', borderCollapse:'collapse', marginBottom:'10px', minWidth:isMobile?'620px':'auto' }}>
          <thead>
            <tr>
              <th style={{padding:'6px 8px',fontSize:'10px',letterSpacing:'1.5px',fontWeight:'800',color:'#888',borderBottom:'2px solid #111',textAlign:'left',width:'120px'}}>MEAL</th>
              <th style={{padding:'6px 8px',fontSize:'10px',letterSpacing:'1.5px',fontWeight:'800',color:'#888',borderBottom:'2px solid #111',textAlign:'left',width:'70px'}}>TIME</th>
              <th style={{padding:'6px 8px',fontSize:'10px',letterSpacing:'1.5px',fontWeight:'800',color:'#888',borderBottom:'2px solid #111',textAlign:'left'}}>FOODS & PORTIONS</th>
              <th style={{padding:'6px 8px',fontSize:'10px',letterSpacing:'1.5px',fontWeight:'800',color:'#888',borderBottom:'2px solid #111',textAlign:'left',width:'90px'}}>KCAL</th>
              <th style={{width:'24px',borderBottom:'2px solid #111'}}></th>
            </tr>
          </thead>
          <tbody>
            {data.meals.map((meal, i) => (
              <tr key={i} style={{borderBottom:'1px solid #f5f5f5'}}>
                <td style={{padding:'5px 8px'}}>
                  <select value={meal?.name||'Breakfast'} onChange={e=>{const m=[...data.meals];m[i]={...m[i],name:e.target.value};upd('meals',m);}}
                    style={{width:'100%',border:'none',outline:'none',fontSize:'13px',fontWeight:'600',color:'#555',background:'transparent',fontFamily:'inherit',cursor:'pointer'}}>
                    {MEAL_OPTIONS.map(o=><option key={o} value={o}>{o}</option>)}
                  </select>
                </td>
                <td style={{padding:'5px 8px'}}>
                  <input type="time" value={meal?.time||''} onChange={e=>{const m=[...data.meals];m[i]={...m[i],time:e.target.value};upd('meals',m);}}
                    style={{border:'none',outline:'none',fontSize:'12px',color:'#888',background:'transparent',fontFamily:'inherit',width:'70px'}} />
                </td>
                <td style={{padding:'4px 8px'}}>
                  <input value={meal?.foods||''} onChange={e=>{const m=[...data.meals];m[i]={...m[i],foods:e.target.value};upd('meals',m);}}
                    placeholder="What did you eat?" style={{width:'100%',border:'none',outline:'none',fontSize:'13px',color:'#333',background:'transparent',fontFamily:'inherit'}} />
                </td>
                <td style={{padding:'4px 8px'}}>
                  <div style={{display:'flex',alignItems:'center',gap:'4px'}}>
                    <input value={meal?.calories||''} onChange={e=>{const m=[...data.meals];m[i]={...m[i],calories:e.target.value};upd('meals',m);}}
                      placeholder="0" style={{width:'50px',border:'1px solid #e8e8e8',borderRadius:'3px',padding:'3px 5px',fontSize:'12px',fontFamily:'inherit',outline:'none',textAlign:'right'}} />
                    <span style={{fontSize:'10px',color:'#bbb'}}>kcal</span>
                  </div>
                </td>
                <td style={{padding:'4px',textAlign:'center'}}>
                  <button onClick={()=>upd('meals',data.meals.filter((_,j)=>j!==i))} style={{background:'none',border:'none',color:'#e0e0e0',cursor:'pointer',fontSize:'15px'}}>×</button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
        </div>

        {/* Eating / fasting window */}
        {eatingWindowMins !== null && (
          <div style={{display:'flex',gap:'20px',padding:'10px 12px',background:'#f8f8f8',borderRadius:'6px',marginBottom:'12px',fontSize:'12px',flexWrap:'wrap'}}>
            <div>
              <span style={{color:'#bbb',letterSpacing:'1px',fontSize:'10px',fontWeight:'700'}}>EATING WINDOW  </span>
              <strong style={{color:'#111'}}>{fmtMins(eatingWindowMins)}</strong>
            </div>
            <div>
              <span style={{color:'#bbb',letterSpacing:'1px',fontSize:'10px',fontWeight:'700'}}>FASTING WINDOW  </span>
              <strong style={{color:'#555'}}>{fmtMins(fastingWindowMins)}</strong>
            </div>
            <div style={{color:'#bbb',fontSize:'11px',fontStyle:'italic',alignSelf:'center'}}>
              {mealTimes.length >= 2 ? `${data.meals.filter(m=>m?.time).sort((a,b)=>a.time.localeCompare(b.time))[0]?.name} → ${data.meals.filter(m=>m?.time).sort((a,b)=>b.time.localeCompare(a.time))[0]?.name}` : ''}
            </div>
          </div>
        )}

        <button onClick={()=>upd('meals',[...data.meals,{name:'Snack',foods:'',calories:'',time:''}])}
          style={{background:'none',border:'1px dashed #e0e0e0',borderRadius:'4px',padding:'5px 14px',fontSize:'12px',color:'#bbb',cursor:'pointer',fontFamily:'inherit',marginBottom:'12px'}}>
          + Add meal
        </button>

        {/* Calorie bars + excess energy */}
        <div style={{display:'grid',gridTemplateColumns:isMobile?'1fr':'1fr 1fr 1fr',gap:'12px'}}>
          {[
            ['Calories In', totalCal, data.calorieTarget, 'calorieTarget', calInPct, calInPct>110?'#c00':calInPct>90?'#888':'#111'],
            ['Cal Burned', exerciseCal, data.calorieBurnTarget, 'calorieBurnTarget', calBurnPct, calBurnPct>=100?'#2a7a2a':'#555'],
          ].map(([label, val, target, field, pct, barColor]) => (
            <div key={label}>
              <div style={{display:'flex',justifyContent:'space-between',fontSize:'10px',color:'#bbb',marginBottom:'4px'}}>
                <span>{label}</span>
                <span style={{fontWeight:'600',color:barColor}}>
                  {val} / <input value={target} onChange={e=>upd(field,parseInt(e.target.value)||target)}
                    style={{width:'40px',border:'none',borderBottom:'1px solid #e8e8e8',outline:'none',fontSize:'10px',color:'#888',background:'transparent',textAlign:'center',fontFamily:'inherit'}} /> kcal
                </span>
              </div>
              <div style={{height:'6px',background:'#f0f0f0',borderRadius:'3px',overflow:'hidden'}}>
                <div style={{height:'100%',width:`${pct}%`,background:barColor,borderRadius:'3px',transition:'width 0.3s'}} />
              </div>
            </div>
          ))}
          {/* Excess energy */}
          <div>
            <div style={{display:'flex',justifyContent:'space-between',fontSize:'10px',color:'#bbb',marginBottom:'4px'}}>
              <span>{excessEnergy > 0 ? 'Excess Energy' : 'Energy Deficit'}</span>
              <span style={{fontWeight:'800',color:excessEnergy>0?'#c44':'#2a7a2a'}}>{Math.abs(excessEnergy)} kcal</span>
            </div>
            <div style={{height:'6px',background:'#f0f0f0',borderRadius:'3px',overflow:'hidden'}}>
              <div style={{height:'100%',width:`${Math.min(100,Math.abs(excessEnergy)/50)}%`,background:excessEnergy>0?'#c44':'#2a7a2a',borderRadius:'3px',transition:'width 0.3s'}} />
            </div>
            <div style={{fontSize:'10px',color:excessEnergy>0?'#c44':'#2a7a2a',marginTop:'3px',fontWeight:'600'}}>
              {excessEnergy>0?'⚠ Gaining':'✓ Losing / Maintaining'}
            </div>
          </div>
        </div>
      </div>

      {/* ── EXERCISE ── */}
      <Divider title="Exercise & Movement" />
      <datalist id="exercise-suggestions">
        {EXERCISE_SUGGESTIONS.map(s=><option key={s} value={s}/>)}
      </datalist>
      <div style={{marginBottom:'28px'}}>
        <div style={{overflowX:'auto'}}>
        <div style={{display:'grid',gridTemplateColumns:'16px 2fr 60px 60px 80px 76px 24px',gap:'6px',padding:'4px 0',marginBottom:'4px', minWidth:isMobile?'560px':'auto'}}>
          {['','Exercise','Sets','Reps','Duration','Cal',''].map((h,i)=>(
            <div key={i} style={{fontSize:'9px',fontWeight:'800',color:'#bbb',letterSpacing:'1px',textAlign:i>1?'center':'left'}}>{h.toUpperCase()}</div>
          ))}
        </div>
        {data.exercise.map((ex,i)=>{
          const e=(ex&&typeof ex==='object')?ex:{name:'',sets:'',reps:'',duration:'',calories:'',done:false};
          return (
            <div key={i} style={{display:'grid',gridTemplateColumns:'16px 2fr 60px 60px 80px 76px 24px',gap:'6px',alignItems:'center',padding:'5px 0',borderBottom:'1px solid #f5f5f5', minWidth:isMobile?'560px':'auto'}}>
              <div onClick={()=>{const a=[...data.exercise];a[i]={...e,done:!e.done};upd('exercise',a);}}
                style={{width:'14px',height:'14px',border:'2px solid',borderRadius:'2px',cursor:'pointer',
                  borderColor:e.done?'#111':'#ccc',background:e.done?'#111':'transparent',display:'flex',alignItems:'center',justifyContent:'center'}}>
                {e.done&&<span style={{color:'#fff',fontSize:'9px'}}>✓</span>}
              </div>
              <input list="exercise-suggestions" value={e.name||''} onChange={ev=>{const a=[...data.exercise];a[i]={...e,name:ev.target.value};upd('exercise',a);}}
                placeholder="Exercise..." style={{border:'none',borderBottom:'1px solid #ebebeb',outline:'none',fontSize:'12px',color:'#333',background:'transparent',fontFamily:'inherit',padding:'2px 0'}} />
              {['sets','reps','duration'].map(k=>(
                <input key={k} value={e[k]||''} onChange={ev=>{const a=[...data.exercise];a[i]={...e,[k]:ev.target.value};upd('exercise',a);}}
                  placeholder="—" style={{border:'none',borderBottom:'1px solid #ebebeb',outline:'none',fontSize:'12px',color:'#666',background:'transparent',fontFamily:'inherit',padding:'2px 0',textAlign:'center'}} />
              ))}
              <div style={{display:'flex',alignItems:'center',gap:'3px'}}>
                <input value={e.calories||''} onChange={ev=>{const a=[...data.exercise];a[i]={...e,calories:ev.target.value};upd('exercise',a);}}
                  placeholder="0" style={{width:'44px',border:'1px solid #e8e8e8',borderRadius:'3px',padding:'3px 4px',fontSize:'11px',fontFamily:'inherit',outline:'none',textAlign:'right'}} />
                <span style={{fontSize:'10px',color:'#bbb'}}>cal</span>
              </div>
              <button onClick={()=>upd('exercise',data.exercise.filter((_,j)=>j!==i))} style={{background:'none',border:'none',color:'#e0e0e0',cursor:'pointer',fontSize:'15px'}}>×</button>
            </div>
          );
        })}
        </div>
        <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginTop:'10px'}}>
          <button onClick={()=>upd('exercise',[...data.exercise,{name:'',sets:'',reps:'',duration:'',calories:'',done:false}])}
            style={{background:'none',border:'1px dashed #e0e0e0',borderRadius:'4px',padding:'5px 14px',fontSize:'12px',color:'#bbb',cursor:'pointer',fontFamily:'inherit'}}>
            + Add exercise
          </button>
          {data.exercise.length>0&&(
            <span style={{fontSize:'12px',color:'#888'}}>
              🔥 {exerciseCal} kcal · Net: <strong style={{color:totalCal-exerciseCal<0?'#2a7a2a':'#111'}}>{totalCal-exerciseCal} kcal</strong>
            </span>
          )}
        </div>
      </div>

      {/* ── MOOD & WATER ── */}
      <Divider title="Mood & Wellness" />
      <div style={{display:'grid',gridTemplateColumns:isMobile?'1fr':'1fr 1fr',gap:'24px',marginBottom:'28px'}}>
        {/* 2-tier mood */}
        <div>
        {/* 2-tier mood — collapses after primary selection */}
          <div style={{fontSize:'11px',fontWeight:'800',letterSpacing:'1.5px',color:'#888',marginBottom:'10px'}}>HOW ARE YOU FEELING?</div>
          {!data.moodPrimary ? (
            // Tier 1: all options shown
            <div style={{display:'flex',gap:'5px',flexWrap:'wrap'}}>
              {Object.entries(MOOD_TIERS).map(([label,{emoji}])=>(
                <div key={label} onClick={()=>save({...data,moodPrimary:label,moodSecondary:''})}
                  style={{display:'flex',alignItems:'center',gap:'4px',padding:'4px 10px',borderRadius:'20px',cursor:'pointer',
                    border:'1.5px solid #e8e8e8',background:'transparent',color:'#555',fontSize:'12px',transition:'all 0.12s'}}>
                  <span style={{fontSize:'15px'}}>{emoji}</span> {label}
                </div>
              ))}
            </div>
          ) : (
            // Collapsed: show selected + secondary + change button
            <div>
              <div style={{display:'flex',alignItems:'center',gap:'8px',marginBottom:'8px'}}>
                <div style={{display:'flex',alignItems:'center',gap:'6px',padding:'5px 12px',borderRadius:'20px',
                  border:'2px solid #111',background:'#111',color:'#fff',fontSize:'13px',fontWeight:'700'}}>
                  <span style={{fontSize:'16px'}}>{MOOD_TIERS[data.moodPrimary]?.emoji}</span>
                  {data.moodPrimary}
                  {data.moodSecondary && <span style={{opacity:0.7,fontWeight:'400'}}>· {data.moodSecondary}</span>}
                </div>
                <button onClick={()=>save({...data,moodPrimary:'',moodSecondary:''})}
                  style={{fontSize:'11px',color:'#bbb',background:'none',border:'1px solid #e8e8e8',borderRadius:'20px',padding:'3px 8px',cursor:'pointer',fontFamily:'inherit'}}>
                  change
                </button>
              </div>
              {/* Secondary tags */}
              <div style={{display:'flex',gap:'5px',flexWrap:'wrap'}}>
                {MOOD_TIERS[data.moodPrimary]?.secondaries.map(tag=>{
                  const [label] = tag.split(' ');
                  return (
                    <div key={tag} onClick={()=>upd('moodSecondary',data.moodSecondary===label?'':label)}
                      style={{padding:'4px 10px',borderRadius:'20px',cursor:'pointer',fontSize:'12px',border:'1.5px solid',
                        borderColor:data.moodSecondary===label?'#555':'#e8e8e8',
                        background:data.moodSecondary===label?'#555':'transparent',
                        color:data.moodSecondary===label?'#fff':'#777',transition:'all 0.1s'}}>
                      {tag}
                    </div>
                  );
                })}
              </div>
            </div>
          )}
          {/* Mood timeline from schedule */}
          {Object.keys(data.scheduleMoods||{}).filter(k=>data.scheduleMoods[k]).length>0&&(
            <div style={{marginTop:'12px'}}>
              <div style={{fontSize:'10px',color:'#ccc',letterSpacing:'1px',marginBottom:'4px',fontWeight:'700'}}>MOOD LOG</div>
              <div style={{display:'flex',gap:'6px',flexWrap:'wrap'}}>
                {Object.entries(data.scheduleMoods).filter(([,v])=>v).map(([time,mood])=>(
                  <div key={time} style={{fontSize:'11px',color:'#aaa',display:'flex',alignItems:'center',gap:'3px'}}>
                    <span>{time}</span><span style={{fontSize:'14px'}}>{mood}</span>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>

        {/* Water stepper */}
        <div>
          <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:'10px'}}>
            <div style={{fontSize:'11px',fontWeight:'800',letterSpacing:'1.5px',color:'#888'}}>WATER INTAKE</div>
            <div style={{display:'flex',alignItems:'center',gap:'6px'}}>
              <span style={{fontSize:'11px',color:'#bbb'}}>Goal:</span>
              <button onClick={()=>upd('waterTarget',Math.max(1,data.waterTarget-1))} style={{width:'22px',height:'22px',border:'1px solid #e0e0e0',borderRadius:'3px',background:'none',cursor:'pointer',fontSize:'14px',display:'flex',alignItems:'center',justifyContent:'center',color:'#888'}}>−</button>
              <span style={{fontSize:'12px',fontWeight:'700',minWidth:'20px',textAlign:'center'}}>{data.waterTarget}</span>
              <button onClick={()=>upd('waterTarget',Math.min(20,data.waterTarget+1))} style={{width:'22px',height:'22px',border:'1px solid #e0e0e0',borderRadius:'3px',background:'none',cursor:'pointer',fontSize:'14px',display:'flex',alignItems:'center',justifyContent:'center',color:'#888'}}>+</button>
            </div>
          </div>
          {/* +/- stepper for intake */}
          <div style={{display:'flex',alignItems:'center',gap:'12px',marginBottom:'10px'}}>
            <button onClick={()=>upd('water',Math.max(0,data.water-1))} style={{width:'32px',height:'32px',border:'1.5px solid #e0e0e0',borderRadius:'50%',background:'none',cursor:'pointer',fontSize:'18px',display:'flex',alignItems:'center',justifyContent:'center',color:'#888',flexShrink:0}}>−</button>
            <div style={{flex:1,textAlign:'center'}}>
              <span style={{fontSize:'28px',fontWeight:'800',color:'#4a90d9'}}>{data.water}</span>
              <span style={{fontSize:'13px',color:'#bbb',marginLeft:'4px'}}>/ {data.waterTarget} glasses</span>
            </div>
            <button onClick={()=>upd('water',Math.min(data.waterTarget,data.water+1))} style={{width:'32px',height:'32px',border:'1.5px solid #4a90d9',borderRadius:'50%',background:'#e8f2fc',cursor:'pointer',fontSize:'18px',display:'flex',alignItems:'center',justifyContent:'center',color:'#4a90d9',flexShrink:0}}>+</button>
          </div>
          {/* Visual glasses */}
          <div style={{display:'flex',gap:'5px',flexWrap:'wrap',marginBottom:'8px'}}>
            {Array.from({length:data.waterTarget},(_,i)=>(
              <div key={i} onClick={()=>upd('water',i<data.water?i:i+1)}
                style={{width:'28px',height:'28px',borderRadius:'4px',border:'1.5px solid',cursor:'pointer',display:'flex',alignItems:'center',justifyContent:'center',fontSize:'14px',
                  borderColor:i<data.water?'#4a90d9':'#e8e8e8',background:i<data.water?'#e8f2fc':'transparent',transition:'all 0.1s'}}>
                {i<data.water?'💧':'○'}
              </div>
            ))}
          </div>
          <div style={{height:'5px',background:'#f0f0f0',borderRadius:'3px',overflow:'hidden'}}>
            <div style={{height:'100%',width:`${waterPct}%`,background:'#4a90d9',borderRadius:'3px',transition:'width 0.3s'}} />
          </div>
          <div style={{fontSize:'11px',color:'#bbb',marginTop:'4px'}}>{waterPct}% of daily goal</div>
        </div>
      </div>

      {/* ── BRAIN DUMP ── */}
      <Divider title="Brain Dump" />
      <div style={{marginBottom:'28px'}}>
        <SpeechTextarea value={data.brainDump} onChange={v=>upd('brainDump',v)} placeholder="Get everything out of your head. No filter. Write or speak..." rows={4} />
      </div>

      {/* ── FOR TOMORROW ── */}
      <Divider title="Plan For Tomorrow" />
      <div style={{marginBottom:'28px'}}>
        <div style={{fontSize:'11px',color:'#bbb',marginBottom:'10px'}}>↩ Auto-appears in tomorrow's to-do list</div>
        {data.forTomorrow.map((item,i)=>{
          const it=(item&&typeof item==='object')?item:{text:'',done:false};
          return (
            <div key={i} style={{display:'flex',alignItems:'center',gap:'8px',padding:'4px 0',borderBottom:'1px solid #f8f8f8'}}>
              <span style={{fontSize:'11px',color:'#ccc',flexShrink:0}}>→</span>
              <input value={it.text||''} onChange={e=>{
                const ft=[...data.forTomorrow]; ft[i]={...it,text:e.target.value}; saveForTomorrow(ft);
              }} placeholder="Plan for tomorrow..."
                style={{flex:1,border:'none',borderBottom:'1px solid #f0f0f0',outline:'none',fontSize:'13px',color:'#333',background:'transparent',fontFamily:'inherit',padding:'3px 0'}} />
              {data.forTomorrow.length>2&&(
                <button onClick={()=>saveForTomorrow(data.forTomorrow.filter((_,j)=>j!==i))} style={{background:'none',border:'none',color:'#e8e8e8',cursor:'pointer',fontSize:'14px'}}>×</button>
              )}
            </div>
          );
        })}
        <button onClick={()=>saveForTomorrow([...data.forTomorrow,{text:'',done:false}])}
          style={{marginTop:'8px',background:'none',border:'1px dashed #e0e0e0',borderRadius:'4px',padding:'4px 14px',fontSize:'12px',color:'#bbb',cursor:'pointer',fontFamily:'inherit'}}>
          + Add
        </button>
      </div>

      {/* ── NOTES ── */}
      <Divider title="Notes" />
      <div style={{marginBottom:'28px'}}>
        <SpeechTextarea value={data.notes} onChange={v=>upd('notes',v)} placeholder="Miscellaneous notes for today..." rows={3} />
      </div>

      {/* ── END OF DAY REFLECTION ── */}
      <Divider title="End of Day Reflection" />
      <div style={{marginBottom:'24px'}}>
        <div style={{display:'grid',gridTemplateColumns:isMobile?'1fr':'1fr 1fr',gap:'24px'}}>
          <div>
            {/* Gratitude — adjustable count */}
            <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:'10px'}}>
              <div style={{fontSize:'11px',fontWeight:'800',letterSpacing:'1.5px',color:'#888'}}>GRATITUDE</div>
              <div style={{display:'flex',alignItems:'center',gap:'4px'}}>
                <button onClick={()=>upd('gratitudeCount',Math.max(1,gCount-1))} style={{width:'20px',height:'20px',border:'1px solid #e0e0e0',borderRadius:'3px',background:'none',cursor:'pointer',fontSize:'13px',display:'flex',alignItems:'center',justifyContent:'center',color:'#888'}}>−</button>
                <span style={{fontSize:'11px',color:'#aaa',minWidth:'14px',textAlign:'center'}}>{gCount}</span>
                <button onClick={()=>upd('gratitudeCount',Math.min(8,gCount+1))} style={{width:'20px',height:'20px',border:'1px solid #e0e0e0',borderRadius:'3px',background:'none',cursor:'pointer',fontSize:'13px',display:'flex',alignItems:'center',justifyContent:'center',color:'#888'}}>+</button>
              </div>
            </div>
            {Array.from({length:gCount},(_,i)=>(
              <div key={i} style={{display:'flex',alignItems:'center',gap:'8px',marginBottom:'8px'}}>
                <span style={{fontSize:'14px',color:'#ccc'}}>✦</span>
                <input value={(data.gratitude||[])[i]||''} onChange={e=>{const g=[...data.gratitude];g[i]=e.target.value;upd('gratitude',g);}}
                  placeholder="I'm grateful for..."
                  style={{flex:1,border:'none',borderBottom:'1.5px solid #e8e8e8',outline:'none',fontSize:'13px',color:'#333',background:'transparent',fontFamily:'inherit',padding:'4px 0'}} />
              </div>
            ))}
            <div style={{marginTop:'16px'}}>
              <div style={{fontSize:'11px',fontWeight:'800',letterSpacing:'1.5px',color:'#888',marginBottom:'7px'}}>TODAY'S REWARD</div>
              <input value={data.reward||''} onChange={e=>upd('reward',e.target.value)} placeholder="I'll treat myself with..."
                style={{width:'100%',border:'none',borderBottom:'1.5px solid #e8e8e8',outline:'none',fontSize:'13px',color:'#333',background:'transparent',fontFamily:'inherit',padding:'4px 0',boxSizing:'border-box'}} />
            </div>
            <div style={{marginTop:'16px'}}>
              <div style={{fontSize:'11px',fontWeight:'800',letterSpacing:'1.5px',color:'#888',marginBottom:'7px'}}>RATE TODAY</div>
              <div style={{display:'flex',gap:'6px',alignItems:'center'}}>
                {[1,2,3,4,5].map(n=>(
                  <span key={n} onClick={()=>upd('rating',n)} style={{fontSize:'22px',cursor:'pointer',color:(data.rating||0)>=n?'#f5b800':'#e8e8e8',transition:'color 0.1s'}}>★</span>
                ))}
                {data.rating>0&&<span style={{fontSize:'12px',color:'#bbb',marginLeft:'4px'}}>{['','Rough','Okay','Decent','Good','Amazing!'][data.rating]}</span>}
              </div>
            </div>
          </div>
          <div>
            <div style={{fontSize:'11px',fontWeight:'800',letterSpacing:'1.5px',color:'#888',marginBottom:'10px'}}>DAILY SUMMARY</div>
            <SpeechTextarea value={data.reflection} onChange={v=>upd('reflection',v)}
              placeholder="What went well? What would you do differently? What are you proud of?" rows={8} />
          </div>
        </div>

        {/* Stats bar */}
        <div style={{display:'flex',marginTop:'20px',border:'1px solid #e8e8e8',borderRadius:'6px',overflow:'hidden',flexWrap:isMobile?'wrap':'nowrap'}}>
          {[
            ['Tasks',`${todoDone}/${todoTotal}`,todoDone===todoTotal&&todoTotal>0?'#2a7a2a':'#111'],
            ['Water',`${data.water}/${data.waterTarget}`,waterPct>=100?'#4a90d9':'#111'],
            ['Cal In',`${totalCal}kcal`,'#111'],
            ['Cal Out',`${exerciseCal}kcal`,'#111'],
            ['Net',`${totalCal-exerciseCal}kcal`,totalCal-exerciseCal<0?'#2a7a2a':'#111'],
            ['Mood',`${data.moodPrimary||'—'}${data.moodSecondary?' · '+data.moodSecondary:''}`, '#111'],
            ['Rating',data.rating?'★'.repeat(data.rating):'—','#f5b800'],
          ].map(([label,val,color],i,arr)=>(
            <div key={label} style={{flex:isMobile?'1 1 50%':1,textAlign:'center',padding:'10px 6px',borderRight:i<arr.length-1?'1px solid #f0f0f0':'none',background:'#fafafa'}}>
              <div style={{fontSize:'9px',color:'#bbb',letterSpacing:'1.5px',marginBottom:'3px',fontWeight:'700'}}>{label.toUpperCase()}</div>
              <div style={{fontSize:'12px',fontWeight:'800',color}}>{val}</div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { DailyPlanner, MicButton, SpeechTextarea, useSpeech });
