// 知乎 — feed page. Dark mode, recreated layout structure with fictional content.

const ZH_BLUE = '#1772F6';
const ZH_BLUE_DIM = '#1E4E8C';
const FEED_BG = '#0E0F12';
const TEXT_PRIMARY = '#EDEEF0';
const TEXT_MUTED = '#7A8089';
const DIVIDER = '#1B1D22';

const FEED_TABS = ['关注', '推荐', '热榜', '故事', '知识', '圈子', '专栏', '直播', '北京', '听'];

// Feed items derived from runtime data. Each card shows the question +
// a preview of its top answer (if any).
function buildFeedItems() {
  return getFeedQuestions().map(q => {
    const answers = getAnswers(q.qid);
    if (answers.length === 0) {
      return {
        id: q.qid, title: q.title,
        author: null, persona: null, excerpt: null,
        likes: 0, stars: 0, comments: 0, images: null,
      };
    }
    // Preview the FIRST answer in the array — same answer the user lands on
    // when they tap into detail. The ANSWERS array is curated in display
    // order (story-first, witty mid, ad last) so [0] is always the "top".
    // Some answers have images, some don't — feed reflects that exactly.
    const top = answers[0];
    const persona = getPersona(top.authorId);
    return {
      id: q.qid, title: q.title,
      author: persona ? { name: persona.name, credential: persona.credential } : null,
      persona,
      excerpt: top.body.split('\n')[0].slice(0, 90).replace(/\*\*/g, '') + '…',
      likes: top.voteUp, stars: top.stars, comments: top.commentCount,
      images: top.images || null,
    };
  });
}

const PLACEHOLDER_HOTS = [
  '陪看：国乒男团决战日本队',
  '特朗普 5 月 15 日访华',
  'A 股长电科技涨停',
  '世乒赛男团决赛中国 vs 日本',
  '8 名中国人赴泰私拍短剧',
  '极地邮轮爆发汉坦病毒疫情',
];

function ZhihuFeed({ onBack, onSearchTap, onCardTap, onDirectTap, onMessageTap, onProfileTap, onPlusTap }) {
  const [tab, setTab] = React.useState('推荐');
  const [phIdx, setPhIdx] = React.useState(0);
  const FEED_ITEMS = React.useMemo(buildFeedItems, []);
  React.useEffect(() => {
    const id = setInterval(() => setPhIdx(i => (i + 1) % PLACEHOLDER_HOTS.length), 2400);
    return () => clearInterval(id);
  }, []);
  const placeholder = PLACEHOLDER_HOTS[phIdx];
  return (
    <div style={{
      position: 'absolute', inset: 0, background: FEED_BG,
      color: TEXT_PRIMARY, display: 'flex', flexDirection: 'column',
      fontFamily: '"PingFang SC", "Noto Sans SC", -apple-system, system-ui',
    }}>
      {/* Top safe area for status bar */}
      <div style={{ height: 38, flexShrink: 0 }}/>

      {/* Search bar */}
      <div style={{ padding: '2px 14px 6px', flexShrink: 0 }}>
        <div onClick={onSearchTap} style={{
          height: 28, borderRadius: 14,
          border: `1px solid ${ZH_BLUE}55`,
          display: 'flex', alignItems: 'center',
          padding: '0 11px', cursor: 'pointer',
          fontSize: 10,
        }}>
          <span key={phIdx} style={{ color: TEXT_PRIMARY, flex: 1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', animation: 'phFade 0.4s ease' }}>
            {placeholder}{phIdx === 1 ? <> <HotBadge/></> : null}
          </span>
          <span style={{ color: '#3A3E45', margin: '0 6px' }}>|</span>
          <span style={{ color: ZH_BLUE, fontWeight: 500 }}>搜索</span>
        </div>
      </div>

      {/* Tabs */}
      <FeedTabs tabs={FEED_TABS} active={tab} onChange={setTab}/>

      {/* Feed list */}
      <div style={{
        flex: 1, overflowY: 'auto', overflowX: 'hidden',
      }}>
        {FEED_ITEMS.map((it, idx) => (
          <FeedCard key={it.id} item={it} last={idx === FEED_ITEMS.length-1} onTap={() => onCardTap && onCardTap(it.id)}/>
        ))}
      </div>

      {/* Bottom nav */}
      <BottomNav onBack={onBack} onDirectTap={onDirectTap} onMessageTap={onMessageTap} onProfileTap={onProfileTap} onPlusTap={onPlusTap}/>
    </div>
  );
}

function HotBadge() {
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      padding: '0 3px', minWidth: 12, height: 12,
      border: '1px solid #F4444A', borderRadius: 2,
      color: '#F4444A', fontSize: 8, fontWeight: 600,
      marginLeft: 4, verticalAlign: 'middle',
      lineHeight: 1, background: 'transparent',
    }}>热</span>
  );
}

