// StarThink — Journal Hub
// Combines: Gratitude Journal, Feelings Journal (both), Boundaries Journal,
// Shadow Work, Letter to Future Self, Couples Journal, Dream Journal

function JournalHub() {
  const today = new Date().toISOString().split('T')[0];
  const [tab, setTab] = React.useState('gratitude');

  // Speech-aware textarea used throughout journal
  const STA = ({ value, onChange, placeholder, rows = 4 }) => (
    <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.8' }} />
      <div style={{ position:'absolute', top:'8px', right:'8px' }}>
        <MicButton onResult={t => onChange((value?value+' ':'')+t)} />
      </div>
    </div>
  );
  const tabs = [
    { id:'gratitude', label:'Gratitude' }, { id:'feelings', label:'Feelings' },
    { id:'dream', label:'Dream' }, { id:'shadow', label:'Shadow Work' },
    { id:'future', label:'Future Self' }, { id:'couples', label:'Couples' },
    { id:'boundaries', label:'Boundaries' }
  ];

  const useJournal = (name) => {
    const key = `journal_${name}_${today}`;
    const [d, setD] = React.useState(() => ST.get(key, {}));
    const upd = (field, val) => { const n = {...d, [field]:val}; setD(n); ST.set(key, n); };
    return [d, upd];
  };

  const [gd, gUpd] = useJournal('gratitude');
  const [fd, fUpd] = useJournal('feelings');
  const [dd, dUpd] = useJournal('dream');
  const [sd, sUpd] = useJournal('shadow');
  const [ftd, ftUpd] = useJournal('future');
  const [cd, cUpd] = useJournal('couples');
  const [bd, bUpd] = useJournal('boundaries');

  const moodList = ['Happy','Content','Relaxed','Average','Motivated','Excited','Bored','Sad','Lonely','Anxious','Angry','Overwhelmed'];
  const selfCare = ['Ate Breakfast','Ate Lunch','Ate Dinner','Took a Nap','Slept 7-9 Hours','Got Fresh Air','Exercised','Meditated'];
  const dreamTypes = ['Lucid','Vivid','Fantasy','Symbolic','Prophetic','Recurring'];
  const moonPhases = ['🌑','🌒','🌓','🌔','🌕','🌖','🌗','🌘'];

  // All journal textareas get mic button
  const TA = ({ value, onChange, placeholder, rows=4 }) => (
    <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:'3px',padding:'8px 36px 8px 8px',fontSize:'13px',fontFamily:'inherit',resize:'vertical',outline:'none',boxSizing:'border-box',color:'#333',lineHeight:'1.8' }} />
      <div style={{ position:'absolute',top:'8px',right:'8px' }}>
        <MicButton onResult={t => onChange((value?value+' ':'')+t)} />
      </div>
    </div>
  );

  return (
    <div className="planner-page">
      <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' }}>Journal Hub</div>
          <div style={{ fontSize:'11px', color:'#888', letterSpacing:'1px', textTransform:'uppercase', marginTop:'2px' }}>StarThink · {today}</div>
        </div>
      </div>

      {/* Tab bar */}
      <div style={{ display:'flex', gap:'2px', marginBottom:'20px', borderBottom:'2px solid #111', overflowX:'auto' }}>
        {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', whiteSpace:'nowrap' }}>
            {t.label}
          </button>
        ))}
      </div>

      {tab === 'gratitude' && (
        <div style={{ maxWidth:'600px' }}>
          <p style={{ fontSize:'13px', fontStyle:'italic', color:'#888', marginBottom:'20px' }}>Gratitude transforms ordinary moments into extraordinary ones.</p>
          {[
            'Things that I am grateful for today:',
            'People in my life that I am grateful for:',
            'A challenge that I am grateful for:',
            'One of my greatest strengths:',
            'An item or food that brings me comfort:',
            'A song or quote that lifts me up:',
            'Something I wished for years ago that I have today:',
            'Something that I am looking forward to:'
          ].map((q, i) => (
            <div key={i} style={{ marginBottom:'16px' }}>
              <div style={{ fontSize:'12px', fontWeight:'600', color:'#555', marginBottom:'6px' }}>{i+1}. {q}</div>
              <TA value={gd[`q${i}`]} onChange={v => gUpd(`q${i}`, v)} placeholder="Write freely..." rows={3} />
            </div>
          ))}
        </div>
      )}

      {tab === 'feelings' && (
        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:'24px' }}>
          <div>
            <STSection title="Today I Feel">
              <div style={{ display:'flex', flexWrap:'wrap', gap:'6px', marginBottom:'12px' }}>
                {moodList.map(mood => (
                  <div key={mood} onClick={() => fUpd('mood', mood)}
                    style={{ padding:'4px 10px', borderRadius:'20px', fontSize:'12px', cursor:'pointer', border:'1.5px solid',
                      borderColor:fd.mood===mood?'#111':'#ddd', background:fd.mood===mood?'#111':'transparent',
                      color:fd.mood===mood?'#fff':'#555', transition:'all 0.15s' }}>
                    {mood}
                  </div>
                ))}
              </div>
              <div style={{ fontSize:'11px', color:'#888', marginBottom:'4px' }}>Because...</div>
              <TA value={fd.because} onChange={v => fUpd('because', v)} placeholder="I feel this way because..." rows={3} />
            </STSection>

            <STSection title="Self-Care Today">
              {selfCare.map(item => (
                <div key={item} onClick={() => { const sc=fd.selfCare||{}; fUpd('selfCare',{...sc,[item]:!sc[item]}); }}
                  style={{ display:'flex', alignItems:'center', gap:'8px', padding:'4px 0', cursor:'pointer' }}>
                  <div style={{ width:'14px',height:'14px',border:'1.5px solid',borderRadius:'2px',flexShrink:0,
                    borderColor:(fd.selfCare||{})[item]?'#111':'#ccc',background:(fd.selfCare||{})[item]?'#111':'transparent',
                    display:'flex',alignItems:'center',justifyContent:'center' }}>
                    {(fd.selfCare||{})[item]&&<span style={{color:'#fff',fontSize:'9px'}}>✓</span>}
                  </div>
                  <span style={{ fontSize:'13px', color:'#444' }}>{item}</span>
                </div>
              ))}
            </STSection>
          </div>

          <div>
            <STSection title="Self-Love">
              <TA value={fd.selfLove} onChange={v => fUpd('selfLove', v)} placeholder="What is one thing I love about myself, or a reason I'm proud of myself today?" rows={4} />
            </STSection>
            <STSection title="Gratitude">
              <TA value={fd.gratitude} onChange={v => fUpd('gratitude', v)} placeholder="What is a moment, person, or thing I'm grateful for today?" rows={4} />
            </STSection>
            <STSection title="On My Mind">
              <TA value={fd.onMind} onChange={v => fUpd('onMind', v)} placeholder="What thoughts and emotions have been stuck on my mind?" rows={4} />
            </STSection>
            <STSection title="My Next Step Will Be To">
              <TA value={fd.nextStep} onChange={v => fUpd('nextStep', v)} placeholder="One action I'll take..." rows={2} />
            </STSection>
            <STSection title="Rate Today">
              <STStars value={fd.rating||0} onChange={v => fUpd('rating',v)} />
            </STSection>
          </div>
        </div>
      )}

      {tab === 'dream' && (
        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:'24px' }}>
          <div>
            <STSection title="My Dream">
              <TA value={dd.dream} onChange={v => dUpd('dream', v)} placeholder="Describe your dream in detail..." rows={6} />
            </STSection>
            <STSection title="Type of Dream">
              <div style={{ display:'flex', flexWrap:'wrap', gap:'6px' }}>
                {dreamTypes.map(t => (
                  <div key={t} onClick={() => { const dt=dd.dreamTypes||{}; dUpd('dreamTypes',{...dt,[t]:!dt[t]}); }}
                    style={{ padding:'4px 10px',borderRadius:'20px',fontSize:'12px',cursor:'pointer',border:'1.5px solid',
                      borderColor:(dd.dreamTypes||{})[t]?'#111':'#ddd',background:(dd.dreamTypes||{})[t]?'#111':'transparent',
                      color:(dd.dreamTypes||{})[t]?'#fff':'#555' }}>
                    {t}
                  </div>
                ))}
              </div>
            </STSection>
            <STSection title="Sleep Quality">
              <div style={{ display:'flex', gap:'8px', alignItems:'center' }}>
                {[1,2,3,4,5,6,7,8,9,10].map(n => (
                  <div key={n} onClick={() => dUpd('sleepQ', n)}
                    style={{ width:'24px',height:'24px',borderRadius:'3px',border:'1.5px solid',cursor:'pointer',display:'flex',alignItems:'center',justifyContent:'center',fontSize:'11px',
                      borderColor:dd.sleepQ>=n?'#111':'#ddd',background:dd.sleepQ>=n?'#111':'transparent',color:dd.sleepQ>=n?'#fff':'#999' }}>
                    {n}
                  </div>
                ))}
              </div>
            </STSection>
            <STSection title="Moon Phase">
              <div style={{ display:'flex', gap:'10px' }}>
                {moonPhases.map((p,i) => (
                  <span key={i} onClick={() => dUpd('moon', i)} style={{ fontSize:'20px', cursor:'pointer', opacity:dd.moon===i?1:0.3 }}>{p}</span>
                ))}
              </div>
            </STSection>
          </div>
          <div>
            <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:'8px', marginBottom:'16px' }}>
              {['Places — Where am I?','People — Who was there?','Symbols — What do I see?'].map((label,i) => (
                <STSection key={i} title={label}>
                  <TA value={dd[`detail${i}`]} onChange={v => dUpd(`detail${i}`, v)} placeholder="..." rows={4} />
                </STSection>
              ))}
            </div>
            <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:'16px' }}>
              <STSection title="How do I feel? (Dreaming)">
                <TA value={dd.feelDream} onChange={v => dUpd('feelDream', v)} placeholder="Emotions in the dream..." rows={4} />
              </STSection>
              <STSection title="How do I feel? (Awake)">
                <TA value={dd.feelAwake} onChange={v => dUpd('feelAwake', v)} placeholder="Emotions now..." rows={4} />
              </STSection>
            </div>
            <STSection title="Interpretation">
              <TA value={dd.interp} onChange={v => dUpd('interp', v)} placeholder="What might this dream mean?" rows={4} />
            </STSection>
          </div>
        </div>
      )}

      {tab === 'shadow' && (
        <div style={{ maxWidth:'620px' }}>
          <div style={{ background:'#f8f8f8', border:'1px solid #e8e8e8', borderRadius:'6px', padding:'14px 16px', marginBottom:'20px' }}>
            <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-start', gap:'12px' }}>
              <p style={{ fontSize:'13px', color:'#555', fontStyle:'italic', margin:0 }}>Shadow work helps integrate unconscious patterns into conscious awareness.</p>
              <details style={{ flexShrink:0 }}>
                <summary style={{ fontSize:'11px', color:'#aaa', cursor:'pointer', userSelect:'none', whiteSpace:'nowrap' }}>What is this? ▾</summary>
                <div style={{ marginTop:'10px', fontSize:'12px', color:'#666', lineHeight:'1.7', maxWidth:'340px' }}>
                  <strong>Shadow work</strong> is a practice from Jungian psychology. The "shadow" is the part of yourself you repress, deny or disown — often because it was judged or rejected in childhood.<br /><br />
                  By <em>exploring</em> these traits rather than hiding them, you reclaim energy, reduce self-sabotage, and develop deeper self-compassion.<br /><br />
                  <strong>How to use this:</strong> Pick one behavior, reaction, or trait that you judge in yourself or others. Follow the prompts honestly — there are no wrong answers.
                </div>
              </details>
            </div>
          </div>
          {[
            ['shadowTrait','Shadow trait:','What behavior or pattern are you exploring?'],
            ['howFeel','How I feel about this behavior:','Be honest about your emotional reaction'],
            ['earliestMemory','Earliest memory related to this behavior:','When did this first appear in your life?'],
            ['affectsToday','How this behavior affects me today:','How does it show up in your current life?'],
            ['recentMemory','A recent memory with this trait:','A recent example of this pattern'],
            ['expressedHow','How do I express this trait?','In what ways does it manifest?'],
            ['rechanneled','How can this behavior be used positively? How can it be rechanneled?','Find the gift in the shadow'],
          ].map(([key, label, hint]) => (
            <div key={key} style={{ marginBottom:'16px' }}>
              <div style={{ fontSize:'13px', fontWeight:'700', color:'#333', marginBottom:'3px' }}>{label}</div>
              <div style={{ fontSize:'11px', color:'#aaa', marginBottom:'5px' }}>{hint}</div>
              <TA value={sd[key]} onChange={v => sUpd(key, v)} placeholder="Write freely..." rows={3} />
            </div>
          ))}
          <STSection title="Actions Moving Forward">
            <STLineList items={sd.actions||[]} count={6} onChange={v => sUpd('actions',v)} placeholder="Action step..." />
          </STSection>
        </div>
      )}

      {tab === 'future' && (
        <div style={{ maxWidth:'560px' }}>
          <p style={{ fontSize:'20px', fontFamily:'Georgia, serif', fontStyle:'italic', color:'#333', marginBottom:'20px', textAlign:'center' }}>Letter to My Future Self</p>
          {[
            ['dear','Dear Future Self,','Speak directly to who you want to become...'],
            ['traveled','When I next read this, I hope to have traveled to...','Places you want to visit'],
            ['experienced','Experienced...','Moments, feelings, milestones'],
            ['accomplished','Accomplished...','Goals, achievements, growth'],
            ['met','Met...','People, communities, connections'],
            ['learned','Learned...','Skills, wisdom, lessons'],
            ['spentTime','Spent time with...','Relationships that matter'],
            ['grown',"The way I've grown most is...",'Your transformation'],
          ].map(([key, label, hint]) => (
            <div key={key} style={{ marginBottom:'16px' }}>
              <div style={{ background:'#f5f5f5', borderRadius:'20px', padding:'6px 14px', fontSize:'12px', fontWeight:'600', color:'#555', marginBottom:'6px', display:'inline-block' }}>{label}</div>
              <TA value={ftd[key]} onChange={v => ftUpd(key, v)} placeholder={hint} rows={3} />
            </div>
          ))}
        </div>
      )}

      {tab === 'couples' && (
        <div style={{ maxWidth:'560px' }}>
          <p style={{ fontSize:'13px', color:'#888', fontStyle:'italic', marginBottom:'20px' }}>Strengthen your relationship through daily reflection together.</p>
          {[
            ["q1","What's one thing your partner did that felt loving?"],
            ["q2","How can we support each other in tough times?"],
            ["q3","What's a dream or goal we want to achieve together?"],
            ["q4","What is one fun memory we created recently?"],
            ["q5","What's one thing I appreciate about us right now?"],
            ["q6","What's one area where I can show up better?"],
          ].map(([key, question], i) => (
            <div key={key} style={{ marginBottom:'16px' }}>
              <div style={{ background:'#fce4ec', borderRadius:'4px 4px 0 0', padding:'8px 12px', fontSize:'13px', fontWeight:'600', color:'#555' }}>
                {i+1}. {question}
              </div>
              <TA value={cd[key]} onChange={v => cUpd(key, v)} placeholder="Your thoughts..." rows={3} />
            </div>
          ))}
          <STSection title="Relationship Goals">
            <STLineList items={cd.goals||[]} count={4} onChange={v => cUpd('goals',v)} placeholder="Goal together..." />
          </STSection>
        </div>
      )}

      {tab === 'boundaries' && (
        <div style={{ maxWidth:'600px' }}>
          <STSection title="My Top Core Values">
            <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:'12px' }}>
              {[0,1,2].map(i => (
                <div key={i}>
                  <div style={{ fontSize:'11px', color:'#888', marginBottom:'4px' }}>Value {i+1}</div>
                  <STLineList items={(bd.values||[])[i]?[...(bd.values[i])]:[]} count={3} onChange={v => { const vals=[...(bd.values||[[],[],[]])]||[[],[],[]]; vals[i]=v; bUpd('values',vals); }} placeholder="..." />
                </div>
              ))}
            </div>
          </STSection>
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:'20px' }}>
            <STSection title="Personal Space">
              <TA value={bd.personalSpace} onChange={v => bUpd('personalSpace',v)} placeholder="My boundaries around personal space..." rows={5} />
            </STSection>
            <STSection title="Emotional Sharing">
              <TA value={bd.emotional} onChange={v => bUpd('emotional',v)} placeholder="What I'm comfortable sharing emotionally..." rows={5} />
            </STSection>
          </div>
          <STSection title="Challenging Situations / Behaviors">
            <TA value={bd.challenging} onChange={v => bUpd('challenging',v)} placeholder="Situations where I struggle to maintain boundaries..." rows={4} />
          </STSection>
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:'20px' }}>
            <STSection title="Boundaries to Set">
              <STLineList items={bd.boundaryList||[]} count={5} onChange={v => bUpd('boundaryList',v)} placeholder="Boundary..." />
            </STSection>
            <STSection title="Phrases to Practice">
              <TA value={bd.phrases} onChange={v => bUpd('phrases',v)} placeholder="Scripts and phrases to use when setting boundaries..." rows={5} />
            </STSection>
          </div>
        </div>
      )}
    </div>
  );
}

window.JournalHub = JournalHub;
