// Anna's Wall — screens: WallScreen (feed) + PostDetailScreen.
// Requires components.jsx, wall-data.jsx, wall-components.jsx loaded first.

const { useState: useStateW, useRef: useRefW, useEffect: useEffectW, useCallback: useCbW } = React;

// ── Recency grouping (brand ALL-CAPS section rhythm) ────────────────────────
function groupByRecency(posts) {
  const now = Date.now();
  const buckets = [
    { key: 'today', label: 'Today', items: [] },
    { key: 'week', label: 'This week', items: [] },
    { key: 'earlier', label: 'Earlier', items: [] },
  ];
  posts.forEach(p => {
    const h = (now - new Date(p.createdAt).getTime()) / 3600000;
    if (h < 24) buckets[0].items.push(p);
    else if (h < 24 * 7) buckets[1].items.push(p);
    else buckets[2].items.push(p);
  });
  return buckets.filter(b => b.items.length);
}

function WallGroupLabel({ children }) {
  return (
    <div style={{
      fontFamily: H.body, fontWeight: 500, fontSize: 12, letterSpacing: 1.4,
      textTransform: 'uppercase', color: H.fg3, padding: '14px 4px 2px',
    }}>{children}</div>
  );
}

// ── Feed header ──────────────────────────────────────────────────────────────
function WallHeader({ unreadCount }) {
  return (
    <div style={{ padding: '8px 20px 14px', background: H.bg }}>
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between' }}>
        <div>
          <div style={{ fontFamily: H.display, fontWeight: 600, fontSize: 30, letterSpacing: -0.6, color: H.fg1, lineHeight: 1.05 }}>Your Wall</div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 6 }}>
            <img src="anna.png" alt="" width="18" height="18" style={{ width: 18, height: 18, borderRadius: 999, objectFit: 'cover' }} />
            <span style={{ fontFamily: H.body, fontSize: 13, color: H.fg2 }}>Curated by Anna · twice a week</span>
          </div>
        </div>
        {unreadCount > 0 && (
          <span style={{
            fontFamily: H.body, fontWeight: 600, fontSize: 12, color: 'var(--brand-orange-vibey)',
            background: 'rgba(255,105,66,0.12)', padding: '5px 11px', borderRadius: 999, whiteSpace: 'nowrap',
          }}>{unreadCount} new</span>
        )}
      </div>
    </div>
  );
}

