// 知乎 — "我的" page. Structurally modeled on the user's screenshots; original copy + names.

const P_BG = '#0E0F12';
const P_CARD = '#16181D';
const P_CARD2 = '#1A1D22';
const P_TEXT = '#EDEEF0';
const P_MUTED = '#7A8089';
const P_DIM = '#5A5F66';
const P_DIVIDER = '#1B1D22';
const P_BLUE = '#1772F6';
const P_BLUE_SOFT = '#1B3556';

function ProfilePage({ onBack, onDirectTap, onMessageTap, onHomeTap, onSettingsTap, onPlusTap }) {
  const scrollRef = React.useRef(null);
  const [scrollY, setScrollY] = React.useState(0);
  const [memIdx, setMemIdx] = React.useState(0);

  React.useEffect(() => {
    const el = scrollRef.current;
    if (!el) return;
    const onScroll = () => setScrollY(el.scrollTop);
    el.addEventListener('scroll', onScroll, { passive: true });
    return () => el.removeEventListener('scroll', onScroll);
  }, []);

  // Small avatar in the fixed top-left row — 用户进入"我的" 第一眼就要看到自己头像,
  // 不再绑 scrollY > 36 才显示 (评审场景: 评审官需要明确看到"是自己登录的").
  const showSmall = true;

  return (
    <div style={{
      position: 'absolute', inset: 0, background: P_BG, color: P_TEXT,
      fontFamily: '"PingFang SC", "Noto Sans SC", -apple-system, system-ui',
      display: 'flex', flexDirection: 'column',
    }}>
      <div style={{ height: 38, flexShrink: 0 }}/>

      {/* Fixed top action row */}
      <div style={{
        position: 'relative', flexShrink: 0, height: 36,
        display: 'flex', alignItems: 'center', padding: '0 12px',
        background: P_BG, zIndex: 5,
      }}>
        {/* Small avatar (appears on scroll) */}
        <div style={{
          opacity: showSmall ? 1 : 0,
          transition: 'opacity 0.18s',
          display: 'flex', alignItems: 'center', gap: 6,
        }}>
          <MiniAvatar size={26}/>
        </div>
        <div style={{ flex: 1 }}/>
        {/* Right icons — always visible */}
        <div style={{ display: 'flex', gap: 14, alignItems: 'center' }}>
          <PIcon kind="scan"/>
          <PIcon kind="search"/>
          <PIcon kind="sun"/>
          <PIcon kind="settings" onClick={onSettingsTap}/>
        </div>
      </div>

      {/* Scrollable content */}
      <div ref={scrollRef} style={{
        flex: 1, overflowY: 'auto', overflowX: 'hidden',
        paddingBottom: 56,
      }}>
        {/* Big avatar + name row */}
        <div style={{
          padding: '2px 12px 8px',
          display: 'flex', alignItems: 'center', gap: 9,
        }}>
          <MiniAvatar size={40}/>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 14, fontWeight: 700, lineHeight: 1.1 }}>{CURRENT_USER.name}</div>
            <div style={{ fontSize: 9, color: P_MUTED, marginTop: 3 }}>点击查看个人主页 ›</div>
          </div>
          <div style={{
            padding: '3px 10px', borderRadius: 12,
            border: `1px solid ${P_DIM}`, fontSize: 9.5, color: P_TEXT,
            cursor: 'pointer',
          }}>创作中心</div>
        </div>

        {/* 认证信息 (硬编码 — 演示场景里用户是知乎 2026 黑客松评审官). */}
        <div style={{ padding: '0 12px 6px' }}>
          <div style={{
            display: 'inline-flex', alignItems: 'center', gap: 4,
            padding: '2px 8px', borderRadius: 10,
            background: P_CARD, fontSize: 9, color: P_TEXT,
          }}>
            <svg width="9" height="9" viewBox="0 0 12 12">
              <circle cx="6" cy="6" r="6" fill={P_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>
            知乎 2026 黑客松评审官
          </div>
        </div>

        {/* Stats row */}
        <div style={{
          padding: '0 12px 10px', display: 'flex',
          fontSize: 9, color: P_MUTED,
        }}>
          {[
            [String(CURRENT_USER.stats.following),   '关注'],
            [String(CURRENT_USER.stats.followers),   '被关注'],
            [String(CURRENT_USER.stats.collections), '收藏'],
            [String(CURRENT_USER.stats.recentViews), '最近浏览'],
          ].map((s, i) => (
            <React.Fragment key={i}>
              <div style={{ flex: 1 }}>
                <span style={{ color: P_TEXT, fontWeight: 700, fontSize: 11, marginRight: 3 }}>{s[0]}</span>
                {s[1]}
              </div>
              {i < 3 && <div style={{ width: 1, background: P_DIVIDER, margin: '2px 0' }}/>}
            </React.Fragment>
          ))}
        </div>

        {/* Membership carousel */}
        <MembershipCarousel idx={memIdx} setIdx={setMemIdx}/>

        {/* Icon grid */}
        <div style={{
          padding: '12px 6px 4px',
          display: 'grid', gridTemplateColumns: 'repeat(6, 1fr)',
          rowGap: 10,
        }}>
          {[
            { kind: 'shelf', label: '书架' },
            { kind: 'course', label: '我的课程' },
            { kind: 'wallet', label: '钱包' },
            { kind: 'yuan', label: '付费咨询' },
            { kind: 'gift', label: '福利社' },
            { kind: 'shop', label: '商城' },
            { kind: 'headset', label: '帮助与客服' },
            { kind: 'flask', label: 'AI 实验室' },
            { kind: 'circle', label: '圈子' },
            { kind: 'check', label: '打卡挑战', active: true },
          ].map((it, i) => (
            <div key={i} style={{
              display: 'flex', flexDirection: 'column', alignItems: 'center',
              gap: 3, cursor: 'pointer',
            }}>
              <div style={{ width: 22, height: 22, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <LineIcon kind={it.kind} color={it.active ? P_BLUE : P_TEXT}/>
              </div>
              <div style={{ fontSize: 8.5, color: P_TEXT }}>{it.label}</div>
            </div>
          ))}
        </div>

        {/* Recommendations card */}
        <div style={{
          margin: '10px 0 0', background: P_CARD,
          padding: '8px 10px 2px',
        }}>
          <div style={{
            display: 'flex', alignItems: 'center', gap: 12,
            fontSize: 11,
          }}>
            <span style={{
              color: P_TEXT, fontWeight: 700,
              borderBottom: `2px solid ${P_BLUE}`, paddingBottom: 2,
            }}>推荐问题</span>
            <span style={{ color: P_MUTED }}>创作灵感</span>
            <div style={{ flex: 1 }}/>
            <span style={{ fontSize: 9, color: P_MUTED }}>更多问题 ›</span>
          </div>

          {[
            { kind: 'globe', tip: '你可能感兴趣', q: '昨晚因为 AI 的话题跟老公争论了很久，谁也说服不了谁，大家帮我评评理？', a: 1733, f: 2069 },
            { kind: 'bubble', tip: '试试帮他/她解答吧', q: '中国老龄化少子化有什么解决方法？', a: 92, f: 102 },
            { kind: 'phone', tip: '试试帮他/她解答吧', q: '巴菲特为什么那么看重商业模式？', a: 15, f: 48 },
          ].map((it, i) => (
            <div key={i} style={{
              padding: '8px 0 6px',
              borderTop: i ? `1px solid ${P_DIVIDER}` : 'none',
            }}>
              <div style={{
                display: 'flex', alignItems: 'center', gap: 4,
                fontSize: 9, color: P_MUTED, marginBottom: 4,
              }}>
                <LineIcon kind={it.kind} color={P_MUTED} size={12}/>
                {it.tip}
              </div>
              <div style={{ fontSize: 11, color: P_TEXT, lineHeight: 1.4 }}>{it.q}</div>
              <div style={{
                display: 'flex', alignItems: 'center', marginTop: 5,
              }}>
                <span style={{ fontSize: 9, color: P_MUTED }}>{it.a} 回答 · {it.f} 关注</span>
                <div style={{ flex: 1 }}/>
                <div style={{
                  padding: '2px 9px', borderRadius: 10,
                  background: P_BLUE_SOFT, color: P_BLUE,
                  fontSize: 9,
                }}>写回答</div>
              </div>
            </div>
          ))}
        </div>

        {/* Punch-in card */}
        <div style={{
          margin: '10px 0 0', background: P_CARD,
          padding: '10px',
        }}>
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <div>
              <div style={{ fontSize: 12, fontWeight: 700, color: P_TEXT }}>创作打卡瓜分 2300 万盐粒</div>
              <div style={{ fontSize: 9, color: P_MUTED, marginTop: 3 }}>全勤奖励翻倍，还有 300 万盐粒等你瓜分！</div>
            </div>
            <div style={{ flex: 1 }}/>
            <div style={{
              padding: '3px 11px', borderRadius: 12,
              background: '#E68B45', color: '#fff',
              fontSize: 10, fontWeight: 600,
            }}>去报名</div>
          </div>
          <div style={{
            marginTop: 14, display: 'grid',
            gridTemplateColumns: 'repeat(4, 1fr)', gap: 5,
          }}>
            {['+100 万', '+100 万', '+100 万', '+200 万'].map((bonus, i) => (
              <div key={i} style={{ position: 'relative' }}>
                <div style={{
                  position: 'absolute', top: -7, left: '50%',
                  transform: 'translateX(-50%)',
                  background: P_CARD,
                  border: '1px solid #5E3618',
                  color: '#E68B45', fontSize: 8,
                  padding: '0px 4px', borderRadius: 3,
                  whiteSpace: 'nowrap',
                  visibility: i === 0 ? 'hidden' : 'visible',
                }}>连续 {bonus}</div>
                <div style={{
                  border: `1px solid ${P_DIVIDER}`, borderRadius: 5,
                  padding: '6px 0', textAlign: 'center',
                }}>
                  <div style={{ fontSize: 9, color: P_TEXT }}>{['第一周','第二周','第三周','第四周'][i]}</div>
                  <div style={{ margin: '4px auto 3px' }}>
                    <Gem/>
                  </div>
                  <div style={{ fontSize: 9, color: P_TEXT }}>400 万</div>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Other functions list */}
        <div style={{
          margin: '10px 0 10px', background: P_CARD,
          padding: '2px 0',
        }}>
          <div style={{ padding: '9px 12px 3px', fontSize: 11, fontWeight: 700 }}>其他功能</div>
          {[
            { pk: true, label: '知识王者' },
            { kind: 'thumbup', label: '超赞包' },
            { kind: 'heart', label: '会员好礼' },
            { kind: 'trophy', label: '品牌榜' },
            { kind: 'flag', label: '活动广场' },
            { kind: 'sound', label: '畅听' },
            { kind: 'flower', label: '圆桌' },
            { kind: 'pen', label: '盐言作者助手' },
            { kind: 'diamond', label: '盐值分' },
            { kind: 'leaf', label: '社区共建' },
            { kind: 'cloud', label: '云空间' },
          ].map((it, i) => (
            <div key={i} style={{
              display: 'flex', alignItems: 'center', gap: 10,
              padding: '9px 12px',
              borderTop: i ? `1px solid ${P_DIVIDER}` : 'none',
            }}>
              <div style={{ width: 18, height: 18, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                {it.pk ? (
                  <span style={{ fontWeight: 800, fontSize: 10 }}>
                    <span style={{ color: '#FF6B7A' }}>P</span>
                    <span style={{ color: '#5BB0FF' }}>K</span>
                  </span>
                ) : <LineIcon kind={it.kind} color={P_TEXT} size={16}/>}
              </div>
              <span style={{ flex: 1, fontSize: 11, color: P_TEXT }}>{it.label}</span>
              <span style={{ color: P_MUTED, fontSize: 11 }}>›</span>
            </div>
          ))}
        </div>
      </div>

      {/* Bottom nav (matches feed) */}
      <BottomNav activeTab="me" onBack={onHomeTap} onDirectTap={onDirectTap} onMessageTap={onMessageTap} onPlusTap={onPlusTap}/>
    </div>
  );
}

function MiniAvatar({ size }) {
  // Delegate to the shared UserAvatar (driven by CURRENT_USER) so the profile
  // header avatar matches the bottom-nav avatar across the app.
  return <UserAvatar size={size} fontScale={0.32}/>;
}

function PIcon({ kind, onClick }) {
  const stroke = '#D8DCE0';
  const sw = 1.5;
  const wrap = (svg) => <div onClick={onClick} style={{ cursor: onClick ? 'pointer' : 'default', display: 'flex' }}>{svg}</div>;
  const w = 18, h = 18;
  if (kind === 'scan') return wrap(
    <svg width={w} height={h} viewBox="0 0 24 24" fill="none" stroke={stroke} strokeWidth={sw} strokeLinecap="round" strokeLinejoin="round">
      <path d="M4 8V5a1 1 0 0 1 1-1h3"/><path d="M16 4h3a1 1 0 0 1 1 1v3"/>
      <path d="M20 16v3a1 1 0 0 1-1 1h-3"/><path d="M8 20H5a1 1 0 0 1-1-1v-3"/>
      <path d="M3 12h18"/>
    </svg>
  );
  if (kind === 'search') return wrap(
    <svg width={w} height={h} viewBox="0 0 24 24" fill="none" stroke={stroke} strokeWidth={sw} strokeLinecap="round">
      <circle cx="11" cy="11" r="6"/><path d="M16 16l4 4"/>
    </svg>
  );
  if (kind === 'sun') return wrap(
    <svg width={w} height={h} viewBox="0 0 24 24" fill="none" stroke={stroke} strokeWidth={sw} strokeLinecap="round">
      <circle cx="12" cy="12" r="3.5"/>
      <path d="M12 3v2M12 19v2M3 12h2M19 12h2M5.6 5.6l1.4 1.4M17 17l1.4 1.4M5.6 18.4l1.4-1.4M17 7l1.4-1.4"/>
    </svg>
  );
  if (kind === 'settings') return wrap(
    <svg width={w} height={h} viewBox="0 0 24 24" fill="none" stroke={stroke} strokeWidth={sw}>
      <circle cx="12" cy="12" r="8.5"/><circle cx="12" cy="12" r="3"/>
    </svg>
  );
  return null;
}

function MembershipCarousel({ idx, setIdx }) {
  const containerRef = React.useRef(null);
  const cards = [
    { kind: 'salt', big: '续费盐选会员', sub: '已过期', accent: '最低 0.5 元/天',
      topBg: 'linear-gradient(180deg, #F4DDA3 0%, #E2B772 100%)',
      bottomBg: 'linear-gradient(180deg, #2A2218 0%, #1F1A12 100%)',
      darkText: true,
      items: [['盐选榜单','发现精品故事'], ['阅读记录','回顾最近内容'], ['全部故事','探索更多内容']] },
    { kind: 'know', big: '开通知识会员', sub: '专享 10W+ 精选内容', accent: '立即开通',
      topBg: 'linear-gradient(180deg, #BFD5F2 0%, #7A93BA 100%)',
      bottomBg: 'linear-gradient(180deg, #181E28 0%, #11141C 100%)',
      darkText: true,
      items: [['内容广场','开启知识之旅'], ['权益中心','查看全部特权']] },
  ];
  const onScroll = () => {
    const el = containerRef.current;
    if (!el) return;
    const w = el.clientWidth;
    setIdx(Math.round(el.scrollLeft / (w * 0.86)));
  };
  // SVG defines the arc-bottom card silhouette and the gradients.
  return (
    <div ref={containerRef} onScroll={onScroll} style={{
      padding: '0 12px', display: 'flex', gap: 6,
      overflowX: 'auto', scrollSnapType: 'x mandatory',
      scrollbarWidth: 'none', msOverflowStyle: 'none',
    }}>
      {cards.map((c, i) => (
        <MembershipCard key={i} c={c}/>
      ))}
    </div>
  );
}

function MembershipCard({ c }) {
  // Top half: bright gradient with downward arc cut. Bottom half: dark, holds the two/three info rows.
  const W = 230, H = 90;
  const arcTop = 52; // height of top color block before the arc dips
  return (
    <div style={{
      flexShrink: 0, width: W, height: H, position: 'relative',
      scrollSnapAlign: 'start', borderRadius: 7, overflow: 'hidden',
      background: c.bottomBg,
    }}>
      {/* Top arc clip */}
      <svg viewBox={`0 0 ${W} ${H}`} width={W} height={H}
        style={{ position: 'absolute', inset: 0 }}>
        <defs>
          <linearGradient id={`g-${c.kind}`} x1="0" y1="0" x2="0" y2="1">
            <stop offset="0" stopColor={c.kind === 'salt' ? '#F4DDA3' : '#BFD5F2'}/>
            <stop offset="1" stopColor={c.kind === 'salt' ? '#E2B772' : '#7A93BA'}/>
          </linearGradient>
        </defs>
        {/* Filled top region with concave arc bottom edge */}
        <path d={`M0 0 H${W} V${arcTop} Q${W/2} ${arcTop+18} 0 ${arcTop} Z`}
          fill={`url(#g-${c.kind})`}/>
      </svg>

      {/* Top text block */}
      <div style={{
        position: 'absolute', top: 8, left: 12, right: 12,
        display: 'flex', alignItems: 'flex-start',
        color: '#1F2937',
      }}>
        <div>
          <div style={{ fontSize: 13, fontWeight: 800, lineHeight: 1.15 }}>{c.big}</div>
          <div style={{ fontSize: 9, marginTop: 2, opacity: 0.75 }}>{c.sub}</div>
        </div>
        <div style={{ flex: 1 }}/>
        <div style={{
          padding: '3px 9px', borderRadius: 10,
          background: c.kind === 'salt' ? 'rgba(255,255,255,0.4)' : '#2D4B7C',
          color: c.kind === 'salt' ? '#1F2937' : '#fff',
          fontSize: 9, fontWeight: 600,
        }}>{c.accent}</div>
      </div>

      {/* Bottom dark block with info items */}
      <div style={{
        position: 'absolute', left: 0, right: 0, bottom: 0,
        height: H - arcTop - 6, padding: '4px 12px',
        display: 'flex', alignItems: 'center', gap: 12,
        color: '#D8DCE0', fontSize: 9,
      }}>
        {c.items.map(([k, v], j) => (
          <div key={j} style={{ flex: 1 }}>
            <div style={{ fontWeight: 600, color: '#EDEEF0' }}>{k} ›</div>
            <div style={{ opacity: 0.7, marginTop: 1 }}>{v}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ─── Line icons ──────────────────────────────────────────────────────
function LineIcon({ kind, color = '#EDEEF0', size = 18 }) {
  const p = { fill: 'none', stroke: color, strokeWidth: 1.4, strokeLinecap: 'round', strokeLinejoin: 'round' };
  const map = {
    shelf:   <g {...p}><rect x="4" y="3" width="16" height="18" rx="1.5"/><path d="M4 9 H20 M4 15 H20"/></g>,
    course:  <g {...p}><rect x="3" y="4" width="18" height="15" rx="1.5"/><path d="M3 9 H21 M8 4 V19"/></g>,
    wallet:  <g {...p}><rect x="3" y="6" width="18" height="14" rx="2"/><path d="M3 10 H21"/><circle cx="16" cy="15" r="1" fill={color}/></g>,
    yuan:    <g {...p}><circle cx="12" cy="12" r="9"/><path d="M8 8 L12 13 L16 8 M12 13 V18 M9 14 H15 M9 16 H15"/></g>,
    gift:    <g {...p}><rect x="3" y="8" width="18" height="13" rx="1.5"/><path d="M3 13 H21 M12 8 V21"/><path d="M12 8 C12 5 9 4 8 5 C7 6 8 8 12 8 C12 5 15 4 16 5 C17 6 16 8 12 8"/></g>,
    shop:    <g {...p}><path d="M4 8 L5 4 H19 L20 8 Z"/><path d="M5 8 V20 H19 V8"/><path d="M9 13 H15"/></g>,
    headset: <g {...p}><path d="M4 14 V12 A8 8 0 0 1 20 12 V14"/><rect x="3" y="14" width="4" height="6" rx="1"/><rect x="17" y="14" width="4" height="6" rx="1"/></g>,
    flask:   <g {...p}><path d="M9 3 V8 L4 19 A1 1 0 0 0 5 21 H19 A1 1 0 0 0 20 19 L15 8 V3"/><path d="M8 3 H16"/></g>,
    circle:  <g {...p}><circle cx="12" cy="12" r="8"/><circle cx="12" cy="12" r="3"/></g>,
    check:   <g {...p}><rect x="4" y="3" width="16" height="18" rx="1.5"/><path d="M8 12 L11 15 L17 8"/></g>,
    globe:   <g {...p}><circle cx="12" cy="12" r="8"/><path d="M4 12 H20 M12 4 C8 8 8 16 12 20 M12 4 C16 8 16 16 12 20"/></g>,
    bubble:  <g {...p}><path d="M4 6 H20 V16 H13 L9 20 V16 H4 Z"/></g>,
    phone:   <g {...p}><rect x="7" y="3" width="10" height="18" rx="1.5"/><circle cx="12" cy="18" r="0.8" fill={color}/></g>,
    thumbup: <g {...p}><path d="M7 11 V20 H17 L20 13 V11 H13 L14 6 A2 2 0 0 0 10 6 L7 11 Z"/><rect x="3" y="11" width="4" height="9" rx="0.8"/></g>,
    heart:   <g {...p}><path d="M12 20 C5 15 3 10 6 7 C8 5 11 6 12 9 C13 6 16 5 18 7 C21 10 19 15 12 20 Z"/></g>,
    trophy:  <g {...p}><path d="M7 4 H17 V10 A5 5 0 0 1 7 10 Z"/><path d="M7 6 H4 V8 A2 2 0 0 0 7 10 M17 6 H20 V8 A2 2 0 0 1 17 10"/><path d="M10 14 H14 M9 17 H15 V20 H9 Z M12 14 V17"/></g>,
    flag:    <g {...p}><path d="M5 3 V21 M5 4 H17 L14 8 L17 12 H5"/></g>,
    sound:   <g {...p}><path d="M4 9 V15 H8 L13 19 V5 L8 9 Z"/><path d="M16 9 C17 11 17 13 16 15 M18 7 C20 10 20 14 18 17"/></g>,
    flower:  <g {...p}><circle cx="12" cy="12" r="2"/><circle cx="12" cy="6" r="3"/><circle cx="12" cy="18" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="12" r="3"/></g>,
    pen:     <g {...p}><path d="M5 19 L5 21 L7 21 L19 9 L17 7 L15 5 L3 17 Z"/><path d="M14 6 L18 10"/></g>,
    diamond: <g {...p}><path d="M12 3 L21 12 L12 21 L3 12 Z"/><path d="M3 12 H21 M12 3 V21"/></g>,
    leaf:    <g {...p}><path d="M4 20 C4 11 11 4 20 4 C20 13 13 20 4 20 Z"/><path d="M4 20 L14 10"/></g>,
    cloud:   <g {...p}><path d="M7 17 H17 A4 4 0 0 0 17 9 A6 6 0 0 0 6 11 A3 3 0 0 0 7 17 Z"/></g>,
  };
  return (
    <svg width={size} height={size} viewBox="0 0 24 24">{map[kind] || null}</svg>
  );
}

function Gem() {
  return (
    <svg width="24" height="20" viewBox="0 0 24 20">
      <defs>
        <linearGradient id="gemG" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0" stopColor="#7AB2FF"/>
          <stop offset="1" stopColor="#2B5FB8"/>
        </linearGradient>
      </defs>
      <polygon points="12,1 22,8 18,18 6,18 2,8" fill="url(#gemG)" stroke="#5A8FE0" strokeWidth="0.8"/>
      <polyline points="2,8 12,11 22,8" fill="none" stroke="#A6CCFF" strokeWidth="0.6"/>
      <line x1="12" y1="11" x2="12" y2="18" stroke="#A6CCFF" strokeWidth="0.6"/>
    </svg>
  );
}

Object.assign(window, { ProfilePage });