function FeedTabs({ tabs, active, onChange }) {
  return (
    <div style={{
      display: 'flex', overflowX: 'auto', overflowY: 'hidden',
      gap: 12, padding: '2px 14px 6px',
      flexShrink: 0,
      borderBottom: `1px solid ${DIVIDER}`,
      scrollbarWidth: 'none',
    }}>
      {tabs.map(t => (
        <div key={t}
          onClick={() => onChange(t)}
          style={{
            position: 'relative', padding: '3px 2px 6px',
            fontSize: t === active ? 12 : 10,
            fontWeight: t === active ? 700 : 400,
            color: t === active ? TEXT_PRIMARY : '#9097A0',
            flexShrink: 0, cursor: 'pointer',
            lineHeight: 1.4,
          }}>
          {t}
          {t === active && (
            <div style={{
              position: 'absolute', bottom: 0, left: 2, right: 2,
              height: 3, borderRadius: 2,
              background: ZH_BLUE,
            }}/>
          )}
        </div>
      ))}
    </div>
  );
}

function FeedCard({ item, last, onTap }) {
  const empty = !item.author && !item.excerpt;
  return (
    <div onClick={onTap} style={{
      padding: '8px 14px 7px', cursor: 'pointer',
      borderBottom: last ? 'none' : `1px solid ${DIVIDER}`,
    }}>
      {item.badge && (
        <div style={{
          color: TEXT_MUTED, fontSize: 8.5, marginBottom: 5,
          display: 'flex', alignItems: 'center', gap: 4,
        }}>
          <span style={{ fontSize: 7 }}>▲</span>
          <span>你关注的</span>
          <span style={{ color: '#9AA3AE' }}>{item.badge.who}</span>
          <span>已赞同</span>
        </div>
      )}

      <div style={{
        fontSize: 10.5, fontWeight: 700, lineHeight: 1.35,
        color: TEXT_PRIMARY,
      }}>{item.title}</div>

      {item.author && (
        <div style={{
          display: 'flex', alignItems: 'center', gap: 5,
          marginTop: 5,
        }}>
          {item.persona ? (
            <AuthorAvatar persona={item.persona} size={13}/>
          ) : (
            <div style={{
              width: 13, height: 13, borderRadius: 7,
              background: '#3A3E45',
            }}/>
          )}
          <span style={{ fontSize: 8.5, color: '#B6BCC4' }}>{item.author.name}</span>
          {item.author.credential === 'verified' && <VerifyTick/>}
        </div>
      )}

      {item.excerpt && (
        <div style={{
          marginTop: 4, fontSize: 9.5, color: '#C8CCD2',
          lineHeight: 1.55, textWrap: 'pretty',
          display: '-webkit-box',
          WebkitLineClamp: 2,
          WebkitBoxOrient: 'vertical',
          overflow: 'hidden',
        }}>{item.excerpt}</div>
      )}

      {item.images && item.images.length > 0 && <ImageTiles seeds={item.images}/>}

      {!empty && <EngagementRow likes={item.likes} stars={item.stars} comments={item.comments}/>}
    </div>
  );
}

