/* ============================================================================
 * Wildy — 프로필 통계 (실제 카운트) + 닉네임 인라인 편집 + 통계 상세 모달
 * ----------------------------------------------------------------------------
 *   spec:
 *     - 닉네임 더블클릭 → 인라인 편집 (즉시 저장)
 *     - 통계 카드 더블클릭 → 상세 모달 (placeholder for now)
 *     - user_stats RPC로 게시물/별/미디어/팔로워/Wild 카운트 한번에
 *     - 별을 상단에 강조 (Twitter 인기도 스타일)
 *
 *   사용:
 *     <window.WildyComponents.ProfileStats
 *        supabaseClient={...}
 *        user={user}
 *        editable={isOwn}
 *        onNicknameChanged={(n) => setNickname(n)}   // 인라인 편집 후 부모 알림
 *     />
 *
 *   글로벌 노출:
 *     window.WildyComponents.ProfileStats
 *     window.WildyComponents.NicknameInlineEdit
 *     window.WildyComponents.StatsDetailModal
 * ========================================================================= */
(function (global) {
  'use strict';

  if (typeof React === 'undefined') {
    console.error('[profile-stats.jsx] React not loaded');
    return;
  }
  const { useState, useEffect, useRef } = React;

  function withTimeout(promise, ms, fallback) {
    return Promise.race([
      promise,
      new Promise(resolve => setTimeout(() => resolve(fallback), ms)),
    ]);
  }

  // ───────────────────────────────────────────────────────────
  // NicknameInlineEdit — 더블클릭 → input → 즉시 저장
  // ───────────────────────────────────────────────────────────
  function NicknameInlineEdit({ supabaseClient, user, value, editable, onChanged, className }) {
    const [editing, setEditing] = useState(false);
    const [draft, setDraft] = useState(value || '');
    const [busy, setBusy] = useState(false);
    const inputRef = useRef(null);

    useEffect(() => { setDraft(value || ''); }, [value]);
    useEffect(() => {
      if (editing && inputRef.current) {
        inputRef.current.focus();
        inputRef.current.select();
      }
    }, [editing]);

    const save = async () => {
      const next = (draft || '').trim();
      if (!next) { setEditing(false); setDraft(value || ''); return; }
      if (next === value) { setEditing(false); return; }
      if (next.length > 30) { alert('닉네임은 30자 이하로'); return; }

      if (!supabaseClient || !user?.id) {
        // 데모 — 로컬만 변경
        onChanged && onChanged(next);
        setEditing(false);
        return;
      }
      setBusy(true);
      try {
        const { error } = await supabaseClient.rpc('update_display_name', {
          p_user_id: user.id,
          p_display_name: next,
        });
        if (error) throw error;
        onChanged && onChanged(next);
        setEditing(false);
      } catch (e) {
        console.error('[NicknameInlineEdit] save', e);
        alert('닉네임 저장 실패: ' + (e?.message || ''));
      } finally { setBusy(false); }
    };

    const cancel = () => { setDraft(value || ''); setEditing(false); };
    const onKey = (e) => {
      if (e.key === 'Enter') { e.preventDefault(); save(); }
      else if (e.key === 'Escape') { cancel(); }
    };

    if (editing) {
      return (
        <input
          ref={inputRef}
          value={draft}
          onChange={(e) => setDraft(e.target.value)}
          onBlur={save}
          onKeyDown={onKey}
          disabled={busy}
          maxLength={30}
          className={className + ' bg-sky-50 border-2 border-sky-300 rounded-lg px-2 py-0.5 outline-none'}
        />
      );
    }

    return (
      <span
        onDoubleClick={() => editable && setEditing(true)}
        className={className + (editable ? ' cursor-text hover:bg-sky-50 rounded-lg px-1' : '')}
        title={editable ? '더블클릭으로 닉네임 편집' : ''}
      >
        {value || 'Wilder'}
      </span>
    );
  }

  // ───────────────────────────────────────────────────────────
  // StatsDetailModal — 통계 카드 더블클릭 시 표시 (간단 placeholder)
  // ───────────────────────────────────────────────────────────
  function StatsDetailModal({ kind, stats, onClose, onNavigate }) {
    if (!kind) return null;
    const labels = {
      level:    { icon: '⭐', title: '레벨', sub: '다음 레벨까지 진행도', body: 'Lv. 7 — 다음까지 320 XP', detail: 'XP 시스템은 Phase 2D에서 활성화될 예정이에요.' },
      points:   { icon: '💎', title: 'Wildy 포인트', sub: '활동 보상', body: '1,284 P', detail: '포인트 이력은 Phase 2D에서 공개돼요.' },
      guild:    { icon: '🏰', title: '참여 Wild', sub: '팔로우 중', body: `${stats?.wild_count || 0}개`, detail: 'Wilds 탭에서 관리할 수 있어요.', cta: { label: 'Wild 보러가기', target: 'wilds' } },
      party:    { icon: '🎮', title: '진행 중 파티', sub: '실시간', body: '2팀', detail: '파티 관리는 Phase 2A에서 활성화돼요.' },
      stars:    { icon: '✦', title: '받은 Sparkle', sub: '인기도', body: `${stats?.star_received || 0}개`, detail: '게시물에 받은 ✦ Sparkle 합계예요.' },
      posts:    { icon: '📝', title: '게시물', sub: '본인 작성', body: `${stats?.post_count || 0}개`, detail: '본인 작성한 게시물 수.' },
    };
    const it = labels[kind] || labels.level;
    return (
      <div className="fixed inset-0 z-[130] flex items-center justify-center bg-black/40 px-5" onClick={onClose}>
        <div className="w-full max-w-sm rounded-3xl bg-white p-6 shadow-2xl" onClick={(e) => e.stopPropagation()}>
          <div className="text-4xl mb-2">{it.icon}</div>
          <h3 className="font-display text-xl font-black text-wildy-ink">{it.title}</h3>
          <p className="mt-1 text-xs text-slate-500">{it.sub}</p>
          <div className="mt-4 text-3xl font-black text-wildy-deep">{it.body}</div>
          <p className="mt-3 text-sm text-slate-600" style={{ wordBreak: 'keep-all' }}>{it.detail}</p>
          <div className="mt-5 grid gap-2">
            {it.cta && (
              <button onClick={() => { onClose(); onNavigate && onNavigate(it.cta.target); }} className="w-full rounded-full bg-wildy-ink py-2.5 text-sm font-bold text-white">{it.cta.label}</button>
            )}
            <button onClick={onClose} className="w-full rounded-full border-2 border-slate-200 py-2.5 text-sm font-bold text-slate-600">닫기</button>
          </div>
        </div>
      </div>
    );
  }

  // ───────────────────────────────────────────────────────────
  // ProfileStats — 메인 컴포넌트
  // ───────────────────────────────────────────────────────────
  function ProfileStats({ supabaseClient, user, editable, onNicknameChanged, onNavigate }) {
    const [stats, setStats] = useState({ post_count: 0, media_count: 0, star_received: 0, follower_count: 0, following_count: 0, wild_count: 0, tag_count: 0 });
    const [modalKind, setModalKind] = useState(null);
    const [username, setUsername] = useState(user?.username || null);

    useEffect(() => {
      if (!supabaseClient || !user?.id) return;
      let active = true;
      (async () => {
        try {
          const [statsRes, profileRes] = await Promise.allSettled([
            withTimeout(supabaseClient.rpc('user_stats', { p_user_id: user.id }), 7000, { data: null }),
            withTimeout(supabaseClient.from('users').select('username').eq('id', user.id).maybeSingle(), 3500, { data: null }),
          ]);
          if (!active) return;
          const statsValue = statsRes.status === 'fulfilled' ? statsRes.value : {};
          const profileValue = profileRes.status === 'fulfilled' ? profileRes.value : {};
          if (statsValue.data) setStats(statsValue.data);
          if (profileValue.data?.username) setUsername(profileValue.data.username);
        } catch (e) {
          console.warn('[ProfileStats] load fail', e.message);
        }
      })();
      return () => { active = false; };
    }, [supabaseClient, user?.id]);

    return (
      <>
        {/* 헤더 — 닉네임 + @핸들 + 별 강조 */}
        <div className="flex items-end gap-3 flex-wrap">
          <div className="flex flex-col">
            <NicknameInlineEdit
              supabaseClient={supabaseClient}
              user={user}
              value={user?.display_name || user?.nickname}
              editable={editable}
              onChanged={onNicknameChanged}
              className="font-display text-3xl font-black text-wildy-ink"
            />
            {/* @핸들 — 영구 식별자, @멘션용 */}
            {username && (
              <span className="mt-0.5 text-sm text-slate-500">@{username}</span>
            )}
          </div>
          {/* ✦ 받은 Sparkle (Twitter 인기도 스타일) */}
          {stats.star_received > 0 && (
            <button
              onDoubleClick={() => setModalKind('stars')}
              className="flex items-center gap-1 rounded-full bg-amber-100 px-3 py-1 text-sm font-bold text-amber-800 self-center"
              title="받은 Sparkle (더블클릭으로 상세)"
            >
              <span>✦</span>
              <span>{stats.star_received.toLocaleString('ko-KR')}</span>
            </button>
          )}
        </div>

        {/* 통계 카드 4개 — 게시물 / Sparkle / Wild / 미디어 */}
        <div className="mt-4 grid grid-cols-2 sm:grid-cols-4 gap-2">
          <StatCard label="게시물" value={stats.post_count} icon="📝" onDoubleClick={() => setModalKind('posts')} />
          <StatCard label="받은 Sparkle" value={stats.star_received} icon="✦" onDoubleClick={() => setModalKind('stars')} />
          <StatCard label="참여 Wild" value={stats.wild_count} icon="🏰" onDoubleClick={() => setModalKind('guild')} />
          <StatCard label="미디어" value={stats.media_count} icon="🖼️" onDoubleClick={() => setModalKind('posts')} />
        </div>

        <StatsDetailModal kind={modalKind} stats={stats} onClose={() => setModalKind(null)} onNavigate={onNavigate} />
      </>
    );
  }

  function StatCard({ label, value, icon, onDoubleClick }) {
    return (
      <div
        onDoubleClick={onDoubleClick}
        className="rounded-2xl border border-sky-100 bg-white p-3 cursor-pointer hover:border-sky-200 transition"
        title="더블클릭으로 상세"
      >
        <div className="text-xs text-slate-500 flex items-center gap-1">
          <span>{icon}</span><span>{label}</span>
        </div>
        <div className="mt-1 font-display text-xl font-black text-wildy-ink">
          {(value || 0).toLocaleString('ko-KR')}
        </div>
      </div>
    );
  }

  global.WildyComponents = global.WildyComponents || {};
  global.WildyComponents.ProfileStats = ProfileStats;
  global.WildyComponents.NicknameInlineEdit = NicknameInlineEdit;
  global.WildyComponents.StatsDetailModal = StatsDetailModal;
})(typeof window !== 'undefined' ? window : globalThis);