// ── WallScreen ───────────────────────────────────────────────────────────────
function WallScreen({ onNavigate, store, settings }) {
  const { posts, loading, refreshing, loadingMore, error, hasMore, refresh, loadMore, userReactions } = store;
  const scrollRef = useRefW(null);
  const [pull, setPull] = useStateW(0);          // current pull distance
  const dragRef = useRefW({ active: false, startY: 0 });

  const unreadCount = posts.filter(p => p.readAt === null).length;

  // infinite scroll
  const onScroll = () => {
    const el = scrollRef.current;
    if (!el || loadingMore || !hasMore || loading || error) return;
    const remaining = el.scrollHeight - (el.scrollTop + el.clientHeight);
    if (remaining < el.clientHeight * 0.3) loadMore();
  };

  // pull-to-refresh (pointer based; works for touch + mouse drag)
  const startDrag = (y) => {
    const el = scrollRef.current;
    if (el && el.scrollTop <= 0 && !refreshing) { dragRef.current = { active: true, startY: y }; }
  };
  const moveDrag = (y, e) => {
    if (!dragRef.current.active) return;
    const dist = y - dragRef.current.startY;
    if (dist > 0) {
      if (e && e.cancelable) e.preventDefault();
      setPull(Math.min(90, dist * 0.55));
    } else { setPull(0); }
  };
  const endDrag = () => {
    if (!dragRef.current.active) return;
    dragRef.current.active = false;
    if (pull > 52) refresh();
    setPull(0);
  };

  const ptrThreshold = pull > 52;

  return (
    <div className="screen-enter" style={{ height: '100%', display: 'flex', flexDirection: 'column', background: H.bg }}>
      <WallHeader unreadCount={unreadCount} />
      <div
        ref={scrollRef}
        className="no-scrollbar"
        onScroll={onScroll}
        onTouchStart={(e) => startDrag(e.touches[0].clientY)}
        onTouchMove={(e) => moveDrag(e.touches[0].clientY, e)}
        onTouchEnd={endDrag}
        onMouseDown={(e) => startDrag(e.clientY)}
        onMouseMove={(e) => dragRef.current.active && moveDrag(e.clientY, e)}
        onMouseUp={endDrag}
        onMouseLeave={endDrag}
        style={{ flex: 1, overflowY: 'auto', padding: '0 20px 150px' }}
      >
        {/* pull-to-refresh indicator */}
        {(pull > 0 || refreshing) && (
          <div style={{ height: refreshing ? 44 : pull, display: 'flex', alignItems: 'center', justifyContent: 'center', overflow: 'hidden', transition: dragRef.current.active ? 'none' : 'height 200ms ease' }}>
            <span style={{
              width: 22, height: 22, borderRadius: 999,
              border: '2.5px solid rgba(3,4,13,0.1)', borderTopColor: 'var(--brand-orange-vibey)',
              display: 'inline-block',
              transform: refreshing ? 'none' : `rotate(${pull * 4}deg) scale(${Math.min(1, pull / 52)})`,
              animation: refreshing ? 'wallSpin 0.8s linear infinite' : 'none',
              opacity: ptrThreshold || refreshing ? 1 : 0.5,
            }} />
          </div>
        )}

        {loading ? (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14, paddingTop: 4 }}>
            {[0, 1, 2].map(i => <WallPostCardSkeleton key={i} />)}
          </div>
        ) : error ? (
          <WallErrorState onRetry={refresh} />
        ) : posts.length === 0 ? (
          <WallEmptyState />
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', paddingTop: 0 }}>
            {(() => { let gi = 0; return groupByRecency(posts).map(group => (
              <div key={group.key}>
                <WallGroupLabel>{group.label}</WallGroupLabel>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 14, paddingTop: 8 }}>
                  {group.items.map(post => {
                    const delay = Math.min(gi++, 7) * 45;
                    return (
                      <div key={post.id} className="wall-card-in" style={{ animationDelay: delay + 'ms' }}>
                        <WallPostCard
                          post={post}
                          userReaction={userReactions[post.id]}
                          unreadStyle={settings.unreadStyle}
                          density={settings.density}
                          onOpen={() => onNavigate('post-detail', { postId: post.id })}
                        />
                      </div>
                    );
                  })}
                </div>
              </div>
            )); })()}
            {(loadingMore || !hasMore) && <WallLoadingFooter done={!hasMore} />}
            <div style={{ fontFamily: H.body, fontSize: 10.5, lineHeight: 1.5, color: H.fg3, textAlign: 'center', padding: '14px 24px 0' }}>
              For educational purposes only. Not medical advice. Anna's notes draw on peer-reviewed literature and your own data.
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

// ── Interactive reaction bar (detail) ────────────────────────────────────────
function WallReactionBar({ post, userReaction, onReact }) {
  const [popKey, setPopKey] = useStateW(null);
  const tap = (key) => {
    setPopKey(key);
    setTimeout(() => setPopKey(null), 380);
    onReact(post.id, key);
  };
  return (
    <div style={{ display: 'flex', gap: 8 }}>
      {REACTIONS.map(r => {
        const mine = userReaction === r.key;
        const count = post.reactions[r.key];
        return (
          <button key={r.key} onClick={() => tap(r.key)} aria-pressed={mine} style={{
            flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
            padding: '11px 4px 9px', borderRadius: 16, cursor: 'pointer',
            border: mine ? '1.5px solid var(--brand-orange-vibey)' : '1.5px solid ' + H.border,
            background: mine ? 'rgba(255,105,66,0.08)' : '#fff',
            transition: 'background 140ms, border-color 140ms',
          }}>
            <span className={'wall-rx' + (mine ? ' mine' : '')} style={{
              fontSize: 22, display: 'inline-block', lineHeight: 1,
              animation: popKey === r.key ? 'wallPop 0.38s ease' : 'none',
            }}>{r.emoji}</span>
            <span style={{ fontFamily: H.body, fontWeight: mine ? 600 : 400, fontSize: 13, color: mine ? 'var(--brand-orange-vibey)' : H.fg2 }}>{count}</span>
          </button>
        );
      })}
    </div>
  );
}