function VerifyTick() {
  return (
    <svg width="11" height="11" viewBox="0 0 12 12">
      <circle cx="6" cy="6" r="6" fill={ZH_BLUE}/>
      <path d="M3.5 6 L5.2 7.6 L8.5 4.3" stroke="#fff" strokeWidth="1.4" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  );
}

function ImageTiles({ seeds }) {
  // Render up to 3 image previews in a row; if more, show "+N" on the last
  // tile. Each seed can be either a Loremflickr URL (full http) or a
  // bare keyword string — `imageUrl()` handles both.
  const visible = seeds.slice(0, 3);
  const extra = seeds.length - 3;
  return (
    <div style={{
      marginTop: 6, display: 'flex', gap: 4,
    }}>
      {visible.map((s, i) => (
        <div key={i} style={{
          flex: 1, height: 64, borderRadius: 3, position: 'relative',
          overflow: 'hidden', background: '#1B1D22',
        }}>
          <img src={imageUrl(s, 240, 240)}
            alt="" loading="lazy"
            style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }}/>
          {i === 2 && extra > 0 && (
            <div style={{
              position: 'absolute', inset: 0,
              background: 'rgba(0,0,0,0.55)', color: '#fff',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontSize: 14, fontWeight: 600,
            }}>+{extra}</div>
          )}
        </div>
      ))}
      {visible.length < 3 && Array.from({ length: 3 - visible.length }).map((_, i) => (
        <div key={'pad' + i} style={{ flex: 1 }}/>
      ))}
    </div>
  );
}

function EngagementRow({ likes, stars, comments }) {
  return (
    <div style={{
      marginTop: 7, display: 'flex', alignItems: 'center',
      gap: 14, color: TEXT_MUTED, fontSize: 8.5,
    }}>
      <IconStat icon="triangle" n={likes}/>
      <IconStat icon="star" n={stars}/>
      <IconStat icon="bubble" n={comments}/>
      <div style={{ flex: 1 }}/>
      <span style={{ fontSize: 11, color: TEXT_MUTED }}>×</span>
    </div>
  );
}

function IconStat({ icon, n }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
      <StatIcon kind={icon}/>
      <span>{formatN(n)}</span>
    </div>
  );
}

function formatN(n) {
  if (n >= 10000) return (n/10000).toFixed(1) + '万';
  return n.toString();
}

function StatIcon({ kind }) {
  const sz = 12;
  if (kind === 'triangle') return (
    <svg width={sz} height={sz} viewBox="0 0 16 16" fill="none">
      <path d="M8 3 L13 12 L3 12 Z" stroke={TEXT_MUTED} strokeWidth="1.3" fill="none" strokeLinejoin="round"/>
    </svg>
  );
  if (kind === 'star') return (
    <svg width={sz} height={sz} viewBox="0 0 16 16" fill="none">
      <path d="M8 2 L9.8 6 L14 6.4 L10.8 9.3 L11.8 13.5 L8 11.3 L4.2 13.5 L5.2 9.3 L2 6.4 L6.2 6 Z"
        stroke={TEXT_MUTED} strokeWidth="1.2" fill="none" strokeLinejoin="round"/>
    </svg>
  );
  return (
    <svg width={sz} height={sz} viewBox="0 0 16 16" fill="none">
      <path d="M3 4 a2 2 0 012-2 h6 a2 2 0 012 2 v4 a2 2 0 01-2 2 h-3 l-3 2 v-2 h-0 a2 2 0 01-2-2 z"
        stroke={TEXT_MUTED} strokeWidth="1.2" fill="none" strokeLinejoin="round"/>
    </svg>
  );
}

