// screens-account.jsx — Chat, Community, Mood Journal, Shortlist

// ===========================================================
//  CHAT (user <> psychologist messaging)
// ===========================================================
function ChatScreen({ activeId, setActiveId, authUser }) {
  const { t, lang } = useLang();
  const el = lang === 'el';

  const isPsy = authUser && (authUser.role === 'pro' || authUser.role === 'admin');
  const myUserId = authUser?.id;

  const [conversations, setConversations] = useState([]);
  const [activeConv,    setActiveConv]    = useState(null);
  const [messages,      setMessages]      = useState([]);
  const [text,          setText]          = useState('');
  const [sending,       setSending]       = useState(false);
  const [loadingList,   setLoadingList]   = useState(true);
  const [loadingThread, setLoadingThread] = useState(false);
  const bodyRef = useRef(null);
  const pollRef = useRef(null);
  const convRef = useRef(null);

  async function loadConversations() {
    try {
      const data = await API.getConversations();
      if (Array.isArray(data)) setConversations(data);
      return data;
    } catch { return []; }
  }

  useEffect(() => {
    loadConversations().finally(() => setLoadingList(false));
  }, []);

  async function loadThread(conv) {
    if (!conv) return;
    try {
      const clientId = isPsy ? conv.client_user_id : undefined;
      const msgs = await API.getThread(conv.psy_id, clientId);
      if (Array.isArray(msgs)) {
        setMessages(msgs);
        setTimeout(() => {
          if (bodyRef.current) bodyRef.current.scrollTop = bodyRef.current.scrollHeight;
        }, 40);
      }
      API.markRead(conv.psy_id, isPsy ? conv.client_user_id : undefined).catch(() => {});
    } catch {}
  }

  function openConv(conv) {
    setActiveConv(conv);
    convRef.current = conv;
    setMessages([]);
    setLoadingThread(true);
    loadThread(conv).finally(() => setLoadingThread(false));
    if (pollRef.current) clearInterval(pollRef.current);
    pollRef.current = setInterval(() => {
      if (convRef.current) loadThread(convRef.current);
    }, 10000);
  }

  useEffect(() => { convRef.current = activeConv; }, [activeConv]);
  useEffect(() => () => { if (pollRef.current) clearInterval(pollRef.current); }, []);

  useEffect(() => {
    if (!activeId || loadingList) return;
    const existing = conversations.find(c => c.psy_id === activeId);
    if (existing) { openConv(existing); return; }
    API.getPsychologist(activeId).then(psy => {
      if (psy && psy.id) {
        const stub = { psy_id: psy.id, psy_name: psy.name, psy_initials: psy.initials || '', last_body: '', unread_count: 0 };
        setConversations(prev => prev.find(c => c.psy_id === psy.id) ? prev : [stub, ...prev]);
        openConv(stub);
      }
    }).catch(() => {});
  }, [activeId, loadingList]);

  async function send() {
    if (!text.trim() || !activeConv || sending) return;
    setSending(true);
    try {
      const clientId = isPsy ? activeConv.client_user_id : undefined;
      await API.sendMessage(activeConv.psy_id, text.trim(), clientId);
      setText('');
      await loadThread(activeConv);
      loadConversations();
    } catch (e) { console.error('[send msg]', e.message); }
    finally { setSending(false); }
  }

  function onKeyDown(e) {
    if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); }
  }

  function fmtTime(ts) {
    if (!ts) return '';
    const d = new Date(ts);
    const now = new Date();
    const isToday = d.toDateString() === now.toDateString();
    return isToday
      ? d.toLocaleTimeString(el ? 'el-GR' : 'en-GB', { hour: '2-digit', minute: '2-digit' })
      : d.toLocaleDateString(el ? 'el-GR' : 'en-GB', { day: 'numeric', month: 'short' });
  }

  function convName(c)     { return isPsy ? c.client_name : c.psy_name; }
  function convInitials(c) { const n = convName(c) || ''; return n.split(' ').map(w => w[0]).slice(0, 2).join('').toUpperCase() || '?'; }
  function convKey(c)      { return isPsy ? c.client_user_id : c.psy_id; }

  return (
    <div className="page wide">
      <div style={{ marginBottom: 16 }}>
        <span className="eyebrow muted">{t('msg_title')}</span>
        <h1 className="display" style={{ fontSize: 32, marginTop: 6 }}>{t('msg_title')}</h1>
      </div>

      <div className="chat">
        {/* Conversation list */}
        <aside className="chat-list">
          <div className="chat-list-head"><h3>{t('msg_inbox')}</h3></div>
          {loadingList ? (
            <div style={{ padding: '40px 20px', textAlign: 'center', color: 'var(--fg3)' }}>
              <Icon name="pending" style={{ fontSize: 28 }} />
            </div>
          ) : conversations.length === 0 ? (
            <div style={{ padding: '40px 20px', textAlign: 'center' }}>
              <Icon name="forum" style={{ fontSize: 32, color: 'var(--fg3)', display: 'block', margin: '0 auto 10px' }} />
              <div style={{ fontSize: 13, color: 'var(--fg3)', lineHeight: 1.55 }}>{t('msg_no_convs')}</div>
            </div>
          ) : (
            <div className="chat-list-items">
              {conversations.map(c => {
                const isActive = activeConv && activeConv.psy_id === c.psy_id && (!isPsy || activeConv.client_user_id === c.client_user_id);
                return (
                  <div key={convKey(c)} className={'chat-item ' + (isActive ? 'active' : '')} onClick={() => openConv(c)}>
                    <div className="avatar-sm" style={{ background: avatarBg(convKey(c)) }}>{convInitials(c)}</div>
                    <div style={{ minWidth: 0 }}>
                      <div className="who">{convName(c)}</div>
                      <div className="preview">{c.last_body || '—'}</div>
                    </div>
                    <div style={{ textAlign: 'right', flexShrink: 0 }}>
                      <div className="time">{fmtTime(c.last_at)}</div>
                      {c.unread_count > 0 && <div className="badge">{c.unread_count}</div>}
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </aside>

        {/* Thread */}
        {activeConv ? (
          <main className="chat-main">
            <div className="chat-head">
              <div className="avatar-sm" style={{ background: avatarBg(convKey(activeConv)) }}>{convInitials(activeConv)}</div>
              <div>
                <div className="who">{convName(activeConv)}</div>
              </div>
              <span style={{ marginLeft: 'auto', fontSize: 11, color: 'var(--fg3)', display: 'flex', alignItems: 'center', gap: 4 }}>
                <Icon name="lock" style={{ fontSize: 13 }} />{el ? 'Κρυπτογραφημένο' : 'Encrypted'}
              </span>
            </div>

            <div className="chat-body" ref={bodyRef}>
              {loadingThread ? (
                <div style={{ display: 'grid', placeItems: 'center', flex: 1, color: 'var(--fg3)' }}>
                  <Icon name="pending" style={{ fontSize: 28 }} />
                </div>
              ) : messages.length === 0 ? (
                <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', flex: 1, gap: 10, color: 'var(--fg3)' }}>
                  <Icon name="chat_bubble_outline" style={{ fontSize: 32 }} />
                  <span style={{ fontSize: 13 }}>{el ? 'Ξεκινήστε τη συνομιλία' : 'Start the conversation'}</span>
                </div>
              ) : messages.map((m, idx) => {
                const isMe = m.sender_user_id === myUserId;
                const showDay = idx === 0 || new Date(m.created_at).toDateString() !== new Date(messages[idx - 1].created_at).toDateString();
                return (
                  <React.Fragment key={m.id}>
                    {showDay && (
                      <div className="chat-day">
                        {new Date(m.created_at).toLocaleDateString(el ? 'el-GR' : 'en-GB', { weekday: 'short', day: 'numeric', month: 'short' })}
                      </div>
                    )}
                    <div className={'msg ' + (isMe ? 'me' : 'them')}>
                      {m.body}
                      <div className="when">{fmtTime(m.created_at)}</div>
                    </div>
                  </React.Fragment>
                );
              })}
            </div>

            <div className="chat-foot">
              <input className="input" placeholder={t('msg_placeholder')}
                value={text} onChange={e => setText(e.target.value)} onKeyDown={onKeyDown} style={{ flex: 1 }} />
              <button className="send-btn" disabled={!text.trim() || sending} onClick={send}>
                <Icon name="send" />
              </button>
            </div>
          </main>
        ) : (
          <main className="chat-main" style={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <div style={{ textAlign: 'center', maxWidth: 320 }}>
              <div style={{ width: 64, height: 64, borderRadius: 20, background: 'var(--psy-accent-soft)', display: 'grid', placeItems: 'center', margin: '0 auto 20px' }}>
                <Icon name="chat_bubble_outline" style={{ fontSize: 32, color: 'var(--psy-accent)' }} />
              </div>
              <h2 className="display" style={{ fontSize: 20, fontWeight: 600, marginBottom: 8 }}>{t('msg_empty_h')}</h2>
              <p style={{ color: 'var(--fg2)', fontSize: 13, lineHeight: 1.6 }}>{t('msg_empty_p')}</p>
            </div>
          </main>
        )}
      </div>
    </div>
  );
}

// ===========================================================
//  COMMUNITY
// ===========================================================
function CommunityScreen({ setRoute, authUser, requireAuth, setToast }) {
  const [tab, setTab] = useState('all');
  const [composing, setComposing] = useState(false);
  const [posts, setPosts] = useState(COMMUNITY_POSTS);
  const [postTitle, setPostTitle] = useState('');
  const [postBody, setPostBody] = useState('');
  const [submitting, setSubmitting] = useState(false);

  useEffect(() => {
    API.getCommunity().then(setPosts).catch(() => {});
  }, []);

  async function submitPost() {
    if (!postTitle.trim() || !postBody.trim()) return;
    setSubmitting(true);
    try {
      await API.postCommunity({ title: postTitle, excerpt: postBody });
      const fresh = await API.getCommunity();
      setPosts(fresh);
      setComposing(false);
      setPostTitle(''); setPostBody('');
      setToast && setToast('Question posted anonymously.');
    } catch (e) {
      setToast && setToast(e.message);
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <div className="page">
      <div style={{ display: 'flex', alignItems: 'end', justifyContent: 'space-between', marginBottom: 22 }}>
        <div>
          <span className="eyebrow muted">Community</span>
          <h1 className="display" style={{ fontSize: 38, marginTop: 8 }}>Talk to people figuring it out too.</h1>
          <p style={{ color: 'var(--fg2)', marginTop: 8, maxWidth: 580, fontSize: 15, lineHeight: 1.55 }}>
            Anonymous Q&amp;A and discussion. Verified psychologists drop in to answer when they have time — marked with a green badge.
          </p>
        </div>
        <button className="btn accent" onClick={() => requireAuth ? requireAuth(() => setComposing(true)) : setComposing(true)}>
          <Icon name="edit" className="sm" /> Ask a question
        </button>
      </div>

      <div className="community-layout">
        <main>
          <div className="tabs" style={{ marginTop: 0 }}>
            <button className={`tab ${tab === 'all' ? 'active' : ''}`} onClick={() => setTab('all')}>All</button>
            <button className={`tab ${tab === 'expert' ? 'active' : ''}`} onClick={() => setTab('expert')}>Answered by a pro</button>
            <button className={`tab ${tab === 'first' ? 'active' : ''}`} onClick={() => setTab('first')}>First-timers</button>
            <button className={`tab ${tab === 'gesy' ? 'active' : ''}`} onClick={() => setTab('gesy')}>GeSY &amp; practical</button>
          </div>

          {composing && (
            <div className="card" style={{ padding: 22, marginBottom: 16, background: 'white' }}>
              <strong style={{ fontSize: 14 }}>Ask anonymously</strong>
              <input className="input" placeholder="Your question…" value={postTitle} onChange={e => setPostTitle(e.target.value)} style={{ marginTop: 10 }} />
              <textarea className="textarea" placeholder="More context (optional)" value={postBody} onChange={e => setPostBody(e.target.value)} style={{ marginTop: 8 }} />
              <div style={{ display: 'flex', gap: 10, marginTop: 16, justifyContent: 'flex-end' }}>
                <button className="btn ghost" onClick={() => { setComposing(false); setPostTitle(''); setPostBody(''); }}>Cancel</button>
                <button className="btn primary" disabled={!postTitle.trim() || submitting} onClick={submitPost}>
                  {submitting ? 'Posting…' : 'Post anonymously'}
                </button>
              </div>
            </div>
          )}

          {posts
            .filter(p => {
              if (tab === 'expert') return !!p.expertReply;
              if (tab === 'first') return p.tags.includes('first-time');
              if (tab === 'gesy') return p.tags.includes('gesy');
              return true;
            })
            .map(p => <PostCard key={p.id} post={p} />)}
        </main>

        <aside style={{ position: 'sticky', top: 88, alignSelf: 'start' }}>
          <div className="card" style={{ padding: 20 }}>
            <strong style={{ fontSize: 14 }}>Community guidelines</strong>
            <ul style={{ margin: '12px 0 0 18px', padding: 0, color: 'var(--fg2)', fontSize: 13, lineHeight: 1.7 }}>
              <li>Anonymity is default. Don't out anyone.</li>
              <li>No medical advice — only experience.</li>
              <li>If you're in crisis, call 1410. We don't want this place to be that place.</li>
              <li>Psychologists answering here aren't your psychologist. They're strangers being generous.</li>
            </ul>
          </div>

          <div className="card" style={{ padding: 20, marginTop: 16 }}>
            <strong style={{ fontSize: 14 }}>Active contributors</strong>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginTop: 12 }}>
              {PSYS.slice(0, 3).map(p => (
                <div key={p.id} style={{ display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer' }} onClick={() => setRoute('detail', p.id)}>
                  <div className="avatar-sm" style={{ background: avatarBg(p.avatarVariant) }}>{p.initials}</div>
                  <div style={{ minWidth: 0 }}>
                    <div style={{ fontSize: 13, fontWeight: 600 }}>{p.name}</div>
                    <div style={{ fontSize: 11, color: 'var(--fg2)' }}>{Math.round(p.reviewCount * 0.4)} answers</div>
                  </div>
                  <VerifiedBadge>Pro</VerifiedBadge>
                </div>
              ))}
            </div>
          </div>

          <div className="card" style={{ padding: 20, marginTop: 16, background: 'var(--psy-ink)', color: 'white', borderColor: 'transparent' }}>
            <Icon name="health_and_safety" style={{ color: 'color-mix(in oklab, var(--psy-accent) 50%, white)' }} />
            <strong style={{ fontSize: 14, display: 'block', marginTop: 8 }}>This is not crisis support.</strong>
            <p style={{ fontSize: 12.5, marginTop: 6, lineHeight: 1.5, color: 'rgba(255,255,255,0.75)' }}>
              If you need someone right now, call the Cyprus Mental Health Helpline at <strong style={{ color: 'white' }}>1410</strong>. It's free and 24/7.
            </p>
          </div>
        </aside>
      </div>
    </div>
  );
}

function PostCard({ post }) {
  return (
    <div className={`post-card ${post.expertReply ? 'expert' : ''}`}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
        <div className="avatar-sm" style={{ background: 'var(--psy-rule)', color: 'var(--fg2)', fontSize: 11 }}>
          {post.author.slice(0, 2).toUpperCase()}
        </div>
        <div>
          <div style={{ fontSize: 12, color: 'var(--fg2)' }}>{post.author} · {post.when}</div>
        </div>
        <div style={{ marginLeft: 'auto', display: 'flex', gap: 6 }}>
          {post.tags.map(t => <span key={t} className="tag" style={{ fontSize: 11 }}>{t}</span>)}
        </div>
      </div>
      <h3 style={{ marginTop: 12 }}>{post.title}</h3>
      <p className="excerpt">{post.excerpt}</p>
      {post.expertReply && (
        <div className="answer-from-pro">
          <div className="who">
            <span>{post.expertReply.who}</span>
            <VerifiedBadge>Verified psychologist</VerifiedBadge>
          </div>
          <p>{post.expertReply.body}</p>
        </div>
      )}
      <div className="foot">
        <span><Icon name="favorite_border" /> {post.likes}</span>
        <span><Icon name="forum" /> {post.replies} replies</span>
        <span style={{ marginLeft: 'auto', color: 'var(--psy-ink)', fontWeight: 600, cursor: 'pointer' }}>Read thread →</span>
      </div>
    </div>
  );
}

// ===========================================================
//  MOOD JOURNAL
// ===========================================================
function JournalScreen({ authUser, requireAuth }) {
  const { t, lang } = useLang();
  const [moodIndex, setMoodIndex] = useState(null); // 0-4
  const [note, setNote] = useState('');
  const [sharedWith, setSharedWith] = useState('none');
  const [saving, setSaving] = useState(false);
  const [saved, setSavedState] = useState(false);
  const [entries, setEntries] = useState([]);        // past entries from API
  const [confirmedPsy, setConfirmedPsy] = useState(null); // psychologist from confirmed booking

  const MOOD_VALUES = [0.1, 0.3, 0.5, 0.75, 0.95];
  const labels = [t('journal_mood_1'), t('journal_mood_2'), t('journal_mood_3'), t('journal_mood_4'), t('journal_mood_5')];
  const dateLocale = lang === 'el' ? 'el-GR' : 'en-GB';

  function getToken() {
    try { return JSON.parse(localStorage.getItem('psyche-auth') || '{}').token; } catch { return null; }
  }
  function authHdrs() {
    return { 'Content-Type': 'application/json', Authorization: 'Bearer ' + getToken() };
  }

  // Load past entries + detect psychologist from confirmed booking
  useEffect(function() {
    if (!authUser) return;

    fetch('/api/journal', { headers: authHdrs() })
      .then(function(r) { return r.json(); })
      .then(function(data) {
        if (Array.isArray(data)) {
          setEntries(data);
          // Pre-fill today's entry if it exists
          const today = new Date().toISOString().slice(0, 10);
          const todayEntry = data.find(function(e) { return e.date === today; });
          if (todayEntry) {
            setMoodIndex(todayEntry.mood);
            setNote(todayEntry.note || '');
            setSharedWith(todayEntry.shared_with_psy_id || 'none');
          }
        }
      })
      .catch(function() {});

    // Find confirmed psychologist from bookings
    fetch('/api/bookings/mine', { headers: authHdrs() })
      .then(function(r) { return r.json(); })
      .then(function(data) {
        if (Array.isArray(data)) {
          const confirmed = data.find(function(b) { return b.status === 'confirmed'; });
          if (confirmed) {
            setConfirmedPsy({ id: confirmed.psy_id, name: confirmed.psy_name });
            setSharedWith(function(cur) { return cur === 'none' ? confirmed.psy_id : cur; });
          }
        }
      })
      .catch(function() {});
  }, [authUser]);

  async function saveEntry() {
    if (!requireAuth()) return;
    if (moodIndex === null) return;
    setSaving(true);
    try {
      await fetch('/api/journal', {
        method: 'POST',
        headers: authHdrs(),
        body: JSON.stringify({
          mood: moodIndex,
          note: note.trim(),
          shared_with_psy_id: sharedWith !== 'none' ? sharedWith : null,
        }),
      });
      setSavedState(true);
      setTimeout(function() { setSavedState(false); }, 2500);
      // Refresh entries
      const fresh = await fetch('/api/journal', { headers: authHdrs() }).then(function(r) { return r.json(); });
      if (Array.isArray(fresh)) setEntries(fresh);
    } catch (e) {}
    setSaving(false);
  }

  // Build last-7-days chart from real entries
  const last7 = [];
  for (let i = 6; i >= 0; i--) {
    const d = new Date();
    d.setDate(d.getDate() - i);
    const dateStr = d.toISOString().slice(0, 10);
    const dayLabel = d.toLocaleDateString(dateLocale, { weekday: 'short' });
    const entry = entries.find(function(e) { return e.date === dateStr; });
    last7.push({ day: dayLabel, date: dateStr, value: entry ? MOOD_VALUES[entry.mood] : null, note: entry ? entry.note : '', mood: entry ? entry.mood : null });
  }
  const filledDays = last7.filter(function(d) { return d.value !== null; });
  const avg = filledDays.length > 0
    ? Math.round(filledDays.reduce(function(s, d) { return s + d.value; }, 0) / filledDays.length * 100) / 100
    : null;

  return (
    <div className="page narrow">
      <div style={{ marginBottom: 22 }}>
        <span className="eyebrow muted">{t('journal_eyebrow')}</span>
        <h1 className="display" style={{ fontSize: 36, marginTop: 8 }}>{t('journal_h1')}</h1>
        <p style={{ color: 'var(--fg2)', marginTop: 8, fontSize: 15, lineHeight: 1.55 }}>
          {t('journal_sub')}
        </p>
      </div>

      <div className="card" style={{ padding: 28 }}>
        <div className="field-label">{t('journal_today_label')} {new Date().toLocaleDateString(dateLocale, { weekday: 'long', day: 'numeric', month: 'long' })}</div>
        <div className="mood-grid">
          {MOOD_VALUES.map(function(v, i) {
            return (
              <button key={i} className={'mood-btn ' + (moodIndex === i ? 'selected' : '')} onClick={function() { setMoodIndex(i); setSavedState(false); }}>
                <div className="face"><MoodFace value={v} /></div>
                <div className="label">{labels[i]}</div>
              </button>
            );
          })}
        </div>

        <div className="field-label" style={{ marginTop: 22 }}>
          {t('journal_mind')} <span style={{ color: 'var(--fg3)', fontWeight: 400 }}>{t('journal_optional')}</span>
        </div>
        <textarea className="textarea"
          value={note}
          onChange={function(e) { setNote(e.target.value); setSavedState(false); }}
          placeholder={lang === 'el' ? 'π.χ. Κοιμήθηκα άσχημα. Ένταση το πρωί. Ένιωσα καλύτερα μετά τη βόλτα.' : 'e.g. Slept badly. Tense morning. Felt better after a walk.'} />

        {/* Share row — only shown when user has a confirmed psychologist */}
        {confirmedPsy && (
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginTop: 16, padding: 14, background: 'var(--psy-surface)', borderRadius: 12 }}>
            <Icon name="visibility" style={{ color: 'var(--fg2)' }} />
            <div style={{ fontSize: 13, flex: 1 }}>
              <div style={{ fontWeight: 600 }}>{t('journal_share_q')}</div>
              <div style={{ color: 'var(--fg2)', marginTop: 2 }}>{t('journal_share_sub')}</div>
            </div>
            <select className="select" style={{ width: 220, padding: '8px 10px' }}
              value={sharedWith}
              onChange={function(e) { setSharedWith(e.target.value); }}>
              <option value="none">{t('journal_keep_priv')}</option>
              <option value={confirmedPsy.id}>{lang === 'el' ? 'Κοινοποίηση με ' : 'Share with '}{confirmedPsy.name}</option>
            </select>
          </div>
        )}

        <div style={{ display: 'flex', justifyContent: 'flex-end', alignItems: 'center', gap: 12, marginTop: 18 }}>
          {saved && (
            <span style={{ fontSize: 13, color: 'var(--psy-leaf)', display: 'flex', alignItems: 'center', gap: 6 }}>
              <Icon name="check_circle" className="sm" /> {lang === 'el' ? 'Αποθηκεύτηκε' : 'Saved'}
            </span>
          )}
          <button className="btn primary" disabled={moodIndex === null || saving} onClick={saveEntry}>
            <Icon name="check" className="sm" /> {saving ? (lang === 'el' ? 'Αποθήκευση…' : 'Saving…') : t('journal_save_entry')}
          </button>
        </div>
      </div>

      {/* Past 7 days */}
      <div className="card" style={{ padding: 28, marginTop: 24 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 16 }}>
          <h3 className="display" style={{ fontSize: 22, fontWeight: 600 }}>{t('journal_this_week')}</h3>
          {avg !== null && (
            <span style={{ fontSize: 13, color: 'var(--fg2)' }}>
              {lang === 'el' ? 'Μ.Ο.' : 'Avg'}: {avg} · {filledDays.length} {lang === 'el' ? 'καταχωρήσεις' : 'entries'}
            </span>
          )}
        </div>

        {filledDays.length === 0 ? (
          <div style={{ padding: '28px 0', textAlign: 'center', color: 'var(--fg3)', fontSize: 14 }}>
            <Icon name="edit_note" style={{ fontSize: 32, display: 'block', margin: '0 auto 10px' }} />
            {lang === 'el' ? 'Δεν υπάρχουν καταχωρήσεις ακόμα. Αποθηκεύστε τη διάθεσή σας παραπάνω.' : 'No entries yet. Save your mood above to start tracking.'}
          </div>
        ) : (
          <>
            <div className="day-chart">
              {last7.map(function(d, i) {
                return (
                  <div key={i}
                    className={'bar ' + (d.value !== null && d.value < 0.4 ? 'low' : '')}
                    style={{ height: d.value !== null ? (d.value * 100) + '%' : '4px', opacity: d.value !== null ? 1 : 0.2 }}
                    title={d.value !== null ? d.day + ': ' + labels[d.mood] : d.day} />
                );
              })}
            </div>
            <div className="day-chart-labels">
              {last7.map(function(d, i) { return <div key={i}>{d.day}</div>; })}
            </div>

            <div style={{ marginTop: 20 }}>
              <h4 style={{ fontSize: 13, fontWeight: 600, color: 'var(--fg2)', textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 12 }}>{t('journal_notes')}</h4>
              {last7.filter(function(d) { return d.note; }).length === 0 ? (
                <div style={{ fontSize: 13, color: 'var(--fg3)' }}>{lang === 'el' ? 'Δεν υπάρχουν σημειώσεις ακόμα.' : 'No notes yet.'}</div>
              ) : (
                last7.filter(function(d) { return d.note; }).map(function(d, i) {
                  return (
                    <div key={i} style={{ display: 'flex', gap: 14, padding: '12px 0', borderTop: i ? '1px solid var(--psy-rule)' : '0' }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 8, minWidth: 90 }}>
                        <MoodFace value={d.value} size={22} />
                        <span style={{ fontSize: 12, fontWeight: 600, color: 'var(--fg2)' }}>{d.day}</span>
                      </div>
                      <div style={{ fontSize: 14, color: 'var(--psy-ink)' }}>{d.note}</div>
                    </div>
                  );
                })
              )}
            </div>
          </>
        )}
      </div>
    </div>
  );
}

// ===========================================================
//  SHORTLIST / COMPARE
// ===========================================================
function ShortlistScreen({ saved, toggleSave, setRoute }) {
  const { t } = useLang();
  const ids = Array.from(saved);

  const [allPsys, setAllPsys] = useState([]);
  useEffect(() => {
    API.getPsychologists().then(d => { if (Array.isArray(d)) setAllPsys(d); }).catch(() => {});
  }, []);

  const items = ids.map(id => allPsys.find(p => String(p.id) === String(id))).filter(Boolean);
  if (ids.length > 0 && allPsys.length === 0) {
    return (
      <div className="page narrow" style={{ display: 'flex', justifyContent: 'center', paddingTop: 80 }}>
        <Icon name="pending" style={{ fontSize: 32, color: 'var(--fg3)' }} />
      </div>
    );
  }
  if (items.length === 0) {
    return (
      <div className="page narrow">
        <div style={{ marginBottom: 22 }}>
          <span className="eyebrow muted">{t('shortlist_eyebrow')}</span>
          <h1 className="display" style={{ fontSize: 36, marginTop: 8 }}>{t('shortlist_h1_empty')}</h1>
        </div>
        <div className="card" style={{ padding: 56, textAlign: 'center' }}>
          <Icon name="bookmark_border" style={{ fontSize: 48, color: 'var(--fg3)' }} />
          <h3 className="display" style={{ fontSize: 22, marginTop: 14, fontWeight: 600 }}>{t('shortlist_empty_h')}</h3>
          <p style={{ color: 'var(--fg2)', marginTop: 8, maxWidth: 380, marginInline: 'auto' }}>
            {t('shortlist_empty_p')}
          </p>
          <button className="btn primary" style={{ marginTop: 20 }} onClick={() => setRoute('directory')}>{t('shortlist_browse')}</button>
        </div>
      </div>
    );
  }

  const display = items.slice(0, 3); // table fits 3
  return (
    <div className="page wide">
      <div style={{ marginBottom: 22 }}>
        <span className="eyebrow muted">{t('shortlist_eyebrow')}</span>
        <h1 className="display" style={{ fontSize: 36, marginTop: 8 }}>{items.length} {items.length === 1 ? t('shortlist_saved_1') : t('shortlist_saved_pl')}</h1>
        {items.length > 3 && <p style={{ color: 'var(--fg2)', marginTop: 6 }}>{t('shortlist_showing')}</p>}
      </div>

      <div className="compare-table">
        <div className="compare-row head">
          <div></div>
          {display.map(p => (
            <div key={p.id}>
              <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
                <Avatar psy={p} />
                <div>
                  <div style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 18, letterSpacing: '-0.015em' }}>{p.name}</div>
                  <div style={{ fontSize: 12, color: 'var(--fg2)' }}>{p.district}</div>
                </div>
              </div>
              <div style={{ display: 'flex', gap: 8, marginTop: 10 }}>
                <button className="btn primary sm" onClick={() => setRoute('detail', p.id)}>{t('shortlist_view')}</button>
                <button className="btn ghost sm" onClick={() => toggleSave(p.id)}><Icon name="close" className="sm" /></button>
              </div>
            </div>
          ))}
        </div>

        {[
          { k: t('shortlist_row_approach'), v: p => APPROACHES.find(a => a.id === p.primaryApproach)?.long },
          { k: t('shortlist_row_spec'), v: p => p.specializations.slice(0, 3).map(s => SPECIALIZATIONS.find(z => z.id === s)?.name).join(', ') },
          { k: t('shortlist_row_rating'), v: p => (<><Stars value={p.rating} /> <strong>{p.rating}</strong> <span style={{ color: 'var(--fg2)' }}>({p.reviewCount})</span></>) },
          { k: t('shortlist_row_exp'), v: p => p.yearsExperience + ' ' + t('shortlist_yr') },
          { k: t('shortlist_row_lang'), v: p => p.languages.join(', ') },
          { k: t('shortlist_row_format'), v: p => p.modes.map(m => m === 'online' ? t('lbl_online') : t('lbl_inperson')).join(' · ') },
          { k: t('shortlist_row_gesy'), v: p => p.gesy ? t('shortlist_gesy_yes') : t('shortlist_gesy_no') },
          { k: t('shortlist_row_price'), v: p => '€' + p.pricePerSession + ' ' + t('shortlist_session') },
          { k: t('shortlist_row_intro'), v: p => p.introCall ? t('shortlist_intro_yes') : '—' },
          { k: t('shortlist_row_next'), v: p => p.nextAvailable },
        ].map((row, i) => (
          <div key={i} className="compare-row">
            <div className="label">{row.k}</div>
            {display.map(p => (
              <div key={p.id} style={{ fontSize: 14 }}>{row.v(p)}</div>
            ))}
          </div>
        ))}
      </div>
    </div>
  );
}

// ===========================================================
//  USER ACCOUNT SETTINGS
// ===========================================================
function UserAccountScreen({ authUser, onSignOut, setRoute }) {
  const { t } = useLang();
  const [confirming, setConfirming] = useState(false);
  const [deleting, setDeleting] = useState(false);

  async function handleDelete() {
    setDeleting(true);
    try {
      const res = await fetch('/api/users/me', { method: 'DELETE', headers: authHeaders() });
      if (res.ok) {
        onSignOut();
      }
    } catch { setDeleting(false); }
  }

  const memberSince = authUser?.created_at
    ? new Date(authUser.created_at).toLocaleDateString('el-GR', { year: 'numeric', month: 'long' })
    : '—';

  return (
    <div className="page" style={{ maxWidth: 600, margin: '0 auto' }}>
      <span className="eyebrow muted">{t('acct_eyebrow')}</span>
      <h1 className="display" style={{ fontSize: 32, marginTop: 6, marginBottom: 32 }}>{t('acct_h1')}</h1>

      <div className="card" style={{ padding: '24px 28px', marginBottom: 16 }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <div>
            <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--fg3)', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: 4 }}>{t('acct_name')}</div>
            <div style={{ fontSize: 16, color: 'var(--psy-ink)' }}>{authUser?.name || '—'}</div>
          </div>
          <div>
            <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--fg3)', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: 4 }}>{t('acct_email')}</div>
            <div style={{ fontSize: 16, color: 'var(--psy-ink)' }}>{authUser?.email || '—'}</div>
          </div>
          <div>
            <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--fg3)', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: 4 }}>{t('acct_member_since')}</div>
            <div style={{ fontSize: 16, color: 'var(--psy-ink)' }}>{memberSince}</div>
          </div>
        </div>
      </div>

    </div>
  );
}

