// StarThink — Weekly Master Planner (v2)
// Fixed: overflow, task counters, habit delete, removed meetings tab, smart prompts

function WeeklyPlanner() {
  const getMonday = (d) => {
    const dt = new Date(d + 'T12:00:00');
    const day = dt.getDay();
    const diff = dt.getDate() - day + (day === 0 ? -6 : 1);
    return new Date(dt.setDate(diff)).toISOString().split('T')[0];
  };
  const [weekStart, setWeekStart] = React.useState(ST.get('weekly_start', getMonday(new Date().toISOString().split('T')[0])));
  const key = `weekly_${weekStart}`;
  const defaultWeekly = () => ({
    thisWeekIntent: '', nextWeek: '', priorities: ['', '', ''],
    notes: '', dayTasks: {}, dayGratitude: {},
    habits: [
      { name: 'Meditation', days: {} }, { name: 'Exercise', days: {} },
      { name: 'Journaling', days: {} }, { name: 'Read', days: {} },
      { name: 'Water (8 cups)', days: {} }
    ],
    mirMorning: {}, weeklyGratitude: [], goals: ['', '', '', '', '']
  });

  const sanitizeWeekly = (d) => {
    if (!d) return defaultWeekly();
    if (!Array.isArray(d.habits)) d.habits = defaultWeekly().habits;
    if (!Array.isArray(d.priorities)) d.priorities = ['', '', ''];
    if (!Array.isArray(d.goals)) d.goals = ['', '', '', '', ''];
    if (!d.dayTasks || typeof d.dayTasks !== 'object' || Array.isArray(d.dayTasks)) d.dayTasks = {};
    if (!d.dayGratitude || typeof d.dayGratitude !== 'object') d.dayGratitude = {};
    // ensure each habit has a days object
    d.habits = d.habits.map(h => ({ name: h.name || '', days: (h.days && typeof h.days === 'object' ? h.days : {}) }));
    return { ...defaultWeekly(), ...d };
  };

  const [data, setData] = React.useState(() => sanitizeWeekly(ST.get(key)));

  React.useEffect(() => {
    setData(sanitizeWeekly(ST.get(key)));
  }, [key]);

  const save = (updated) => { setData(updated); ST.set(key, updated); };
  const upd = (field, val) => save({ ...data, [field]: val });

  const [tab, setTab] = React.useState('overview');
  const tabs = [
    { id: 'overview', label: 'Overview' },
    { id: 'habits', label: 'Habits' },
    { id: 'morning', label: 'Morning Routine' }
  ];

  const days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
  const getDate = (i) => {
    const d = new Date(weekStart + 'T12:00:00');
    d.setDate(d.getDate() + i);
    return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
  };

  const changeWeek = (dir) => {
    const d = new Date(weekStart + 'T12:00:00');
    d.setDate(d.getDate() + dir * 7);
    const newStart = d.toISOString().split('T')[0];
    setWeekStart(newStart);
    ST.set('weekly_start', newStart);
  };

  return (
    <div className="planner-page" style={{ maxWidth: '1100px' }}>
      {/* Header */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '24px' }}>
        <div>
          <div style={{ fontSize: '28px', fontWeight: '800', letterSpacing: '-0.5px' }}>Weekly Planner</div>
          <div style={{ fontSize: '11px', color: '#999', letterSpacing: '2px', textTransform: 'uppercase', marginTop: '3px' }}>StarThink</div>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
          <button onClick={() => changeWeek(-1)} style={{ background: 'none', border: '1px solid #e0e0e0', borderRadius: '4px', padding: '6px 12px', cursor: 'pointer', fontFamily: 'inherit', fontSize: '14px' }}>‹</button>
          <div style={{ textAlign: 'center' }}>
            <div style={{ fontSize: '14px', fontWeight: '700' }}>{getDate(0)} — {getDate(6)}</div>
            <input type="date" value={weekStart} onChange={e => { const m = getMonday(e.target.value); setWeekStart(m); ST.set('weekly_start', m); }}
              style={{ fontSize: '11px', color: '#aaa', border: 'none', outline: 'none', fontFamily: 'inherit', cursor: 'pointer', background: 'transparent', marginTop: '2px' }} />
          </div>
          <button onClick={() => changeWeek(1)} style={{ background: 'none', border: '1px solid #e0e0e0', borderRadius: '4px', padding: '6px 12px', cursor: 'pointer', fontFamily: 'inherit', fontSize: '14px' }}>›</button>
        </div>
      </div>

      {/* Tabs */}
      <div style={{ display: 'flex', gap: '2px', marginBottom: '24px', borderBottom: '2px solid #111' }}>
        {tabs.map(t => (
          <button key={t.id} onClick={() => setTab(t.id)}
            style={{ padding: '7px 18px', 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', letterSpacing: '0.5px' }}>
            {t.label}
          </button>
        ))}
      </div>

      {tab === 'overview' && (
        <div>
          {/* Intent + priorities */}
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '20px', marginBottom: '28px' }}>
            <div>
              <div style={{ fontSize: '11px', fontWeight: '700', letterSpacing: '1px', color: '#888', marginBottom: '8px' }}>THIS WEEK I WANT TO...</div>
              <textarea value={data.thisWeekIntent} onChange={e => upd('thisWeekIntent', e.target.value)}
                placeholder="Set your intention for the week..."
                style={{ width: '100%', minHeight: '80px', border: '1px solid #e8e8e8', borderRadius: '4px', padding: '8px', fontSize: '13px', fontFamily: 'inherit', resize: 'none', outline: 'none', boxSizing: 'border-box', color: '#333', lineHeight: '1.6' }} />
            </div>
            <div>
              <div style={{ fontSize: '11px', fontWeight: '700', letterSpacing: '1px', color: '#888', marginBottom: '8px' }}>TOP PRIORITIES</div>
              {[0, 1, 2].map(i => (
                <div key={i} style={{ display: 'flex', alignItems: 'center', gap: '6px', marginBottom: '6px' }}>
                  <span style={{ width: '18px', height: '18px', borderRadius: '50%', background: '#111', color: '#fff', fontSize: '10px', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, fontWeight: '700' }}>{i + 1}</span>
                  <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: '1px solid #e0e0e0', outline: 'none', fontSize: '13px', color: '#111', background: 'transparent', fontFamily: 'inherit', padding: '3px 0' }} />
                </div>
              ))}
            </div>
            <div>
              <div style={{ fontSize: '11px', fontWeight: '700', letterSpacing: '1px', color: '#888', marginBottom: '8px' }}>NEXT WEEK PREVIEW</div>
              <textarea value={data.nextWeek} onChange={e => upd('nextWeek', e.target.value)}
                placeholder="What's coming up next week..."
                style={{ width: '100%', minHeight: '80px', border: '1px solid #e8e8e8', borderRadius: '4px', padding: '8px', fontSize: '13px', fontFamily: 'inherit', resize: 'none', outline: 'none', boxSizing: 'border-box', color: '#333', lineHeight: '1.6' }} />
            </div>
          </div>

          {/* 7-day grid — horizontally scrollable on small screens */}
          <div style={{ overflowX: 'auto', marginBottom: '24px' }}>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, minmax(130px, 1fr))', gap: '6px', minWidth: '700px' }}>
              {days.map((day, i) => {
                const dayTasks = (data.dayTasks[day] || []);
                const done = dayTasks.filter(t => t?.done).length;
                const total = dayTasks.filter(t => t?.text).length;
                return (
                  <div key={day} style={{ display: 'flex', flexDirection: 'column' }}>
                    {/* Day header */}
                    <div style={{ background: '#111', color: '#fff', padding: '8px 10px', borderRadius: '4px 4px 0 0' }}>
                      <div style={{ fontSize: '12px', fontWeight: '700', letterSpacing: '1px' }}>{day}</div>
                      <div style={{ fontSize: '10px', color: '#888', marginTop: '1px' }}>{getDate(i)}</div>
                      {total > 0 && <div style={{ fontSize: '10px', color: done === total ? '#6fcf6f' : '#aaa', marginTop: '3px' }}>{done}/{total} done</div>}
                    </div>

                    {/* Tasks */}
                    <div style={{ border: '1px solid #e8e8e8', borderTop: 'none', padding: '8px', flex: 1, borderRadius: '0 0 4px 4px', background: '#fff' }}>
                      <div style={{ fontSize: '10px', color: '#bbb', fontWeight: '700', letterSpacing: '1px', marginBottom: '6px' }}>TASKS</div>
                      <div style={{ maxHeight: '200px', overflowY: 'auto' }}>
                        {[...dayTasks, { text: '', done: false }].map((task, j) => {
                          const t = task || { text: '', done: false };
                          return (
                            <div key={j} style={{ display: 'flex', alignItems: 'center', gap: '4px', marginBottom: '4px' }}>
                              <div onClick={() => {
                                const dt = { ...data.dayTasks };
                                const arr = [...(dt[day] || [])];
                                if (!arr[j]) arr[j] = { text: '', done: false };
                                arr[j] = { ...arr[j], done: !arr[j].done };
                                dt[day] = arr;
                                upd('dayTasks', dt);
                              }} style={{ width: '12px', height: '12px', border: '1.5px solid', borderRadius: '2px', flexShrink: 0, cursor: 'pointer',
                                borderColor: t.done ? '#111' : '#ccc', background: t.done ? '#111' : 'transparent', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                                {t.done && <span style={{ color: '#fff', fontSize: '8px' }}>✓</span>}
                              </div>
                              <input value={t.text || ''} onChange={e => {
                                const dt = { ...data.dayTasks };
                                const arr = [...(dt[day] || [])];
                                if (!arr[j]) arr[j] = { text: '', done: false };
                                arr[j] = { ...arr[j], text: e.target.value };
                                // auto-add new row when typing in last
                                if (j === arr.length - 1 && e.target.value) arr.push({ text: '', done: false });
                                dt[day] = arr;
                                upd('dayTasks', dt);
                              }} placeholder={j === dayTasks.length ? '+ add' : ''}
                                style={{ flex: 1, border: 'none', outline: 'none', fontSize: '11px', color: t.done ? '#bbb' : '#333',
                                  textDecoration: t.done ? 'line-through' : 'none', background: 'transparent', fontFamily: 'inherit', padding: '1px 0',
                                  borderBottom: '1px solid #f5f5f5' }} />
                            </div>
                          );
                        })}
                      </div>

                      {/* Gratitude */}
                      <div style={{ marginTop: '10px', paddingTop: '8px', borderTop: '1px dashed #eee' }}>
                        <div style={{ fontSize: '10px', color: '#bbb', fontWeight: '700', letterSpacing: '1px', marginBottom: '4px' }}>GRATEFUL FOR</div>
                        <input value={data.dayGratitude[day] || ''} onChange={e => upd('dayGratitude', { ...data.dayGratitude, [day]: e.target.value })}
                          placeholder="One thing..."
                          style={{ width: '100%', border: 'none', borderBottom: '1px solid #f0f0f0', outline: 'none', fontSize: '11px', color: '#666', background: 'transparent', fontFamily: 'inherit', padding: '2px 0', boxSizing: 'border-box' }} />
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>

          {/* Notes */}
          <div>
            <div style={{ fontSize: '11px', fontWeight: '700', letterSpacing: '1px', color: '#888', marginBottom: '8px' }}>WEEKLY NOTES</div>
            <textarea value={data.notes} onChange={e => upd('notes', e.target.value)} placeholder="Anything else on your mind this week..."
              style={{ width: '100%', minHeight: '80px', border: '1px solid #e8e8e8', borderRadius: '4px', padding: '8px', fontSize: '13px', fontFamily: 'inherit', resize: 'none', outline: 'none', boxSizing: 'border-box', color: '#333' }} />
          </div>
        </div>
      )}

      {tab === 'habits' && (
        <div>
          <div style={{ marginBottom: '12px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <div style={{ fontSize: '13px', color: '#888' }}>Track your habits across the week. Click circles to check off.</div>
            <button onClick={() => upd('habits', [...data.habits, { name: '', days: {} }])}
              style={{ padding: '6px 14px', background: '#111', color: '#fff', border: 'none', borderRadius: '4px', fontSize: '12px', cursor: 'pointer', fontFamily: 'inherit' }}>
              + Add Habit
            </button>
          </div>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead>
              <tr>
                <th style={{ textAlign: 'left', padding: '8px 10px', fontSize: '11px', letterSpacing: '1px', fontWeight: '700', borderBottom: '2px solid #111', width: '200px' }}>HABIT</th>
                {days.map((d, i) => (
                  <th key={d} style={{ padding: '8px 6px', fontSize: '11px', letterSpacing: '1px', fontWeight: '700', borderBottom: '2px solid #111', textAlign: 'center' }}>
                    {d}<br /><span style={{ fontWeight: '400', color: '#aaa', fontSize: '10px' }}>{getDate(i)}</span>
                  </th>
                ))}
                <th style={{ padding: '8px 6px', fontSize: '11px', letterSpacing: '1px', fontWeight: '700', borderBottom: '2px solid #111', textAlign: 'center' }}>%</th>
                <th style={{ width: '30px', borderBottom: '2px solid #111' }}></th>
              </tr>
            </thead>
            <tbody>
              {data.habits.map((habit, hi) => {
                const done = days.filter(d => habit.days[d]).length;
                return (
                  <tr key={hi} style={{ background: hi % 2 === 0 ? '#fafafa' : '#fff' }}>
                    <td style={{ padding: '8px 10px' }}>
                      <input value={habit.name} onChange={e => { const h = [...data.habits]; h[hi] = { ...h[hi], name: e.target.value }; upd('habits', h); }}
                        placeholder="Habit name..." style={{ border: 'none', outline: 'none', fontSize: '13px', color: '#111', background: 'transparent', fontFamily: 'inherit', width: '100%' }} />
                    </td>
                    {days.map(day => (
                      <td key={day} style={{ textAlign: 'center', padding: '8px 6px' }}>
                        <div onClick={() => { const h = [...data.habits]; h[hi] = { ...h[hi], days: { ...h[hi].days, [day]: !h[hi].days[day] } }; upd('habits', h); }}
                          style={{ width: '26px', height: '26px', borderRadius: '50%', border: '2px solid', cursor: 'pointer', margin: '0 auto',
                            borderColor: habit.days[day] ? '#111' : '#ddd', background: habit.days[day] ? '#111' : 'transparent',
                            display: 'flex', alignItems: 'center', justifyContent: 'center', transition: 'all 0.12s' }}>
                          {habit.days[day] && <span style={{ color: '#fff', fontSize: '11px' }}>✓</span>}
                        </div>
                      </td>
                    ))}
                    <td style={{ textAlign: 'center', padding: '8px 6px', fontSize: '12px', fontWeight: '700', color: done === 7 ? '#2a7a2a' : done >= 4 ? '#888' : '#ccc' }}>
                      {Math.round(done / 7 * 100)}%
                    </td>
                    <td style={{ textAlign: 'center', padding: '8px 4px' }}>
                      <button onClick={() => upd('habits', data.habits.filter((_, j) => j !== hi))}
                        style={{ background: 'none', border: 'none', color: '#ddd', cursor: 'pointer', fontSize: '16px', padding: '0' }}>×</button>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>

          {/* Habit stats */}
          {data.habits.length > 0 && (
            <div style={{ marginTop: '20px', padding: '16px', background: '#f8f8f8', borderRadius: '6px', display: 'flex', gap: '24px' }}>
              <div>
                <div style={{ fontSize: '10px', color: '#aaa', letterSpacing: '1px' }}>BEST STREAK</div>
                <div style={{ fontSize: '16px', fontWeight: '700' }}>{Math.max(...data.habits.map(h => days.filter(d => h.days[d]).length))} days</div>
              </div>
              <div>
                <div style={{ fontSize: '10px', color: '#aaa', letterSpacing: '1px' }}>OVERALL COMPLETION</div>
                <div style={{ fontSize: '16px', fontWeight: '700' }}>
                  {Math.round(data.habits.reduce((s, h) => s + days.filter(d => h.days[d]).length, 0) / (data.habits.length * 7) * 100)}%
                </div>
              </div>
              <div>
                <div style={{ fontSize: '10px', color: '#aaa', letterSpacing: '1px' }}>PERFECT HABITS</div>
                <div style={{ fontSize: '16px', fontWeight: '700' }}>{data.habits.filter(h => days.filter(d => h.days[d]).length === 7).length}</div>
              </div>
            </div>
          )}
        </div>
      )}

      {tab === 'morning' && (
        <div>
          <div style={{ fontSize: '13px', fontStyle: 'italic', color: '#888', marginBottom: '20px' }}>
            Miracle Morning Routine — check off each practice every day
          </div>
          {['Meditation', 'Affirmations', 'Visualization', 'Journaling', 'Exercise'].map(practice => (
            <div key={practice} style={{ marginBottom: '12px', display: 'flex', alignItems: 'center', gap: '16px' }}>
              <div style={{ width: '110px', fontSize: '12px', fontWeight: '700', color: '#555', letterSpacing: '0.5px', flexShrink: 0 }}>{practice}</div>
              <div style={{ display: 'flex', gap: '8px' }}>
                {days.map((day, i) => {
                  const pkey = practice.toLowerCase();
                  const mm = data.mirMorning || {};
                  const done = mm[pkey]?.[day];
                  return (
                    <div key={day} style={{ textAlign: 'center' }}>
                      <div style={{ fontSize: '10px', color: '#bbb', marginBottom: '3px' }}>{day[0]}</div>
                      <div onClick={() => { const mm = { ...data.mirMorning }; if (!mm[pkey]) mm[pkey] = {}; mm[pkey][day] = !mm[pkey][day]; upd('mirMorning', mm); }}
                        style={{ width: '30px', height: '30px', borderRadius: '6px', border: '2px solid', cursor: 'pointer',
                          borderColor: done ? '#111' : '#e0e0e0', background: done ? '#111' : 'transparent',
                          display: 'flex', alignItems: 'center', justifyContent: 'center', transition: 'all 0.12s' }}>
                        {done && <span style={{ color: '#fff', fontSize: '14px' }}>✓</span>}
                      </div>
                    </div>
                  );
                })}
              </div>
              <div style={{ fontSize: '11px', color: '#aaa', marginLeft: 'auto' }}>
                {days.filter(d => (data.mirMorning?.[practice.toLowerCase()])?.[d]).length}/7
              </div>
            </div>
          ))}

          <div style={{ marginTop: '28px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '20px' }}>
            <div>
              <div style={{ fontSize: '11px', fontWeight: '700', letterSpacing: '1px', color: '#888', marginBottom: '10px' }}>5 THINGS I WANT TO ACHIEVE</div>
              {[0, 1, 2, 3, 4].map(i => (
                <div key={i} style={{ display: 'flex', alignItems: 'center', gap: '6px', marginBottom: '8px' }}>
                  <span style={{ fontSize: '11px', color: '#ddd', width: '16px' }}>{i + 1}.</span>
                  <input value={(data.goals || [])[i] || ''} onChange={e => { const g = [...(data.goals || [])]; g[i] = e.target.value; upd('goals', g); }}
                    placeholder="Goal..."
                    style={{ flex: 1, border: 'none', borderBottom: '1px solid #e8e8e8', outline: 'none', fontSize: '13px', color: '#333', background: 'transparent', fontFamily: 'inherit', padding: '4px 0' }} />
                </div>
              ))}
            </div>
            <div>
              <div style={{ fontSize: '11px', fontWeight: '700', letterSpacing: '1px', color: '#888', marginBottom: '10px' }}>I'M GRATEFUL FOR THIS WEEK</div>
              {[0, 1, 2, 3, 4, 5].map(i => (
                <div key={i} style={{ display: 'flex', alignItems: 'center', gap: '6px', marginBottom: '6px' }}>
                  <span style={{ fontSize: '14px' }}>✦</span>
                  <input value={(data.weeklyGratitude || [])[i] || ''} onChange={e => { const g = [...(data.weeklyGratitude || [])]; g[i] = e.target.value; upd('weeklyGratitude', g); }}
                    placeholder="Grateful for..."
                    style={{ flex: 1, border: 'none', borderBottom: '1px solid #e8e8e8', outline: 'none', fontSize: '13px', color: '#333', background: 'transparent', fontFamily: 'inherit', padding: '3px 0' }} />
                </div>
              ))}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

window.WeeklyPlanner = WeeklyPlanner;