function BottomNav({ onBack, onDirectTap, onMessageTap, onProfileTap, onPlusTap, activeTab = 'home' }) {
  return (
    <div style={{
      position: 'relative', flexShrink: 0,
      paddingBottom: 16, paddingTop: 4,
      background: FEED_BG,
      borderTop: `1px solid ${DIVIDER}`,
      display: 'flex', justifyContent: 'space-around', alignItems: 'stretch',
    }}>
      <NavItem icon="home"   label="首页" active={activeTab === 'home'}   onClick={onBack}/>
      <NavItem icon="direct" label="直答" active={activeTab === 'direct'} onClick={onDirectTap}/>
      <NavItem icon="plus"   label=" " onClick={onPlusTap}/>
      <NavItem icon="msg"    label="消息" active={activeTab === 'msg'} badge="99+" onClick={onMessageTap}/>
      <NavItem icon="me"     label="我的" active={activeTab === 'me'} onClick={onProfileTap}/>
    </div>
  );
}

function NavItem({ icon, label, active, badge, onClick }) {
  const isPlus = icon === 'plus';
  return (
    <div onClick={onClick} style={{
      display: 'flex', flexDirection: 'column', alignItems: 'center',
      gap: 2, position: 'relative', width: 48,
      color: active ? TEXT_PRIMARY : TEXT_MUTED,
      cursor: 'pointer',
    }}>
      <div style={{ position: 'relative', height: 18, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        {isPlus ? (
          <div style={{
            width: 30, height: 30, borderRadius: 15,
            background: ZH_BLUE, color: '#fff',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontSize: 20, fontWeight: 300, lineHeight: 1,
            position: 'absolute', top: -6, left: '50%',
            transform: 'translateX(-50%)',
            boxShadow: '0 2px 6px rgba(26,117,224,0.4)',
          }}>+</div>
        ) : <NavIcon kind={icon} active={active}/>}
        {badge && (
          <div style={{
            position: 'absolute', top: -3, left: 10,
            background: '#E53935', color: '#fff', fontSize: 8,
            padding: '0 3px', borderRadius: 7, fontWeight: 600,
            minWidth: 14, height: 12, lineHeight: '12px', textAlign: 'center',
          }}>{badge}</div>
        )}
      </div>
      <span style={{ fontSize: 9, fontWeight: active ? 600 : 400, minHeight: 12 }}>{label}</span>
    </div>
  );
}

function NavIcon({ kind, active }) {
  const stroke = active ? TEXT_PRIMARY : TEXT_MUTED;
  const sz = 18;
  if (kind === 'home') return (
    <svg width={sz} height={sz} viewBox="0 0 24 24" fill={active ? TEXT_PRIMARY : 'none'} stroke={stroke} strokeWidth="1.6">
      <path d="M3 10 L12 3 L21 10 V20 a1 1 0 01-1 1 H4 a1 1 0 01-1-1 Z" strokeLinejoin="round"/>
    </svg>
  );
  if (kind === 'direct') return (
    <div style={{ position: 'relative', display: 'inline-block', lineHeight: 1 }}>
      <span style={{
        fontFamily: 'Georgia, "Times New Roman", serif',
        fontSize: 16, fontWeight: 700, fontStyle: 'italic',
        color: stroke, letterSpacing: -0.5,
      }}>D</span>
      <span style={{
        position: 'absolute', top: -2, right: -5,
        fontFamily: 'Georgia, serif', fontSize: 8, fontWeight: 700,
        color: ZH_BLUE,
      }}>+</span>
    </div>
  );
  if (kind === 'msg') return (
    <svg width={sz} height={sz} viewBox="0 0 24 24" fill="none" stroke={stroke} strokeWidth="1.6">
      <path d="M12 3 a6 6 0 016 6 v4 l1.5 2 h-15 L4 13 V9 a6 6 0 016-6 z M10 19 a2 2 0 004 0" strokeLinejoin="round" strokeLinecap="round"/>
    </svg>
  );
  if (kind === 'me') return <UserAvatar size={sz} fontScale={0.5}/>;
  return null;
}

Object.assign(window, { ZhihuFeed });