// ===========================================================
//  USER PROFILE EDIT
// ===========================================================
function UserProfileScreen({ authUser, setRoute, setToast, onProfileUpdate, onAvatarChange }) {
  const { t } = useLang();
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [saved, setSavedState] = useState(false);
  const [snapshot, setSnapshot] = useState(null); // last-saved state

  const [name, setName] = useState('');
  const [phone, setPhone] = useState('');
  const [dob, setDob] = useState('');
  const [gender, setGender] = useState('');
  const [gesyNumber, setGesyNumber] = useState('');
  const [emergency, setEmergency] = useState([]);
  const [shareEmergency, setShareEmergency] = useState(false);
  const [avatarData, setAvatarData] = useState(null);

  const email = authUser?.email || '';

  useEffect(() => {
    fetch('/api/users/profile', { headers: { Authorization: 'Bearer ' + (JSON.parse(localStorage.getItem('psyche-auth') || '{}').token || '') } })
      .then(r => r.json())
      .then(d => {
        const snap = {
          name: d.name || authUser?.name || '',
          phone: d.phone || '',
          dob: d.dob ? d.dob.slice(0, 10) : '',
          gender: d.gender || '',
          gesyNumber: d.gesy_number || '',
          emergency: Array.isArray(d.emergency_contacts) ? d.emergency_contacts : [],
          shareEmergency: d.share_emergency || false,
          avatarData: d.avatar_data || null,
        };
        setName(snap.name); setPhone(snap.phone); setDob(snap.dob);
        setGender(snap.gender); setGesyNumber(snap.gesyNumber);
        setEmergency(snap.emergency); setShareEmergency(snap.shareEmergency);
        setAvatarData(snap.avatarData);
        setSnapshot(snap);
        setLoading(false);
      })
      .catch(() => setLoading(false));
  }, []);

  function addEmergency() { setEmergency(e => [...e, { name: '', phone: '' }]); }
  function removeEmergency(i) { setEmergency(e => e.filter((_, idx) => idx !== i)); }
  function updateEmergency(i, field, val) {
    setEmergency(e => e.map((c, idx) => idx === i ? { ...c, [field]: val } : c));
  }

  function handlePhoto(e) {
    const file = e.target.files[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = ev => {
      setAvatarData(ev.target.result);
      if (onAvatarChange) onAvatarChange(ev.target.result);
    };
    reader.readAsDataURL(file);
  }

  function handleRemovePhoto() {
    setAvatarData(null);
    if (onAvatarChange) onAvatarChange(null);
  }

  async function handleSave() {
    setSaving(true);
    try {
      const token = JSON.parse(localStorage.getItem('psyche-auth') || '{}').token || '';
      const res = await fetch('/api/users/profile', {
        method: 'PUT',
        headers: { Authorization: 'Bearer ' + token, 'Content-Type': 'application/json' },
        body: JSON.stringify({ name, phone, dob, gender, gesy_number: gesyNumber, emergency_contacts: emergency, share_emergency: shareEmergency, avatar_data: avatarData }),
      });
      if (res.ok) {
        const newSnap = { name, phone, dob, gender, gesyNumber, emergency, shareEmergency, avatarData };
        setSnapshot(newSnap);
        setSavedState(true);
        setTimeout(() => setSavedState(false), 2500);
        if (onAvatarChange) onAvatarChange(avatarData);
        if (onProfileUpdate) onProfileUpdate();
      }
    } finally { setSaving(false); }
  }

  const isDirty = !snapshot || (
    name !== snapshot.name ||
    phone !== snapshot.phone ||
    dob !== snapshot.dob ||
    gender !== snapshot.gender ||
    gesyNumber !== snapshot.gesyNumber ||
    shareEmergency !== snapshot.shareEmergency ||
    avatarData !== snapshot.avatarData ||
    JSON.stringify(emergency) !== JSON.stringify(snapshot.emergency)
  );

  const fieldStyle = { width: '100%', padding: '10px 14px', borderRadius: 10, border: '1.5px solid var(--psy-rule)', fontSize: 14, background: 'var(--psy-surface)', color: 'var(--psy-ink)', boxSizing: 'border-box' };
  const labelStyle = { fontSize: 12, fontWeight: 600, color: 'var(--fg2)', letterSpacing: '0.05em', textTransform: 'uppercase', marginBottom: 6, display: 'block' };

  if (loading) return <div className="page" style={{ textAlign: 'center', padding: 60, color: 'var(--fg3)' }}>…</div>;

  return (
    <div className="page" style={{ maxWidth: 640, margin: '0 auto' }}>
      <button className="btn ghost sm" onClick={() => setRoute('home')} style={{ marginBottom: 32 }}>
        ← Back
      </button>
      <span className="eyebrow muted">{t('uprof_eyebrow')}</span>
      <h1 className="display" style={{ fontSize: 32, marginTop: 8, marginBottom: 28 }}>{t('uprof_h1')}</h1>

      {/* Avatar */}
      <div className="card" style={{ padding: '24px 28px', marginBottom: 16 }}>
        <label style={labelStyle}>{t('uprof_photo_h')}</label>
        <div style={{ display: 'flex', alignItems: 'center', gap: 20 }}>
          <div style={{ width: 72, height: 72, borderRadius: '50%', overflow: 'hidden', background: 'var(--psy-surface-2)', border: '2px solid var(--psy-rule)', flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            {avatarData
              ? <img src={avatarData} alt="avatar" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
              : <Icon name="person" style={{ fontSize: 32, color: 'var(--fg3)' }} />}
          </div>
          <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
            <label className="btn ghost sm" style={{ cursor: 'pointer' }}>
              {t('uprof_photo_upload')}
              <input type="file" accept="image/*" style={{ display: 'none' }} onChange={handlePhoto} />
            </label>
            {avatarData && (
              <button className="btn ghost sm" onClick={handleRemovePhoto}>{t('uprof_photo_remove')}</button>
            )}
          </div>
        </div>
      </div>

      {/* Basic info */}
      <div className="card" style={{ padding: '24px 28px', marginBottom: 16 }}>
        <div style={{ display: 'grid', gap: 18 }}>
          <div>
            <label style={labelStyle}>{t('uprof_name')}</label>
            <input style={fieldStyle} value={name} onChange={e => setName(e.target.value)} />
          </div>
          <div>
            <label style={labelStyle}>{t('uprof_email')}</label>
            <input style={{ ...fieldStyle, opacity: 0.6, cursor: 'not-allowed' }} value={email} readOnly />
            <span style={{ fontSize: 11, color: 'var(--fg3)', marginTop: 4, display: 'block' }}>{t('uprof_email_note')}</span>
          </div>
          <div>
            <label style={labelStyle}>{t('uprof_phone')}</label>
            <input style={fieldStyle} value={phone} onChange={e => setPhone(e.target.value)} type="tel" />
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
            <div>
              <label style={labelStyle}>{t('uprof_dob')}</label>
              <input style={fieldStyle} value={dob} onChange={e => setDob(e.target.value)} type="date" />
            </div>
            <div>
              <label style={labelStyle}>{t('uprof_gender')}</label>
              <select style={fieldStyle} value={gender} onChange={e => setGender(e.target.value)}>
                <option value="">—</option>
                <option value="male">{t('uprof_gender_male')}</option>
                <option value="female">{t('uprof_gender_female')}</option>
                <option value="non-binary">{t('uprof_gender_nb')}</option>
                <option value="prefer_not">{t('uprof_gender_pnts')}</option>
              </select>
            </div>
          </div>
          <div>
            <label style={labelStyle}>{t('uprof_gesy')}</label>
            <input style={fieldStyle} value={gesyNumber} onChange={e => setGesyNumber(e.target.value)} placeholder="e.g. 123456" />
            <span style={{ fontSize: 11, color: 'var(--fg3)', marginTop: 4, display: 'block' }}>{t('uprof_gesy_note')}</span>
          </div>
        </div>
      </div>

      {/* Emergency contacts */}
      <div className="card" style={{ padding: '24px 28px', marginBottom: 16 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 4 }}>
          <label style={{ ...labelStyle, marginBottom: 0 }}>{t('uprof_emergency_h')}</label>
          <button className="btn ghost sm" onClick={addEmergency} style={{ fontSize: 12 }}>{t('uprof_emergency_add')}</button>
        </div>
        <p style={{ fontSize: 12, color: 'var(--fg3)', margin: '0 0 16px' }}>{t('uprof_emergency_sub')}</p>

        {emergency.map((c, i) => (
          <div key={i} style={{ display: 'grid', gridTemplateColumns: '1fr 1fr auto', gap: 10, marginBottom: 10, alignItems: 'end' }}>
            <div>
              {i === 0 && <label style={labelStyle}>{t('uprof_emergency_name')}</label>}
              <input style={fieldStyle} value={c.name} onChange={e => updateEmergency(i, 'name', e.target.value)} />
            </div>
            <div>
              {i === 0 && <label style={labelStyle}>{t('uprof_emergency_phone')}</label>}
              <input style={fieldStyle} value={c.phone} onChange={e => updateEmergency(i, 'phone', e.target.value)} type="tel" />
            </div>
            <button onClick={() => removeEmergency(i)} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--fg3)', padding: '10px 8px' }}>
              <Icon name="close" style={{ fontSize: 18 }} />
            </button>
          </div>
        ))}

        <label style={{ display: 'flex', alignItems: 'flex-start', gap: 10, marginTop: emergency.length > 0 ? 16 : 4, cursor: 'pointer', opacity: emergency.length === 0 ? 0.5 : 1 }}>
          <input type="checkbox" checked={shareEmergency} onChange={e => setShareEmergency(e.target.checked)} disabled={emergency.length === 0} style={{ marginTop: 2, flexShrink: 0 }} />
          <div>
            <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--psy-ink)' }}>{t('uprof_share_emergency')}</div>
            <div style={{ fontSize: 12, color: 'var(--fg3)', marginTop: 2 }}>{t('uprof_share_note')}</div>
          </div>
        </label>
      </div>

      <button className="btn accent" onClick={handleSave} disabled={saving || !isDirty} style={{ width: '100%', justifyContent: 'center', opacity: (!isDirty && !saving) ? 0.45 : 1, cursor: (!isDirty && !saving) ? 'default' : 'pointer' }}>
        {saving ? t('uprof_saving') : saved ? t('uprof_saved') : t('uprof_save')}
      </button>
    </div>
  );
}

Object.assign(window, { ChatScreen, CommunityScreen, JournalScreen, ShortlistScreen, PostCard, UserAccountScreen, UserProfileScreen });