// ── Citations ────────────────────────────────────────────────────────────────
function hostOf(url) { try { return new URL(url).hostname.replace('www.', ''); } catch { return url; } }
function WallCitations({ urls }) {
  if (!urls || urls.length === 0) return null;
  return (
    <div>
      <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 13, letterSpacing: 1, textTransform: 'uppercase', color: H.fg3, marginBottom: 10 }}>Sources</div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {urls.map((u, i) => (
          <a key={i} href={u} target="_blank" rel="noreferrer" style={{
            display: 'flex', alignItems: 'center', gap: 10, textDecoration: 'none',
            background: '#fff', borderRadius: 14, padding: '12px 14px', minHeight: 44, boxSizing: 'border-box',
            boxShadow: '0 1px 2px rgba(3,4,13,0.04)',
          }}>
            <div style={{ width: 30, height: 30, borderRadius: 8, background: H.bgSecondary, display: 'grid', placeItems: 'center', flexShrink: 0 }}>
              <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke={H.fg2} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M14 3h7v7M21 3l-9 9M21 14v5a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5" /></svg>
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontFamily: H.body, fontSize: 14, color: H.fg1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{hostOf(u)}</div>
              <div style={{ fontFamily: H.body, fontSize: 11.5, color: H.fg3 }}>Peer-reviewed source</div>
            </div>
            <HChevron />
          </a>
        ))}
      </div>
    </div>
  );
}

// ── Detail hero ──────────────────────────────────────────────────────────────
function WallDetailHero({ post }) {
  const p = pillarOf(post);
  if (!post.mediaUrl) return null;
  const D = CHART_DATA[post.mediaUrl];
  return (
    <div style={{ borderRadius: 18, overflow: 'hidden', background: '#fff', boxShadow: '0 1px 2px rgba(3,4,13,0.05)', marginBottom: 16 }}>
      <div style={{ position: 'relative', width: '100%', aspectRatio: '16 / 9', background: rgba(p.color, 0.06), display: 'grid', placeItems: 'stretch' }}>
        {post.type === 'CHART' && (
          <div style={{ display: 'flex', flexDirection: 'column', justifyContent: 'center', padding: '8px 4px' }}>
            <WallLineChart src={post.mediaUrl} color={p.color} height={170} pad={20} />
          </div>
        )}
        {post.type === 'ACHIEVEMENT' && <WallBadgeArt color={p.color} size="lg" />}
        {post.type === 'VOICE_NOTE' && <WallVoiceArt color={p.color} full />}
        {post.type === 'CHART' && D && (
          <div style={{ position: 'absolute', left: 14, top: 12, background: 'rgba(255,255,255,0.72)', backdropFilter: 'blur(6px)', WebkitBackdropFilter: 'blur(6px)', padding: '6px 11px 7px', borderRadius: 14 }}>
            <div style={{ fontFamily: H.body, fontSize: 10.5, letterSpacing: 0.7, textTransform: 'uppercase', color: H.fg3 }}>Latest</div>
            <div style={{ fontFamily: H.display, fontWeight: 600, fontSize: 24, color: H.fg1, letterSpacing: -0.5, whiteSpace: 'nowrap', lineHeight: 1.1 }}>{D.last}</div>
          </div>
        )}
      </div>
      {post.type === 'VOICE_NOTE' && <VoicePlayerBar color={p.color} />}
    </div>
  );
}

