/* ============================================================================
 * Wildy — "내 Wild" 관리 화면 (Phase 1B-M)
 * ----------------------------------------------------------------------------
 *   spec Section 8.6 — 프로필 → 내 Wild 메뉴
 *   - 현재 follow한 Wild 목록 (카드)
 *   - 각 카드 [팔로우 취소] 버튼
 *   - [+ Wild 추가] 버튼 → 게임 검색 후 follow (source='manual')
 *
 *   사용:
 *     <window.WildyComponents.MyWildsScreen
 *        supabaseClient={supabaseClient}
 *        user={user}
 *        lang="ko"
 *        onBack={() => setView('profile')}
 *        onOpenWild={(wildId) => setView('wild-detail', wildId)}
 *     />
 *
 *   글로벌 노출:
 *     window.WildyComponents.MyWildsScreen
 *     window.WildyComponents.AddWildSheet  (재사용 가능)
 * ========================================================================= */
(function (global) {
  'use strict';

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

  function localize(g, lang) {
    if (!g) return '';
    if (lang === 'en' && g.title_en) return g.title_en;
    if (lang === 'ja' && g.title_ja) return g.title_ja;
    if (lang === 'zh' && g.title_zh) return g.title_zh;
    if (lang === 'id' && g.title_id) return g.title_id;
    return g.name;
  }

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

  // ───────────────────────────────────────────────────────────
  // AddWildSheet — 게임 검색 + 추가 모달
  // ───────────────────────────────────────────────────────────
  function AddWildSheet({ supabaseClient, user, lang, excludeIds = [], onClose, onAdded }) {
    const [games, setGames] = useState([]);
    const [search, setSearch] = useState('');
    const [loading, setLoading] = useState(true);
    const [addingId, setAddingId] = useState('');
    const [error, setError] = useState('');

    useEffect(() => {
      if (!supabaseClient) { setLoading(false); return; }
      let active = true;
      (async () => {
        try {
          const { data } = await withTimeout(
            supabaseClient
              .from('wilds')
              .select('id,name,short_name,emoji,category,title_en,title_ja,title_zh,title_id,icon_url,short_description,member_count')
              .eq('is_curated', true)
              .order('rank_in_discover', { ascending: true }),
            7000,
            { data: [] }
          );
          if (active) setGames(data || []);
        } catch (e) {
          if (active) setError('게임 목록 로딩 실패');
        } finally {
          if (active) setLoading(false);
        }
      })();
      return () => { active = false; };
    }, [supabaseClient]);

    const excludeSet = useMemo(() => new Set(excludeIds), [excludeIds]);

    const filtered = useMemo(() => {
      const q = search.toLowerCase().trim();
      return games
        .filter(g => !excludeSet.has(g.id))
        .filter(g => !q || (g.name || '').toLowerCase().includes(q) || (g.title_en || '').toLowerCase().includes(q));
    }, [games, search, excludeSet]);

    const add = async (wildId) => {
      if (addingId) return;
      setAddingId(wildId);
      setError('');
      try {
        if (supabaseClient && user?.id) {
          const { error: e } = await supabaseClient
            .from('wild_subscriptions')
            .insert({ user_id: user.id, wild_id: wildId, source: 'manual' });
          if (e && !String(e.message || '').includes('duplicate')) throw e;
        }
        onAdded && onAdded(wildId);
      } catch (e) {
        setError(e?.message || '추가 실패');
      } finally {
        setAddingId('');
      }
    };

    return (
      <div className="fixed inset-0 z-[110] flex flex-col bg-white" style={{ maxWidth: 480, margin: '0 auto' }}>
        <div className="sticky top-0 bg-white z-10 px-5 py-3 border-b border-slate-100 flex items-center justify-between">
          <h3 className="font-display text-lg font-black text-wildy-ink">Wild 추가</h3>
          <button onClick={onClose} className="text-sm text-slate-500">닫기</button>
        </div>
        <div className="px-5 pt-3 pb-2">
          <input
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            placeholder="게임 검색"
            className="w-full rounded-2xl border-2 border-sky-100 px-4 py-2.5 text-sm outline-none focus:border-sky-300"
            autoFocus
          />
        </div>
        <div className="flex-1 overflow-y-auto px-5 pb-8">
          {loading && (
            <div className="grid gap-2">
              {Array.from({ length: 5 }).map((_, i) => (
                <div key={i} className="flex items-center gap-3 rounded-2xl border border-slate-100 bg-white p-3">
                  <div className="h-11 w-11 animate-pulse rounded-xl bg-sky-50"></div>
                  <div className="flex-1 space-y-2">
                    <div className="h-3 w-1/2 animate-pulse rounded bg-slate-100"></div>
                    <div className="h-2.5 w-1/3 animate-pulse rounded bg-slate-100"></div>
                  </div>
                </div>
              ))}
            </div>
          )}
          {error && <div className="my-3 rounded-2xl bg-rose-50 px-4 py-3 text-sm text-rose-600">{error}</div>}
          {!loading && filtered.length === 0 && (
            <div className="py-12 text-center text-slate-400 text-sm">
              {search ? '검색 결과가 없어요' : '추가 가능한 게임이 없어요'}
            </div>
          )}
          <div className="grid gap-2">
            {filtered.map(g => (
              <div key={g.id} className="flex items-center gap-3 rounded-2xl border border-slate-100 bg-white p-3">
                <div className="flex-shrink-0">
                  {g.icon_url ? (
                    <img src={g.icon_url} alt="" className="h-10 w-10 rounded-lg object-cover bg-slate-100" onError={(e) => { e.target.style.display = 'none'; }} />
                  ) : (
                    <div className="h-10 w-10 rounded-lg bg-wildy-cloud flex items-center justify-center text-xl">{g.emoji || '🎮'}</div>
                  )}
                </div>
                <div className="flex-1 min-w-0">
                  <div className="font-bold text-sm text-wildy-ink truncate">{localize(g, lang)}</div>
                  <div className="text-xs text-slate-500 truncate">{g.short_description || g.category}</div>
                </div>
                <button
                  onClick={() => add(g.id)}
                  disabled={addingId === g.id}
                  className="rounded-full bg-wildy-ink px-3 py-1.5 text-xs font-bold text-white disabled:opacity-50"
                >
                  {addingId === g.id ? '...' : '+ 추가'}
                </button>
              </div>
            ))}
          </div>
        </div>
      </div>
    );
  }

  // ───────────────────────────────────────────────────────────
  // MyWildsScreen
  // ───────────────────────────────────────────────────────────
  function MyWildsScreen({ supabaseClient, user, lang = 'ko', onBack, onOpenWild }) {
    const [subs, setSubs] = useState([]);          // [{wild_id, source, subscribed_at, wilds: {...}}]
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState('');
    const [removingId, setRemovingId] = useState('');
    const [addOpen, setAddOpen] = useState(false);

    const reload = async () => {
      if (!supabaseClient || !user?.id) { setSubs([]); setLoading(false); return; }
      setLoading(true);
      setError('');
      try {
        const { data, error: e } = await withTimeout(
          supabaseClient
            .from('wild_subscriptions')
            .select('wild_id,source,subscribed_at,wilds(id,name,emoji,category,title_en,title_ja,title_zh,title_id,icon_url,short_description,member_count)')
            .eq('user_id', user.id)
            .order('subscribed_at', { ascending: false }),
          7000,
          { data: [], error: new Error('my_wilds_timeout') }
        );
        if (e) throw e;
        setSubs(data || []);
      } catch (err) {
        console.error('[MyWildsScreen] load failed', err);
        setError('내 Wild 목록을 불러오지 못했어요');
      } finally {
        setLoading(false);
      }
    };

    useEffect(() => { reload(); }, [supabaseClient, user?.id]);

    const removeSub = async (wildId) => {
      if (removingId) return;
      if (!confirm('이 Wild의 팔로우를 취소할까요?')) return;
      setRemovingId(wildId);
      const prev = subs;
      setSubs(prev.filter(s => s.wild_id !== wildId));   // optimistic
      const tag = `[MyWildsScreen] DELETE user=${user?.id} wild=${wildId}`;
      try {
        if (supabaseClient && user?.id) {
          // .select()로 영향 row 회수 — RLS/이미 비구독으로 0 row 면 에러 아님(낙관적 유지).
          const { data, error: e } = await supabaseClient
            .from('wild_subscriptions')
            .delete()
            .eq('user_id', user.id)
            .eq('wild_id', wildId)
            .select('id');
          if (e) throw e;
          const rows = Array.isArray(data) ? data.length : 0;
          console.info(tag, rows === 0 ? '→ 0 rows (이미 비구독 또는 RLS 필터)' : `→ deleted ${rows} row`);
        }
      } catch (err) {
        console.error(tag, 'FAILED', { code: err?.code, message: err?.message, details: err?.details, hint: err?.hint });
        setSubs(prev);  // rollback
        setError('팔로우 취소 실패');
      } finally {
        setRemovingId('');
      }
    };

    const subscribedIds = useMemo(() => subs.map(s => s.wild_id), [subs]);

    return (
      <div className="min-h-screen w-full bg-white pb-20" style={{ maxWidth: 480, margin: '0 auto' }}>
        <div className="sticky top-0 z-10 bg-white/95 backdrop-blur px-5 py-3 border-b border-slate-100 flex items-center justify-between">
          <button onClick={onBack} className="flex h-9 w-9 items-center justify-center rounded-full hover:bg-slate-100 text-lg">←</button>
          <h1 className="font-display text-lg font-black text-wildy-ink">내 Wild</h1>
          <button
            onClick={() => setAddOpen(true)}
            className="rounded-full bg-wildy-ink px-3 py-1.5 text-xs font-bold text-white"
          >
            + 추가
          </button>
        </div>

        <div className="px-5 pt-4">
          {loading && (
            <div className="grid gap-2">
              {Array.from({ length: 4 }).map((_, i) => (
                <div key={i} className="flex items-center gap-3 rounded-2xl border border-slate-100 bg-white p-3">
                  <div className="h-11 w-11 animate-pulse rounded-xl bg-sky-50"></div>
                  <div className="flex-1 space-y-2">
                    <div className="h-3 w-1/2 animate-pulse rounded bg-slate-100"></div>
                    <div className="h-2.5 w-1/3 animate-pulse rounded bg-slate-100"></div>
                  </div>
                </div>
              ))}
            </div>
          )}
          {error && <div className="my-3 rounded-2xl bg-rose-50 px-4 py-3 text-sm text-rose-600">{error}</div>}

          {!loading && subs.length === 0 && (
            <div className="py-16 text-center">
              <div className="text-5xl mb-3">🎮</div>
              <p className="text-sm text-slate-500">아직 팔로우한 Wild가 없어요</p>
              <button
                onClick={() => setAddOpen(true)}
                className="mt-5 rounded-full bg-wildy-ink px-6 py-3 text-sm font-bold text-white"
              >
                Wild 추가하러 가기
              </button>
            </div>
          )}

          {!loading && subs.length > 0 && (
            <>
              <div className="mb-3 text-xs text-slate-500">{subs.length}개 팔로우 중</div>
              <div className="space-y-2">
                {subs.map(s => {
                  const w = s.wilds || {};
                  return (
                    <div key={s.wild_id} className="flex items-center gap-3 rounded-2xl border border-slate-100 bg-white p-3">
                      <button
                        onClick={() => onOpenWild && onOpenWild(s.wild_id)}
                        className="flex flex-1 items-center gap-3 text-left min-w-0"
                      >
                        <div className="flex-shrink-0">
                          {w.icon_url ? (
                            <img src={w.icon_url} alt="" className="h-11 w-11 rounded-lg object-cover bg-slate-100" onError={(e) => { e.target.style.display = 'none'; }} />
                          ) : (
                            <div className="h-11 w-11 rounded-lg bg-wildy-cloud flex items-center justify-center text-xl">{w.emoji || '🎮'}</div>
                          )}
                        </div>
                        <div className="flex-1 min-w-0">
                          <div className="font-bold text-sm text-wildy-ink truncate">{localize(w, lang)}</div>
                          <div className="text-xs text-slate-500 truncate">
                            멤버 {(w.member_count || 0).toLocaleString('ko-KR')}명
                            {s.source === 'onboarding' && <span className="ml-1.5 rounded-full bg-sky-50 px-1.5 py-0.5 text-[10px] text-sky-700">온보딩</span>}
                          </div>
                        </div>
                      </button>
                      <button
                        onClick={() => removeSub(s.wild_id)}
                        disabled={removingId === s.wild_id}
                        className="rounded-full border-2 border-slate-200 px-3 py-1.5 text-xs font-bold text-slate-500 hover:border-rose-200 hover:text-rose-500 disabled:opacity-50"
                      >
                        {removingId === s.wild_id ? '...' : '취소'}
                      </button>
                    </div>
                  );
                })}
              </div>
            </>
          )}
        </div>

        {addOpen && (
          <AddWildSheet
            supabaseClient={supabaseClient}
            user={user}
            lang={lang}
            excludeIds={subscribedIds}
            onClose={() => setAddOpen(false)}
            onAdded={() => { setAddOpen(false); reload(); }}
          />
        )}
      </div>
    );
  }

  global.WildyComponents = global.WildyComponents || {};
  global.WildyComponents.MyWildsScreen = MyWildsScreen;
  global.WildyComponents.AddWildSheet = AddWildSheet;
})(typeof window !== 'undefined' ? window : globalThis);
