// 知乎 — 答主个人主页 (Author profile). Reached by tapping any author avatar
// or author row in a question detail page. Mirrors Zhihu's real profile
// layout: hero banner → avatar + stats → name/IP/bio → follow/DM → tabs →
// sub-tabs with counts → answer list scoped to this author.

const AP_BG       = '#0E0F12';
const AP_CARD     = '#16181D';
const AP_TEXT     = '#EDEEF0';
const AP_MUTED    = '#7A8089';
const AP_DIM      = '#5A5F66';
const AP_DIVIDER  = '#1B1D22';
const AP_BLUE     = '#1772F6';
const AP_BLUE_SOFT= '#1B3556';

function AuthorProfile({ authorId, onBack, onQuestionTap }) {
  const persona = getPersona(authorId);
  const answers = getAnswersByAuthor(authorId);
  const [tab, setTab] = React.useState('create');     // create | activity | agree
  const [subTab, setSubTab] = React.useState('all');  // all | answers | ideas | articles | columns | asks

  if (!persona) {
    return (
      <div style={{ position: 'absolute', inset: 0, background: AP_BG, color: AP_TEXT,
        display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 12 }}>
        未找到该答主 ({authorId})
      </div>
    );
  }

  const [g1, g2] = persona.coverGradient || ['#243653', '#0E1929'];
  const showIp   = !!persona.region;

  // Apply sub-tab filter to displayed answers.
  let shown = answers;
  if (subTab === 'answers') shown = answers; // all the answers we have are 回答
  // others are 0 — leave empty list to show 空状态

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

      {/* Top action row (always visible over the banner) */}
      <div style={{
        position: 'absolute', top: 38, left: 0, right: 0, height: 36,
        display: 'flex', alignItems: 'center', padding: '0 10px',
        zIndex: 5,
      }}>
        <div onClick={onBack} style={{
          width: 24, height: 24, color: AP_TEXT, fontSize: 20,
          cursor: 'pointer', display: 'flex', alignItems: 'center',
          justifyContent: 'center',
        }}>‹</div>
        <div style={{ flex: 1 }}/>
        <div style={{ display: 'flex', gap: 12, color: AP_TEXT }}>
          <span style={{ fontSize: 14, cursor: 'pointer' }}>⌕</span>
          <span style={{ fontSize: 14, cursor: 'pointer' }}>⋯</span>
        </div>
      </div>

      <div style={{ flex: 1, overflowY: 'auto', overflowX: 'hidden' }}>
        {/* Hero banner */}
        <div style={{
          position: 'relative', height: 80,
          background: `linear-gradient(135deg, ${g1}, ${g2})`,
        }}>
          <div style={{
            position: 'absolute', inset: 0,
            background: 'radial-gradient(circle at 70% 30%, rgba(255,255,255,0.08), transparent 60%)',
          }}/>
          {showIp && (
            <div style={{
              position: 'absolute', right: 8, bottom: 5,
              background: 'rgba(0,0,0,0.5)', borderRadius: 9,
              padding: '1.5px 7px', fontSize: 8.5, color: AP_TEXT,
              display: 'flex', alignItems: 'center', gap: 3,
            }}>
              <svg width="7" height="9" viewBox="0 0 8 10" fill="none">
                <path d="M4 0 C 1.8 0 0 1.8 0 4 C 0 6.5 4 10 4 10 C 4 10 8 6.5 8 4 C 8 1.8 6.2 0 4 0 Z"
                  fill={AP_TEXT}/>
                <circle cx="4" cy="4" r="1.4" fill={g2}/>
              </svg>
              <span>IP 属地 {persona.region}</span>
            </div>
          )}
        </div>

        {/* Header row — avatar + stats */}
        <div style={{
          padding: '0 12px', marginTop: -28, position: 'relative',
          display: 'flex', alignItems: 'flex-end',
        }}>
          <AuthorAvatar persona={persona} size={56} ring/>
          <div style={{ flex: 1, marginLeft: 4, display: 'flex',
            paddingBottom: 3, color: AP_TEXT }}>
            <Stat label="获赞"   value={fmtN(persona.stats.likes)}/>
            <Stat label="被关注" value={fmtN(persona.stats.followers)}/>
            <Stat label="关注"   value={fmtN(persona.stats.following)}/>
          </div>
        </div>

        {/* Name + credential + bio */}
        <div style={{ padding: '7px 12px 0' }}>
          <div style={{
            display: 'flex', alignItems: 'center', gap: 5,
            fontSize: 14, fontWeight: 700, color: AP_TEXT,
          }}>
            <span>{persona.name}</span>
            {persona.gender === 'm' && <GenderChip kind="m"/>}
            {persona.gender === 'f' && <GenderChip kind="f"/>}
          </div>

          {persona.credential === 'verified' && (
            <div style={{
              marginTop: 4, display: 'flex', alignItems: 'center', gap: 4,
              fontSize: 9.5, color: AP_BLUE,
            }}>
              <VerifiedTick color={AP_BLUE}/>
              <span>{persona.credentialText}</span>
            </div>
          )}
          {persona.credential === 'kol' && (
            <div style={{
              marginTop: 4, display: 'flex', alignItems: 'center', gap: 4,
              fontSize: 9.5, color: '#E8B47A',
            }}>
              <span>★ {persona.credentialText}</span>
            </div>
          )}

          <div style={{
            marginTop: 5, fontSize: 10, color: AP_TEXT, lineHeight: 1.5,
          }}>
            {persona.bio}
            <span style={{ color: AP_MUTED, marginLeft: 4 }}>更多 ›</span>
          </div>

          {persona.badges?.length > 0 && (
            <div style={{ marginTop: 6, display: 'flex', flexWrap: 'wrap', gap: 5 }}>
              {persona.badges.map((b, i) => (
                <div key={i} style={{
                  padding: '1.5px 7px', borderRadius: 9,
                  background: AP_CARD, fontSize: 8.5, color: '#E8B47A',
                }}>★ {b}</div>
              ))}
            </div>
          )}

          {/* Action buttons */}
          <div style={{ marginTop: 10, display: 'flex', gap: 7 }}>
            <div style={{
              flex: 1, height: 27, borderRadius: 14, background: AP_BLUE,
              color: '#fff', fontSize: 10.5, fontWeight: 600,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              cursor: 'pointer',
            }}>
              <span style={{ fontSize: 12, marginRight: 3 }}>+</span> 关注
            </div>
            <div style={{
              width: 85, height: 27, borderRadius: 14, background: AP_CARD,
              color: AP_TEXT, fontSize: 10.5,
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 3,
              cursor: 'pointer',
            }}>
              <span style={{ fontSize: 10 }}>✈</span> 发私信
            </div>
          </div>
        </div>

        {/* Main tabs */}
        <div style={{
          marginTop: 11, display: 'flex',
          borderBottom: `1px solid ${AP_DIVIDER}`,
        }}>
          {[
            ['create',   '创作'],
            ['activity', '动态'],
            ['agree',    '赞同'],
          ].map(([k, label]) => (
            <div key={k} onClick={() => setTab(k)} style={{
              flex: 1, textAlign: 'center', padding: '8px 0 7px',
              fontSize: 11, fontWeight: tab === k ? 700 : 400,
              color: tab === k ? AP_TEXT : AP_MUTED,
              position: 'relative', cursor: 'pointer',
            }}>
              {label}
              {tab === k && (
                <div style={{
                  position: 'absolute', bottom: 0, left: '50%',
                  transform: 'translateX(-50%)',
                  width: 16, height: 2.5, borderRadius: 2,
                  background: AP_BLUE,
                }}/>
              )}
            </div>
          ))}
        </div>

        {/* Sub-tabs (only on 创作) */}
        {tab === 'create' && (
          <div style={{
            display: 'flex', gap: 6, padding: '10px 14px 6px',
            overflowX: 'auto', scrollbarWidth: 'none',
          }}>
            <SubTabChip k="all"     label="全部" total={persona.stats.answers}
                       active={subTab === 'all'} onClick={() => setSubTab('all')}/>
            <SubTabChip k="answers" label="回答" count={persona.stats.answers}
                       active={subTab === 'answers'} onClick={() => setSubTab('answers')}/>
            <SubTabChip k="ideas"   label="想法" count={persona.stats.ideas}
                       active={subTab === 'ideas'} onClick={() => setSubTab('ideas')}/>
            <SubTabChip k="articles" label="文章" count={persona.stats.articles}
                       active={subTab === 'articles'} onClick={() => setSubTab('articles')}/>
            <SubTabChip k="columns" label="专栏" count={persona.stats.columns}
                       active={subTab === 'columns'} onClick={() => setSubTab('columns')}/>
            <SubTabChip k="asks"    label="提问" count={persona.stats.asks}
                       active={subTab === 'asks'} onClick={() => setSubTab('asks')}/>
          </div>
        )}

        {/* Body */}
        {tab === 'create' && (
          subTab === 'all' || subTab === 'answers' ? (
            <div>
              {shown.length === 0 ? (
                <EmptyState text="还没有回答"/>
              ) : (
                shown.map((a, i) => (
                  <AuthorAnswerCard key={a.id} persona={persona} answer={a}
                    onTap={() => onQuestionTap && onQuestionTap(a.qid)}
                    isLast={i === shown.length - 1}/>
                ))
              )}
            </div>
          ) : (
            <EmptyState text={subTab === 'ideas' && persona.stats.ideas > 0
              ? `${persona.stats.ideas} 条想法（演示版暂未展开）`
              : '暂无内容'}/>
          )
        )}

        {tab !== 'create' && (
          <EmptyState text="演示版暂未实现此分区"/>
        )}

        <div style={{ height: 60 }}/>
      </div>

      {/* Sticky bottom follow CTA */}
      <div style={{
        position: 'absolute', left: 0, right: 0, bottom: 0,
        background: AP_BG, borderTop: `1px solid ${AP_DIVIDER}`,
        padding: '7px 10px 16px', display: 'flex', alignItems: 'center', gap: 8,
      }}>
        <AuthorAvatar persona={persona} size={24}/>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 10, fontWeight: 600, color: AP_TEXT }}>{persona.name}</div>
          <div style={{ fontSize: 8.5, color: AP_MUTED, marginTop: 1 }}>关注他, 精彩内容抢先看</div>
        </div>
        <div style={{
          padding: '4px 12px', borderRadius: 12, background: AP_BLUE_SOFT,
          color: AP_BLUE, fontSize: 10, fontWeight: 600, cursor: 'pointer',
        }}>关注</div>
        <div style={{
          width: 16, height: 16, color: AP_MUTED, fontSize: 10,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          cursor: 'pointer',
        }}>✕</div>
      </div>
    </div>
  );
}

