// KolProfile — KOL 公开主页抽屉 v2
// 布局：头像 + 社交 + 关注 → 直播入口 → 社区互动（单页滚动）
const sb = window.supabaseClient;

const PLATFORM_LIVE_URLS = {
  binance: 'https://www.binance.com/en/live',
  okx:     'https://www.okx.com/web3/live',
  gate:    'https://www.gate.com/zh/live',
  bybit:   'https://www.bybit.com/en/live',
};

const PLATFORMS_META = {
  binance: { name: 'Binance Live', color: '#F3BA2F',
    icon: <svg viewBox="0 0 24 24" fill="none" width="18" height="18"><path d="M12 3l3 3-3 3-3-3 3-3zM6 9l3 3-3 3-3-3 3-3zM18 9l3 3-3 3-3-3 3-3zM12 15l3 3-3 3-3-3 3-3z" fill="currentColor"/></svg> },
  okx:     { name: 'OKX Live',    color: '#FFFFFF',
    icon: <svg viewBox="0 0 24 24" fill="none" width="18" height="18"><rect x="3" y="3" width="6" height="6" fill="currentColor"/><rect x="15" y="3" width="6" height="6" fill="currentColor"/><rect x="9" y="9" width="6" height="6" fill="currentColor"/><rect x="3" y="15" width="6" height="6" fill="currentColor"/><rect x="15" y="15" width="6" height="6" fill="currentColor"/></svg> },
  gate:    { name: 'Gate.io Live', color: '#2354E6',
    icon: <svg viewBox="0 0 24 24" fill="none" width="18" height="18"><circle cx="12" cy="12" r="9" stroke="currentColor" strokeWidth="1.8"/><path d="M16 12h5" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"/></svg> },
  bybit:   { name: 'Bybit Live',  color: '#F7A600',
    icon: <svg viewBox="0 0 24 24" fill="none" width="18" height="18"><path d="M4 4h7a4 4 0 0 1 0 8H4V4z" stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round"/><path d="M4 12h8a4 4 0 0 1 0 8H4v-8z" stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round"/></svg> },
};

function SocialIcon({ type }) {
  switch (type) {
    case 'x': case 'twitter': return (
      <svg width="13" height="13" viewBox="0 0 24 24" fill="currentColor">
        <path d="M18.244 2H21l-6.55 7.49L22 22h-6.79l-4.74-6.2L4.96 22H2.2l7.02-8.02L2 2h6.96l4.28 5.66L18.244 2zm-1.18 18h1.86L7.06 4H5.1l11.964 16z"/>
      </svg>
    );
    case 'telegram': return (
      <svg width="13" height="13" viewBox="0 0 24 24" fill="currentColor">
        <path d="M21.5 3.5L2.6 11.2c-1 .4-1 1.4 0 1.7l4.7 1.5 1.8 5.7c.2.7.6.9 1.2.5l2.7-2.1 4.6 3.4c.9.5 1.5.2 1.7-.8l3.1-14.7c.3-1.4-.5-2-1.9-1.4z"/>
      </svg>
    );
    case 'youtube': return (
      <svg width="13" height="13" viewBox="0 0 24 24" fill="currentColor">
        <path d="M23 7s-.3-2-1.2-2.8c-1.1-1.2-2.4-1.2-3-1.3C16.6 2.8 12 2.8 12 2.8s-4.6 0-6.8.1C4.6 3 3.3 3 2.2 4.2 1.3 5 1 7 1 7S.7 9.3.7 11.5v2.1c0 2.2.3 4.4.3 4.4s.3 2 1.2 2.8c1.1 1.2 2.6 1.1 3.3 1.2C7.6 22.2 12 22.2 12 22.2s4.6 0 6.8-.2c.6-.1 1.9-.1 3-1.3.9-.8 1.2-2.8 1.2-2.8s.3-2.2.3-4.4v-2.1C23.3 9.3 23 7 23 7zM9.7 15.5V8.4l8.1 3.6-8.1 3.5z"/>
      </svg>
    );
    case 'twitch': return (
      <svg width="13" height="13" viewBox="0 0 24 24" fill="currentColor">
        <path d="M11.571 4.714h1.715v5.143H11.57zm4.715 0H18v5.143h-1.714zM6 0L1.714 4.286v15.428h5.143V24l4.286-4.286h3.428L22.286 12V0zm14.571 11.143l-3.428 3.428h-3.429l-3 3v-3H6.857V1.714h13.714z"/>
      </svg>
    );
    default: return (
      <svg width="13" height="13" viewBox="0 0 24 24" fill="none">
        <circle cx="12" cy="12" r="9" stroke="currentColor" strokeWidth="1.6"/>
        <path d="M2 12h20M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z" stroke="currentColor" strokeWidth="1.6"/>
      </svg>
    );
  }
}

function guessPlatformType(url, key) {
  if (key) {
    if (['x', 'twitter'].includes(key)) return 'x';
    if (key === 'telegram') return 'telegram';
    if (key === 'youtube') return 'youtube';
    if (key === 'twitch') return 'twitch';
  }
  const u = (url || '').toLowerCase();
  if (u.includes('x.com') || u.includes('twitter.com')) return 'x';
  if (u.includes('t.me') || u.includes('telegram')) return 'telegram';
  if (u.includes('youtube')) return 'youtube';
  if (u.includes('twitch')) return 'twitch';
  return 'link';
}

function timeAgoKol(dateStr) {
  if (!dateStr) return '';
  const diff = Date.now() - new Date(dateStr).getTime();
  const mins = Math.floor(diff / 60000);
  if (mins < 1) return '刚刚';
  if (mins < 60) return `${mins}m`;
  const h = Math.floor(mins / 60);
  if (h < 24) return `${h}h`;
  return `${Math.floor(h / 24)}d`;
}

function fmtCount(n) {
  if (n >= 10000) return (n / 10000).toFixed(1) + 'W';
  if (n >= 1000) return (n / 1000).toFixed(1) + 'K';
  return String(n);
}

// ── 关注状态 Hook ─────────────────────────────────────────────────
function useFollowState(kolName) {
  const { user } = useGlobalAuth();
  const [following, setFollowing] = React.useState(false);
  const [count, setCount] = React.useState(0);
  const [loading, setLoading] = React.useState(true);

  React.useEffect(() => {
    let mounted = true;
    const tasks = [
      sb.from('kol_follows').select('*', { count: 'exact', head: true }).eq('kol_name', kolName),
      user
        ? sb.from('kol_follows').select('id').eq('kol_name', kolName).eq('user_id', user.id).maybeSingle()
        : Promise.resolve({ data: null }),
    ];
    Promise.all(tasks).then(([countRes, followRes]) => {
      if (!mounted) return;
      setCount(countRes.count || 0);
      setFollowing(!!followRes.data);
      setLoading(false);
    }).catch(() => { if (mounted) setLoading(false); });
    return () => { mounted = false; };
  }, [kolName, user && user.id]);

  const toggle = async () => {
    if (loading || !user) return;
    setLoading(true);
    try {
      if (following) {
        await sb.from('kol_follows').delete().eq('kol_name', kolName).eq('user_id', user.id);
        setFollowing(false);
        setCount(c => Math.max(0, c - 1));
      } else {
        await sb.from('kol_follows').insert({ kol_name: kolName, user_id: user.id });
        setFollowing(true);
        setCount(c => c + 1);
      }
    } catch (e) { console.error(e); }
    setLoading(false);
  };

  return { following, count, loading, toggle };
}

// ── 社区互动区块 ──────────────────────────────────────────────────
function CommunitySection({ kol }) {
  const [questions, setQuestions] = React.useState([]);
  const [comments, setComments] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [subtab, setSubtab] = React.useState('questions');

  React.useEffect(() => {
    setLoading(true);
    // 优先用 user_id 查询，确保昵称变更后仍能匹配
    const uid = kol.userId;
    const qQuery = uid
      ? sb.from('questions').select('id, title, tag, solved, created_at').eq('user_id', uid)
      : sb.from('questions').select('id, title, tag, solved, created_at').eq('author_name', kol.name);
    const cQuery = uid
      ? sb.from('comments').select('id, body, created_at, questions(title)').eq('user_id', uid)
      : sb.from('comments').select('id, body, created_at, questions(title)').eq('author_name', kol.name);
    Promise.all([
      qQuery.order('created_at', { ascending: false }).limit(10),
      cQuery.order('created_at', { ascending: false }).limit(10),
    ]).then(([qRes, cRes]) => {
      setQuestions(qRes.data || []);
      setComments(cRes.data || []);
    }).catch(() => {}).finally(() => setLoading(false));
  }, [kol.userId, kol.name]);

  const EmptyState = ({ text }) => (
    <div className="flex flex-col items-center py-10 text-center">
      <div className="w-10 h-10 rounded-full bg-white/[0.03] border border-white/[0.06] flex items-center justify-center mb-3">
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" className="text-white/20">
          <path d="M21 12c0 4-4 7-9 7-1.5 0-2.9-.3-4.2-.8L3 20l1-4.2A7.2 7.2 0 0 1 3 12c0-4 4-7 9-7s9 3 9 7z" stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round"/>
        </svg>
      </div>
      <p className="text-[12.5px] text-white/30">{text}</p>
    </div>
  );

  return (
    <div>
      <div className="text-[10.5px] text-white/35 font-mono tracking-[0.14em] uppercase mb-3">社区互动</div>
      <div className="flex items-center gap-0.5 p-1 rounded-lg bg-white/[0.03] border border-white/[0.05] inline-flex mb-4">
        {[
          { id: 'questions', label: '提问', count: questions.length },
          { id: 'comments',  label: '回答', count: comments.length },
        ].map(t => (
          <button
            key={t.id}
            onClick={() => setSubtab(t.id)}
            className={`h-7 px-3 rounded-md text-[12px] font-medium transition-colors ${
              subtab === t.id
                ? 'bg-[#0A1512] text-white shadow-[inset_0_0_0_1px_rgba(16,185,129,0.2)]'
                : 'text-white/40 hover:text-white/70'
            }`}
          >
            {t.label}
            <span className={`ml-1 text-[10px] font-mono ${subtab === t.id ? 'text-emerald-300/80' : 'text-white/25'}`}>
              {t.count}
            </span>
          </button>
        ))}
      </div>

      {loading ? (
        <div className="flex justify-center py-8">
          <svg className="animate-spin text-emerald-400/50" width="20" height="20" viewBox="0 0 24 24" fill="none">
            <circle cx="12" cy="12" r="9" stroke="currentColor" strokeWidth="2.5" opacity="0.25"/>
            <path d="M21 12a9 9 0 0 0-9-9" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"/>
          </svg>
        </div>
      ) : subtab === 'questions' ? (
        questions.length === 0 ? <EmptyState text="暂无提问记录" /> : (
          <div className="space-y-2">
            {questions.map(q => (
              <div key={q.id} className="flex items-center gap-3 p-3 rounded-xl bg-[#0F1E1A] border border-white/[0.04]">
                <span className={`shrink-0 text-[10px] font-mono px-1.5 py-0.5 rounded ${q.solved ? 'bg-emerald-400/10 text-emerald-300' : 'bg-white/[0.05] text-white/40'}`}>
                  {q.solved ? '已解决' : q.tag || '通用'}
                </span>
                <span className="flex-1 text-[13px] text-white/80 truncate">{q.title}</span>
                <span className="shrink-0 text-[10.5px] text-white/25 font-mono">{timeAgoKol(q.created_at)}</span>
              </div>
            ))}
          </div>
        )
      ) : (
        comments.length === 0 ? <EmptyState text="暂无回答记录" /> : (
          <div className="space-y-2">
            {comments.map(c => (
              <div key={c.id} className="p-3 rounded-xl bg-[#0F1E1A] border border-white/[0.04]">
                {c.questions?.title && (
                  <div className="text-[10.5px] text-white/30 font-mono mb-1 truncate">↳ {c.questions.title}</div>
                )}
                <div className="flex items-center justify-between gap-2">
                  <p className="text-[13px] text-white/75 leading-relaxed line-clamp-2">{c.body}</p>
                  <span className="shrink-0 text-[10.5px] text-white/25 font-mono">{timeAgoKol(c.created_at)}</span>
                </div>
              </div>
            ))}
          </div>
        )
      )}
    </div>
  );
}

// ── 主组件 ────────────────────────────────────────────────────────
function KolProfileModal({ kol, onClose }) {
  const { user } = useGlobalAuth();
  const { following, count, loading: followLoading, toggle } = useFollowState(kol.name);

  const handleFollow = () => {
    if (!user) {
      const lang = window.__kiwvoLang || localStorage.getItem('kiwvo.lang') || 'zh';
      window.__authPromptMsg = lang === 'en' ? 'Welcome to join the Kiwvo community!' : '欢迎加入 Kiwvo 社区！';
      document.querySelector('[data-auth-trigger]')?.click();
      return;
    }
    toggle();
  };

  // ESC 关闭
  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [onClose]);

  // 阻止背景滚动
  React.useEffect(() => {
    document.body.style.overflow = 'hidden';
    return () => { document.body.style.overflow = ''; };
  }, []);

  // 整理社交链接
  const socialLinks = [];
  if (kol.social?.x) socialLinks.push({ type: 'x', label: 'X', url: kol.social.x });
  if (kol.social?.telegram) {
    const tg = kol.social.telegram;
    socialLinks.push({ type: 'telegram', label: 'Telegram', url: tg.startsWith('http') ? tg : `https://t.me/${tg.replace('@', '')}` });
  }
  if (kol.social?.links) {
    kol.social.links.forEach(l => socialLinks.push({
      type: guessPlatformType(l.url, l.key),
      label: l.platform || l.label || l.key || 'Link',
      url: l.url,
    }));
  }

  return (
    <div
      className="fixed inset-0 z-[200] flex items-stretch"
      style={{ background: 'rgba(5,18,15,0.7)', backdropFilter: 'blur(8px)' }}
      onClick={onClose}
    >
      <div
        className="ml-auto w-full max-w-[520px] h-full bg-[#0A1512] border-l border-white/[0.06] flex flex-col animate-[slideInRight_0.22s_cubic-bezier(0.22,1,0.36,1)]"
        onClick={e => e.stopPropagation()}
      >
        {/* ── 头部区域 ───────────────────────────────────────────── */}
        <div className="px-6 pt-5 pb-5 border-b border-white/[0.06] shrink-0">

          {/* 顶栏：关闭 + 关注按钮 */}
          <div className="flex items-center justify-between mb-5">
            <button
              onClick={onClose}
              className="w-8 h-8 rounded-lg border border-white/[0.07] text-white/40 hover:text-white hover:border-white/20 flex items-center justify-center transition-all"
            >
              <svg width="13" height="13" viewBox="0 0 24 24" fill="none">
                <path d="M18 6L6 18M6 6l12 12" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/>
              </svg>
            </button>

            <button
              onClick={handleFollow}
              disabled={followLoading}
              className={`h-8 px-4 rounded-lg text-[12.5px] font-semibold transition-all inline-flex items-center gap-1.5 ${
                following
                  ? 'bg-white/[0.06] border border-white/[0.12] text-white/60 hover:bg-rose-500/10 hover:border-rose-400/30 hover:text-rose-300'
                  : 'bg-emerald-500 hover:bg-emerald-400 text-[#052E21] shadow-[0_2px_14px_-3px_rgba(16,185,129,0.5)]'
              } ${followLoading ? 'opacity-40 cursor-not-allowed' : ''}`}
            >
              {following ? (
                <>
                  <svg width="11" height="11" viewBox="0 0 24 24" fill="none">
                    <path d="M5 12.5l4.5 4.5L19 7.5" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"/>
                  </svg>
                  已关注
                </>
              ) : (
                <>
                  <svg width="10" height="10" viewBox="0 0 24 24" fill="none">
                    <path d="M12 5v14M5 12h14" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"/>
                  </svg>
                  关注
                </>
              )}
            </button>
          </div>

          {/* 头像 + 名字 + 社交 */}
          <div className="flex items-start gap-4">
            <div
              className="w-[68px] h-[68px] rounded-full flex items-center justify-center text-[22px] font-semibold text-emerald-100 shrink-0 ring-2 ring-emerald-400/20 overflow-hidden"
              style={{ background: kol.avatarUrl ? 'transparent' : `oklch(0.32 0.08 ${kol.hue})` }}
            >
              {kol.avatarUrl
                ? <img src={kol.avatarUrl} alt="" className="w-full h-full object-cover" />
                : kol.name.slice(0, 1).toUpperCase()
              }
            </div>

            <div className="flex-1 min-w-0 pt-1">
              <div className="flex items-center gap-3 mb-0.5">
                <h2 className="text-[18px] text-white font-semibold tracking-tight truncate">{kol.name}</h2>
                {kol.platforms?.length > 0 && (
                  <span className="inline-flex items-center gap-1 text-[9px] font-mono tracking-[0.2em] text-emerald-300 shrink-0">
                    <span className="relative flex h-1.5 w-1.5">
                      <span className="absolute inset-0 rounded-full bg-emerald-400 animate-ping" />
                      <span className="relative rounded-full h-1.5 w-1.5 bg-emerald-400" />
                    </span>
                    LIVE
                  </span>
                )}
                <span className="text-[12px] text-white/40 font-mono">·</span>
                <span className="text-[13px] text-white/60 font-mono tabular-nums">{followLoading ? '–' : fmtCount(count)}</span>
                <span className="text-[11px] text-white/35">关注</span>
              </div>
              {kol.topic && <p className="text-[12.5px] text-white/45 mb-3 truncate">{kol.topic}</p>}

              {/* 社交媒体 pills */}
              {socialLinks.length > 0 && (
                <div className="flex flex-wrap gap-1.5">
                  {socialLinks.map((l, i) => (
                    <a
                      key={i}
                      href={l.url}
                      target="_blank"
                      rel="noreferrer noopener"
                      onClick={e => e.stopPropagation()}
                      className="group inline-flex items-center gap-1.5 h-7 px-2.5 rounded-full bg-white/[0.05] border border-white/[0.08] hover:bg-emerald-400/[0.08] hover:border-emerald-400/30 text-[11.5px] text-white/55 hover:text-emerald-200 transition-all"
                    >
                      <span className="text-white/35 group-hover:text-emerald-300 transition-colors">
                        <SocialIcon type={l.type} />
                      </span>
                      {l.label}
                    </a>
                  ))}
                </div>
              )}
            </div>
          </div>

          {/* 统计数据行 */}
          {(kol.tier > 0 || kol.platforms?.length > 0) && (
          <div className="flex items-center gap-5 mt-5">
            {kol.tier > 0 && (
              <div>
                <div className="flex items-center gap-1 text-emerald-300 leading-tight">
                  <svg width="11" height="11" viewBox="0 0 24 24" fill="currentColor">
                    <path d="M12 2l1.4 3.8 4 .3-3 2.7 1 3.9L12 10.6 8.6 12.7l1-3.9-3-2.7 4-.3L12 2z"/>
                  </svg>
                  <span className="text-[16px] font-semibold font-mono tabular-nums">+{kol.tier}</span>
                </div>
                <div className="text-[10px] text-white/35 font-mono tracking-wide uppercase mt-0.5">贡献值</div>
              </div>
            )}

            {kol.tier > 0 && kol.platforms?.length > 0 && (
              <div className="w-px h-7 bg-white/[0.07]" />
            )}

            {kol.platforms?.length > 0 && (
              <div>
                <div className="text-[16px] text-white font-semibold font-mono tabular-nums leading-tight">
                  {kol.platforms.length}×
                </div>
                <div className="text-[10px] text-white/35 font-mono tracking-wide uppercase mt-0.5">同播</div>
              </div>
            )}
          </div>
          )}
        </div>

        {/* ── 可滚动内容区 ───────────────────────────────────────── */}
        <div className="flex-1 overflow-y-auto no-scrollbar">

          {/* 正在直播 */}
          {kol.platforms?.length > 0 && (
          <div className="px-6 pt-5 pb-4">
            <div className="text-[10.5px] text-white/35 font-mono tracking-[0.14em] uppercase mb-3">正在直播</div>
            <div className="space-y-2">
              {kol.platforms.map(raw => {
                const pid = typeof raw === 'string' ? raw : raw?.key;
                if (!pid) return null;
                const p = PLATFORMS_META[pid];
                const url = (kol.streamUrls && kol.streamUrls[pid]) || PLATFORM_LIVE_URLS[pid];
                return (
                  <a
                    key={pid}
                    href={url}
                    target="_blank"
                    rel="noreferrer noopener"
                    onClick={e => {
                      e.stopPropagation();
                      if (url && window.kiwvoTrackRoomClick) {
                        window.kiwvoTrackRoomClick({ kolUserId: kol.userId, platform: pid, sessionId: kol.sessionId, sessionStartedAt: kol.startedAt });
                      }
                    }}
                    className="group flex items-center gap-3 p-3 rounded-xl bg-[#0F1E1A] border border-white/[0.05] hover:border-emerald-400/30 hover:bg-emerald-400/[0.04] transition-all"
                  >
                    <div
                      className="w-9 h-9 rounded-lg flex items-center justify-center shrink-0"
                      style={{ background: p.color + '18', color: p.color }}
                    >
                      {p.icon}
                    </div>
                    <div className="flex-1 min-w-0">
                      <div className="text-[13.5px] text-white font-medium group-hover:text-emerald-200 transition-colors">{p.name}</div>
                      <div className="flex items-center gap-1.5 text-[11px] text-white/40 font-mono mt-0.5">
                        <span className="relative flex h-1.5 w-1.5">
                          <span className="absolute inset-0 rounded-full bg-emerald-400 animate-ping" />
                          <span className="relative rounded-full h-1.5 w-1.5 bg-emerald-400" />
                        </span>
                        LIVE
                      </div>
                    </div>
                    <span className="shrink-0 inline-flex items-center gap-1 h-7 px-3 rounded-lg bg-emerald-500/15 border border-emerald-400/25 text-[11.5px] font-medium text-emerald-300 group-hover:bg-emerald-500 group-hover:border-emerald-500 group-hover:text-[#052E21] transition-all">
                      看直播
                      <svg width="10" height="10" viewBox="0 0 24 24" fill="none">
                        <path d="M7 17L17 7M7 7h10v10" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/>
                      </svg>
                    </span>
                  </a>
                );
              })}
            </div>
          </div>
          )}

          {/* 分隔线 */}
          <div className="h-px bg-white/[0.04] mx-6" />

          {/* 社区互动 */}
          <div className="px-6 pt-5 pb-8">
            <CommunitySection kol={kol} />
          </div>
        </div>
      </div>
    </div>
  );
}

window.KolProfileModal = KolProfileModal;
