// StarThink — Monthly Master Planner
// Combines: Monthly Planner, Monthly Bullet Journal, Monthly Home Reflection,
// Monthly Home Reset Checklist, 42 Easy Tracker

function MonthlyPlanner() {
  const now = new Date();
  const [year, setYear] = React.useState(ST.get('monthly_year', now.getFullYear()));
  const [month, setMonth] = React.useState(ST.get('monthly_month', now.getMonth()));
  const key = `monthly_${year}_${month}`;
  const [data, setData] = React.useState(() => ST.get(key, {
    goals: [], todos: [], notes: '',
    reflection: { calm:'', beauty:'', routines:'', shift:'' },
    homeReset: { declutter:[], restock:[], clean:[], refresh:[] },
    dayNotes: {}, dayMoods: {}
  }));

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

  const [tab, setTab] = React.useState('calendar');
  const tabs = [{ id:'calendar', label:'Calendar' }, { id:'goals', label:'Goals & Lists' },
    { id:'reflection', label:'Home Reflection' }, { id:'reset', label:'Home Reset' }];

  const monthNames = ['January','February','March','April','May','June','July','August','September','October','November','December'];
  const daysInMonth = new Date(year, month + 1, 0).getDate();
  const firstDay = new Date(year, month, 1).getDay();
  const adjustedFirst = firstDay === 0 ? 6 : firstDay - 1; // Mon-start

  const moods = ['😄','🙂','😐','😔','😤'];
  const weekDays = ['Mon','Tue','Wed','Thu','Fri','Sat','Sun'];

  const changeMonth = (dir) => {
    let m = month + dir, y = year;
    if (m < 0) { m = 11; y--; } if (m > 11) { m = 0; y++; }
    setMonth(m); setYear(y); ST.set('monthly_month', m); ST.set('monthly_year', y);
  };

  const homeResetSections = [
    { key:'declutter', label:'Declutter Hot Spots', placeholder:'e.g. Entryway drop zone...' },
    { key:'restock', label:'Restock Essentials', placeholder:'e.g. Cleaning supplies...' },
    { key:'clean', label:'Clean & Reset', placeholder:'e.g. Vacuum floors...' },
    { key:'refresh', label:'Refresh the Feeling', placeholder:'e.g. Change seasonal decor...' }
  ];

  return (
    <div className="planner-page">
      {/* Header */}
      <div style={{ borderBottom:'2px solid #111', marginBottom:'16px', paddingBottom:'10px', display:'flex', justifyContent:'space-between', alignItems:'center' }}>
        <div>
          <div style={{ fontSize:'22px', fontWeight:'800', letterSpacing:'-0.5px', color:'#111' }}>Monthly Planner</div>
          <div style={{ fontSize:'11px', color:'#888', letterSpacing:'1px', textTransform:'uppercase', marginTop:'2px' }}>StarThink</div>
        </div>
        <div style={{ display:'flex', alignItems:'center', gap:'12px' }}>
          <button onClick={() => changeMonth(-1)} style={{ background:'none',border:'1px solid #ccc',borderRadius:'3px',padding:'4px 10px',cursor:'pointer',fontFamily:'inherit',fontSize:'13px' }}>‹</button>
          <span style={{ fontSize:'16px', fontWeight:'700', minWidth:'140px', textAlign:'center' }}>{monthNames[month]} {year}</span>
          <button onClick={() => changeMonth(1)} style={{ background:'none',border:'1px solid #ccc',borderRadius:'3px',padding:'4px 10px',cursor:'pointer',fontFamily:'inherit',fontSize:'13px' }}>›</button>
        </div>
      </div>

      {/* Tabs */}
      <div style={{ display:'flex', gap:'2px', marginBottom:'16px', borderBottom:'2px solid #111' }}>
        {tabs.map(t => (
          <button key={t.id} onClick={() => setTab(t.id)}
            style={{ padding:'6px 16px', 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 === 'calendar' && (
        <div style={{ display:'grid', gridTemplateColumns:'1fr 220px', gap:'20px' }}>
          <div>
            {/* Day headers */}
            <div style={{ display:'grid', gridTemplateColumns:'repeat(7,1fr)', gap:'2px', marginBottom:'2px' }}>
              {weekDays.map(d => (
                <div key={d} style={{ textAlign:'center', fontSize:'11px', fontWeight:'700', color:'#888', letterSpacing:'1px', padding:'4px 0' }}>{d}</div>
              ))}
            </div>
            {/* Calendar grid */}
            <div style={{ display:'grid', gridTemplateColumns:'repeat(7,1fr)', gap:'2px' }}>
              {Array.from({ length: adjustedFirst }, (_, i) => <div key={`e${i}`} />)}
              {Array.from({ length: daysInMonth }, (_, i) => {
                const day = i + 1;
                const isToday = new Date().getDate() === day && new Date().getMonth() === month && new Date().getFullYear() === year;
                return (
                  <div key={day} style={{ border:'1px solid #e8e8e8', borderRadius:'3px', padding:'4px', minHeight:'70px',
                    background: isToday ? '#fffff8' : '#fff', borderColor: isToday ? '#111' : '#e8e8e8' }}>
                    <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:'2px' }}>
                      <span style={{ fontSize:'11px', fontWeight:isToday?'800':'600', color:isToday?'#111':'#888' }}>{day}</span>
                      <select value={data.dayMoods[day]||''} onChange={e => upd('dayMoods',{...data.dayMoods,[day]:e.target.value})}
                        style={{ border:'none',background:'transparent',fontSize:'13px',cursor:'pointer',outline:'none',padding:0 }}>
                        <option value="">·</option>
                        {moods.map(m => <option key={m} value={m}>{m}</option>)}
                      </select>
                    </div>
                    <textarea value={data.dayNotes[day]||''} onChange={e => upd('dayNotes',{...data.dayNotes,[day]:e.target.value})}
                      style={{ width:'100%',border:'none',outline:'none',resize:'none',fontSize:'10px',fontFamily:'inherit',color:'#555',background:'transparent',padding:0,boxSizing:'border-box',minHeight:'44px' }}
                      placeholder="" />
                  </div>
                );
              })}
            </div>
          </div>
          {/* Sidebar */}
          <div>
            <STSection title="Monthly Goals">
              <STCheckList items={data.goals} count={8} placeholder="Goal..." onToggle={(i,v) => { const g=[...(data.goals||[])]; if(!g[i]) g[i]={text:'',done:false}; g[i]={...g[i],done:v}; upd('goals',g); }} onEdit={(i,v) => { const g=[...(data.goals||[])]; if(!g[i]) g[i]={text:'',done:false}; g[i]={...g[i],text:v}; upd('goals',g); }} />
            </STSection>
            <STSection title="To-Do List">
              <div style={{ maxHeight:'200px', overflowY:'auto' }}>
                {[...(data.todos||[]), {text:'',done:false}].map((item, i) => {
                  const it = (item && typeof item==='object') ? item : {text:item||'',done:false};
                  const isDummy = i === (data.todos||[]).length;
                  return (
                    <div key={i} style={{ display:'flex', alignItems:'center', gap:'6px', padding:'3px 0', borderBottom:'1px solid #f5f5f5' }}>
                      {!isDummy && (
                        <div onClick={() => { const t=[...(data.todos||[])]; t[i]={...it,done:!it.done}; upd('todos',t); }}
                          style={{ width:'14px',height:'14px',border:'1.5px solid',borderRadius:'2px',flexShrink:0,cursor:'pointer',
                            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>
                      )}
                      {isDummy && <span style={{width:'14px',flexShrink:0,fontSize:'11px',color:'#ddd'}}>+</span>}
                      <input value={it.text||''} onChange={e => {
                        const t=[...(data.todos||[])];
                        if(isDummy) t.push({text:e.target.value,done:false});
                        else t[i]={...it,text:e.target.value};
                        upd('todos',t);
                      }} placeholder={isDummy?'Add task...':''}
                        style={{ flex:1,border:'none',outline:'none',fontSize:'12px',color:it.done?'#bbb':'#333',
                          textDecoration:it.done?'line-through':'none',background:'transparent',fontFamily:'inherit',padding:'2px 0' }} />
                      {!isDummy && <button onClick={() => upd('todos',(data.todos||[]).filter((_,j)=>j!==i))} style={{background:'none',border:'none',color:'#e8e8e8',cursor:'pointer',fontSize:'13px',padding:0}}>×</button>}
                    </div>
                  );
                })}
              </div>
              {/* checked/remaining summary */}
              {(data.todos||[]).filter(t=>t?.text).length > 0 && (
                <div style={{ fontSize:'11px',color:'#bbb',marginTop:'6px',textAlign:'right' }}>
                  {(data.todos||[]).filter(t=>t?.done).length}/{(data.todos||[]).filter(t=>t?.text).length} done
                </div>
              )}
            </STSection>
            <STSection title="Notes">
              <textarea value={data.notes} onChange={e => upd('notes',e.target.value)}
                style={{ width:'100%',minHeight:'120px',border:'1px solid #e8e8e8',borderRadius:'3px',padding:'6px',fontSize:'12px',fontFamily:'inherit',resize:'vertical',outline:'none',boxSizing:'border-box',color:'#333' }} />
            </STSection>
          </div>
        </div>
      )}

      {tab === 'goals' && (
        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:'24px' }}>
          <div>
            <STSection title="This Month I Want To">
              <STLineList items={data.monthWants||[]} count={6} onChange={v => upd('monthWants',v)} placeholder="Achieve, experience, feel..." />
            </STSection>
            <STSection title="Short Term Goals (1 Year)">
              <STLineList items={data.shortGoals||[]} count={5} onChange={v => upd('shortGoals',v)} placeholder="Goal..." />
            </STSection>
            <STSection title="Medium Term (2-5 Years)">
              <STLineList items={data.medGoals||[]} count={4} onChange={v => upd('medGoals',v)} placeholder="Goal..." />
            </STSection>
            <STSection title="Long Term (5+ Years)">
              <STLineList items={data.longGoals||[]} count={4} onChange={v => upd('longGoals',v)} placeholder="Goal..." />
            </STSection>
          </div>
          <div>
            <STSection title="Savings Goal This Month">
              <div style={{ display:'flex', gap:'12px', marginBottom:'12px' }}>
                {['Target','Saved','Remaining'].map(label => (
                  <div key={label} style={{ flex:1 }}>
                    <div style={{ fontSize:'10px', color:'#888', letterSpacing:'1px', marginBottom:'4px' }}>{label.toUpperCase()}</div>
                    <input value={data[`saving_${label}`]||''} onChange={e => upd(`saving_${label}`,e.target.value)}
                      placeholder="$0" style={{ width:'100%',border:'1px solid #e0e0e0',borderRadius:'3px',padding:'5px',fontSize:'13px',fontFamily:'inherit',outline:'none',boxSizing:'border-box',color:'#111' }} />
                  </div>
                ))}
              </div>
            </STSection>
            <STSection title="Monthly To-Do List">
              <STCheckList items={data.monthTodos} count={12} placeholder="Task..." onToggle={(i,v) => { const t=[...(data.monthTodos||[])]; if(!t[i]) t[i]={text:'',done:false}; t[i]={...t[i],done:v}; upd('monthTodos',t); }} onEdit={(i,v) => { const t=[...(data.monthTodos||[])]; if(!t[i]) t[i]={text:'',done:false}; t[i]={...t[i],text:v}; upd('monthTodos',t); }} />
            </STSection>
          </div>
        </div>
      )}

      {tab === 'reflection' && (
        <div style={{ maxWidth:'600px' }}>
          <div style={{ fontSize:'13px', color:'#888', marginBottom:'20px', fontStyle:'italic' }}>
            A space to pause, reflect, and care for your home and daily life.
          </div>
          {[
            { key:'calm', label:'What feels calm and is working well in my home right now?' },
            { key:'beauty', label:'What areas would I like to bring more ease or beauty to this month?' },
            { key:'routines', label:'Are there any routines or life events I want to prepare for this month?' },
            { key:'shift', label:'One simple shift I will make this month to refresh my space or routine is...' }
          ].map(q => (
            <STSection key={q.key} title={q.label}>
              <textarea value={data.reflection[q.key]||''} onChange={e => upd('reflection',{...data.reflection,[q.key]:e.target.value})}
                style={{ width:'100%',minHeight:'80px',border:'1px solid #e8e8e8',borderRadius:'3px',padding:'8px',fontSize:'13px',fontFamily:'inherit',resize:'vertical',outline:'none',boxSizing:'border-box',color:'#333',lineHeight:'1.6' }} />
            </STSection>
          ))}
        </div>
      )}

      {tab === 'reset' && (
        <div>
          <div style={{ fontSize:'13px', color:'#888', marginBottom:'16px', fontStyle:'italic' }}>Monthly habits for living beautifully at home.</div>
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:'20px' }}>
            {homeResetSections.map(({ key: sKey, label, placeholder }) => {
              const hr = data.homeReset || {};
              const items = Array.isArray(hr[sKey]) ? hr[sKey] : [];
              const list = items.length ? items : [{text:'',done:false},{text:'',done:false},{text:'',done:false},{text:'',done:false},{text:'',done:false}];
              return (
                <STSection key={sKey} title={label}>
                  {list.map((item, i) => {
                    const it = (item && typeof item === 'object') ? item : { text: item||'', done: false };
                    return (
                      <div key={i} style={{ display:'flex', alignItems:'center', gap:'8px', marginBottom:'6px' }}>
                        <div onClick={() => {
                          const hr = { ...data.homeReset };
                          const arr = [...list];
                          arr[i] = { ...it, done: !it.done };
                          hr[sKey] = arr;
                          upd('homeReset', hr);
                        }} style={{ width:'16px',height:'16px',border:'2px solid',borderRadius:'3px',flexShrink:0,cursor:'pointer',
                          borderColor:it.done?'#111':'#ccc',background:it.done?'#111':'transparent',display:'flex',alignItems:'center',justifyContent:'center' }}>
                          {it.done && <span style={{color:'#fff',fontSize:'10px'}}>✓</span>}
                        </div>
                        <input value={it.text||''} onChange={e => {
                          const hr = { ...data.homeReset };
                          const arr = [...list];
                          arr[i] = { ...it, text: e.target.value };
                          hr[sKey] = arr;
                          upd('homeReset', hr);
                        }} placeholder={i<2 ? placeholder : 'Add item...'}
                          style={{ flex:1,border:'none',borderBottom:'1px solid #eee',outline:'none',fontSize:'13px',
                            color:it.done?'#bbb':'#333',textDecoration:it.done?'line-through':'none',
                            background:'transparent',fontFamily:'inherit',padding:'3px 0' }} />
                        <button onClick={() => {
                          const hr = { ...data.homeReset };
                          hr[sKey] = list.filter((_,j)=>j!==i);
                          upd('homeReset', hr);
                        }} style={{ background:'none',border:'none',color:'#e0e0e0',cursor:'pointer',fontSize:'14px',padding:'0' }}>×</button>
                      </div>
                    );
                  })}
                  <button onClick={() => {
                    const hr = { ...data.homeReset };
                    hr[sKey] = [...list, {text:'',done:false}];
                    upd('homeReset', hr);
                  }} style={{ marginTop:'6px',background:'none',border:'1px dashed #ddd',borderRadius:'3px',padding:'4px 10px',fontSize:'11px',color:'#bbb',cursor:'pointer',fontFamily:'inherit' }}>
                    + Add
                  </button>
                </STSection>
              );
            })}
          </div>
        </div>
      )}
    </div>
  );
}

window.MonthlyPlanner = MonthlyPlanner;