function VoicePlayerBar({ color }) {
  const [playing, setPlaying] = useStateW(false);
  const [t, setT] = useStateW(0);
  useEffectW(() => {
    if (!playing) return;
    const id = setInterval(() => setT(v => (v >= 100 ? (clearInterval(id), setPlaying(false), 0) : v + 1.6)), 80);
    return () => clearInterval(id);
  }, [playing]);
  const total = 96; const cur = Math.round((t / 100) * total);
  const fmt = s => `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 14px' }}>
      <button onClick={() => setPlaying(p => !p)} style={{ width: 40, height: 40, borderRadius: 999, border: 0, background: color, display: 'grid', placeItems: 'center', cursor: 'pointer', flexShrink: 0 }}>
        {playing
          ? <svg width="15" height="15" viewBox="0 0 24 24" fill="#fff"><rect x="6" y="5" width="4" height="14" rx="1" /><rect x="14" y="5" width="4" height="14" rx="1" /></svg>
          : <svg width="15" height="15" viewBox="0 0 24 24" fill="#fff" style={{ marginLeft: 2 }}><path d="M7 5v14l11-7z" /></svg>}
      </button>
      <div style={{ flex: 1 }}>
        <div style={{ height: 5, borderRadius: 999, background: rgba(color, 0.18), overflow: 'hidden' }}>
          <div style={{ width: `${t}%`, height: '100%', background: color, transition: 'width 80ms linear' }} />
        </div>
      </div>
      <span style={{ fontFamily: H.body, fontSize: 12, color: H.fg2, flexShrink: 0, fontVariantNumeric: 'tabular-nums' }}>{fmt(cur)} / {fmt(total)}</span>
    </div>
  );
}

// ── PostDetailScreen ─────────────────────────────────────────────────────────
function PostDetailScreen({ onNavigate, onBack, postId, store, settings }) {
  const post = store.posts.find(p => p.id === postId);
  const [toast, setToast] = useStateW(null);

  // mark read on open
  useEffectW(() => { if (post && post.readAt === null) store.markRead(post.id); }, [post && post.id]);

  if (!post) {
    return (
      <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: H.bg }}>
        <HTopBar onBack={onBack} title="Post" />
        <div style={{ flex: 1, display: 'grid', placeItems: 'center', fontFamily: H.body, color: H.fg2 }}>This post is no longer available.</div>
      </div>
    );
  }

  const p = pillarOf(post);
  const share = () => {
    setToast('Shared with Healify ❤️');
    setTimeout(() => setToast(null), 1900);
  };
  const ShareBtn = (
    <div onClick={share} role="button" aria-label="Share" style={{ width: 36, height: 36, borderRadius: 999, background: '#fff', display: 'grid', placeItems: 'center', cursor: 'pointer', boxShadow: '0 1px 2px rgba(3,4,13,0.06)' }}>
      <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke={H.fg1} strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round"><path d="M12 3v13M8 7l4-4 4 4" /><path d="M5 12v7a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2v-7" /></svg>
    </div>
  );

  return (
    <div className="screen-enter" style={{ height: '100%', display: 'flex', flexDirection: 'column', background: H.bg, position: 'relative' }}>
      <HTopBar onBack={onBack} right={ShareBtn} sticky />
      <div className="no-scrollbar" style={{ flex: 1, overflowY: 'auto', padding: '4px 20px 130px' }}>
        <WallDetailHero post={post} />

        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 14 }}>
          <WallPillarChip tag={post.pillarTag} />
          <WallTypeBadge type={post.type} />
        </div>

        <h1 style={{
          fontFamily: H.display, fontWeight: 600, fontSize: 27, lineHeight: 1.18,
          letterSpacing: -0.6, color: H.fg1, margin: '0 0 16px',
        }}>{post.caption}</h1>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 14, marginBottom: 22 }}>
          {post.annaCommentary.split('\n').filter(Boolean).map((para, i) => (
            <p key={i} style={{ fontFamily: H.body, fontSize: 16, lineHeight: 1.6, color: H.fg1, letterSpacing: -0.2, margin: 0 }}>{para}</p>
          ))}
        </div>

        {post.citationUrls && post.citationUrls.length > 0 && (
          <div style={{ marginBottom: 24 }}><WallCitations urls={post.citationUrls} /></div>
        )}

        {/* reaction bar */}
        <div style={{ marginBottom: 22 }}>
          <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 13, letterSpacing: 1, textTransform: 'uppercase', color: H.fg3, marginBottom: 10 }}>How does this land?</div>
          <WallReactionBar post={post} userReaction={store.userReactions[post.id]} onReact={store.react} />
        </div>

        {/* byline */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '14px 0 0', borderTop: '0.5px solid ' + H.border }}>
          <img src="anna.png" alt="Anna" width="40" height="40" style={{ width: 40, height: 40, borderRadius: 999, objectFit: 'cover' }} />
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: H.body, fontWeight: 600, fontSize: 15, color: H.fg1 }}>Anna</div>
            <div style={{ fontFamily: H.body, fontSize: 12.5, color: H.fg3 }}>Your AI health coach · {relativeTime(post.createdAt)}</div>
          </div>
          <div onClick={() => onNavigate('chat')} role="button" style={{ display: 'inline-flex', alignItems: 'center', gap: 5, padding: '8px 13px', borderRadius: 999, background: H.bgSecondary, cursor: 'pointer' }}>
            <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke={H.fg1} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M4 6a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H9l-4 3v-3H6a2 2 0 0 1-2-2z" /></svg>
            <span style={{ fontFamily: H.body, fontSize: 13, fontWeight: 500, color: H.fg1 }}>Ask Anna</span>
          </div>
        </div>
      </div>

      {/* share toast */}
      {toast && (
        <div style={{
          position: 'absolute', left: '50%', bottom: 46, transform: 'translateX(-50%)',
          background: H.black, color: '#fff', fontFamily: H.body, fontSize: 13.5,
          padding: '11px 18px', borderRadius: 999, boxShadow: '0 8px 24px rgba(3,4,13,0.3)',
          display: 'flex', alignItems: 'center', gap: 8, whiteSpace: 'nowrap', zIndex: 90,
          animation: 'screenIn 200ms ease',
        }}>
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="m5 12 5 5L20 7" /></svg>
          {toast}
        </div>
      )}
    </div>
  );
}

Object.assign(window, { WallHeader, WallScreen, WallReactionBar, WallCitations, WallDetailHero, VoicePlayerBar, PostDetailScreen, hostOf });