// ─── Sub-components ────────────────────────────────────────────────────
function Stat({ label, value }) {
  return (
    <div style={{ flex: 1, textAlign: 'center' }}>
      <div style={{ fontSize: 12.5, fontWeight: 700, color: AP_TEXT, lineHeight: 1.1 }}>{value}</div>
      <div style={{ fontSize: 8.5, color: AP_MUTED, marginTop: 2.5 }}>{label}</div>
    </div>
  );
}

function GenderChip({ kind }) {
  const isM = kind === 'm';
  return (
    <div style={{
      width: 13, height: 13, borderRadius: 7,
      background: isM ? '#3D6FB8' : '#C5577A',
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      fontSize: 8, color: '#fff',
    }}>{isM ? '♂' : '♀'}</div>
  );
}

function VerifiedTick({ color = '#1772F6' }) {
  return (
    <svg width="11" height="11" viewBox="0 0 12 12">
      <circle cx="6" cy="6" r="6" fill={color}/>
      <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 SubTabChip({ k, label, count, total, active, onClick }) {
  const text = count != null ? `${label} ${count}` : (total != null ? `${label}` : label);
  return (
    <div onClick={onClick} style={{
      flexShrink: 0, padding: '3px 10px', borderRadius: 12,
      background: active ? AP_TEXT : AP_CARD,
      color: active ? '#0E0F12' : AP_TEXT,
      fontSize: 9.5, fontWeight: active ? 700 : 400,
      cursor: 'pointer',
    }}>{text}</div>
  );
}

function EmptyState({ text }) {
  return (
    <div style={{
      padding: '40px 20px', textAlign: 'center',
      color: AP_MUTED, fontSize: 11,
    }}>{text}</div>
  );
}

function AuthorAvatar({ persona, size = 40, ring = false }) {
  const url = avatarUrl(persona, size * 2);
  return (
    <div style={{
      width: size, height: size, borderRadius: '50%',
      background: AP_CARD,
      border: ring ? '3px solid #0E0F12' : 'none',
      boxShadow: ring ? '0 2px 6px rgba(0,0,0,0.3)' : 'none',
      overflow: 'hidden', flexShrink: 0,
    }}>
      <img src={url} alt={persona.name} width={size} height={size}
        style={{ display: 'block', width: '100%', height: '100%' }}/>
    </div>
  );
}

function fmtN(n) {
  if (n == null) return '0';
  if (n >= 10000) return (n / 10000).toFixed(n >= 100000 ? 0 : 1) + '万';
  return n.toString();
}

// ─── Answer card on the profile page ────────────────────────────────────
function AuthorAnswerCard({ persona, answer, onTap, isLast }) {
  return (
    <div onClick={onTap} style={{
      padding: '8px 12px 10px', cursor: 'pointer',
      borderBottom: !isLast ? `6px solid #07080A` : `1px solid ${AP_DIVIDER}`,
    }}>
      <div style={{
        display: 'flex', alignItems: 'center', gap: 5, marginBottom: 5,
        fontSize: 8.5, color: AP_MUTED,
      }}>
        <AuthorAvatar persona={persona} size={16}/>
        <span style={{ color: AP_TEXT, fontWeight: 500 }}>{persona.name}</span>
        <span>·</span>
        <span>{relativeTime(answer.publishDate)} · 回答了问题</span>
      </div>

      <div style={{
        fontSize: 11, fontWeight: 700, color: AP_TEXT,
        lineHeight: 1.35,
      }}>{answer.qTitle}</div>

      <div style={{
        marginTop: 4, fontSize: 10, color: '#C8CCD2',
        lineHeight: 1.55,
        display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical',
        overflow: 'hidden',
      }}>{answer.body.split('\n')[0]}</div>

      <div style={{
        marginTop: 6, display: 'flex', alignItems: 'center',
        gap: 14, color: AP_MUTED, fontSize: 8.5,
      }}>
        <span>△ {fmtN(answer.voteUp)}</span>
        <span>☆ 收藏</span>
        <span>○ {fmtN(answer.commentCount)}</span>
        <div style={{ flex: 1 }}/>
        <span style={{ fontSize: 10 }}>⋯</span>
      </div>
    </div>
  );
}

function relativeTime(dateStr) {
  if (!dateStr) return '';
  // dateStr like '2024-08-15' — return a coarse relative; this is a demo so
  // we just compare year + month, never showing real "now"-dependent text.
  const [y, m] = dateStr.split('-');
  if (!y) return dateStr;
  const yy = parseInt(y, 10);
  if (yy <= 2023) return '1 年前';
  if (yy === 2024) return `${parseInt(m, 10)} 个月前`;
  return `${parseInt(m, 10) || 1} 天前`;
}

Object.assign(window, { AuthorProfile, AuthorAvatar, avatarUrl });
