/* ============================================================================
 * Wildy — 채팅방 생성 모달
 * ----------------------------------------------------------------------------
 *   spec: Part C — 채팅방 6종 + 4중 안전장치 RLS
 *
 *   기능:
 *     - 이름 / 종류 / 소개 / 비공개 입력
 *     - /api/moderate 사전 검증 (이름/소개)
 *     - public.create_chat_room RPC 호출 (RLS 4중 안전장치 통과)
 *     - 성공 시 onCreated(room_id) 콜백
 *
 *   사용:
 *     <window.WildyComponents.CreateRoomModal
 *        supabaseClient={...}
 *        user={user}
 *        wildId="lol"
 *        wildName="리그 오브 레전드"
 *        onClose={() => ...}
 *        onCreated={(roomId, name) => ...}
 *     />
 *
 *   글로벌 노출:
 *     window.WildyComponents.CreateRoomModal
 * ========================================================================= */
(function (global) {
  'use strict';

  if (typeof React === 'undefined') {
    console.error('[create-room-modal.jsx] React not loaded');
    return;
  }
  const { useState } = React;

  const ROOM_TYPES = [
    { value: 'free',    label: '오픈채팅', emoji: '💬', desc: '자유 주제 / 누구나 참여' },
    { value: 'meetup',  label: '파티방',   emoji: '🎮', desc: '게임 같이 할 사람 모집' },
    { value: 'social',  label: '그룹',     emoji: '👥', desc: '친목 도모' },
    { value: 'recruit', label: '길드 모집', emoji: '🏰', desc: '5인큐 · 듀오 · 길드 멤버' },
  ];

  function CreateRoomModal({ supabaseClient, user, wildId, wildName, onClose, onCreated }) {
    const [name, setName] = useState('');
    const [type, setType] = useState('free');
    const [description, setDescription] = useState('');
    const [isPrivate, setIsPrivate] = useState(false);
    const [maxMembers, setMaxMembers] = useState(50);
    const [busy, setBusy] = useState(false);
    const [error, setError] = useState('');
    const helpers = (global.WildyLib && global.WildyLib.SupabaseHelpers) || {};

    const submit = async () => {
      if (busy) return;
      setError('');
      const n = name.trim();
      if (!n) { setError('채팅방 이름을 입력해주세요'); return; }
      if (n.length > 30) { setError('이름은 30자 이하로 입력해주세요'); return; }
      if (description.length > 200) { setError('소개는 200자 이하로 입력해주세요'); return; }
      if (!supabaseClient || !user?.id) { setError('로그인이 필요해요'); return; }

      setBusy(true);
      try {
        // 1) 모더레이션 사전 검증 (이름 + 소개)
        try {
          const mr = await fetch('/api/moderate', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ name: n, description }),
          });
          if (mr.ok) {
            const md = await mr.json();
            if (md && md.ok === false && md.flagged) {
              setError(md.reason || '부적절한 표현이 포함되어 있어요');
              setBusy(false);
              return;
            }
          }
        } catch {
          // 모더레이션 장애 = 통과 (best-effort)
        }

        // 2) RPC 호출
        const { data: roomId, error: rpcErr } = await supabaseClient.rpc('create_chat_room', {
          p_wild_id: wildId,
          p_room_type: type,
          p_name: n,
          p_description: description.trim() || null,
          p_is_private: isPrivate,
          p_max_members: Math.max(2, Math.min(maxMembers, isPrivate ? 30 : 100)),
        });
        if (rpcErr) throw rpcErr;
        if (!roomId) throw new Error('채팅방 생성 실패');

        onCreated && onCreated(roomId, n);
        onClose && onClose();
      } catch (e) {
        console.error('[CreateRoomModal] submit failed', e);
        setError(helpers.translateAuthError ? helpers.translateAuthError(e) : (e?.message || '채팅방 생성 실패'));
      } finally {
        setBusy(false);
      }
    };

    return (
      <div
        className="fixed inset-0 z-[130] flex items-center justify-center bg-black/40 p-4"
        onClick={onClose}
      >
        <div
          onClick={(e) => e.stopPropagation()}
          className="w-full max-w-md max-h-[90vh] rounded-3xl bg-white shadow-2xl overflow-hidden flex flex-col"
        >
          {/* Header */}
          <div className="flex items-center justify-between border-b border-slate-100 px-5 py-4">
            <button onClick={onClose} className="flex h-9 w-9 items-center justify-center rounded-full hover:bg-slate-100" aria-label="닫기">✕</button>
            <h2 className="font-display text-lg font-black text-wildy-ink">새 채팅방 만들기</h2>
            <div className="w-9"></div>
          </div>

          {/* Body */}
          <div className="flex-1 overflow-y-auto p-5 space-y-4">
            <p className="text-xs text-slate-500" style={{ wordBreak: 'keep-all' }}>
              <b className="text-wildy-ink">{wildName}</b> Wild의 채팅방을 만들어요. 하루 최대 3개까지 만들 수 있어요.
            </p>

            {/* 이름 */}
            <div>
              <label className="block text-xs font-bold text-slate-700 mb-1.5">채팅방 이름 *</label>
              <input
                value={name}
                onChange={(e) => setName(e.target.value)}
                maxLength={30}
                placeholder="예) 다이아 모임"
                className="w-full rounded-2xl border-2 border-sky-100 px-4 py-3 text-sm outline-none focus:border-sky-300"
                autoFocus
              />
              <p className="mt-1 text-[10px] text-slate-400 text-right">{name.length}/30</p>
            </div>

            {/* 종류 */}
            <div>
              <label className="block text-xs font-bold text-slate-700 mb-1.5">종류</label>
              <div className="grid grid-cols-2 gap-2">
                {ROOM_TYPES.map(rt => (
                  <button
                    key={rt.value}
                    onClick={() => setType(rt.value)}
                    className={`rounded-2xl border-2 px-3 py-2 text-left transition ${
                      type === rt.value
                        ? 'border-sky-300 bg-sky-50'
                        : 'border-slate-100 bg-white hover:border-sky-200'
                    }`}
                  >
                    <div className="flex items-center gap-1.5 text-sm font-bold">
                      <span>{rt.emoji}</span>
                      <span className={type === rt.value ? 'text-sky-700' : 'text-wildy-ink'}>{rt.label}</span>
                    </div>
                    <p className="text-[10px] text-slate-500 mt-0.5">{rt.desc}</p>
                  </button>
                ))}
              </div>
            </div>

            {/* 소개 (선택) */}
            <div>
              <label className="block text-xs font-bold text-slate-700 mb-1.5">소개 (선택)</label>
              <textarea
                value={description}
                onChange={(e) => setDescription(e.target.value)}
                maxLength={200}
                rows={2}
                placeholder="간단한 설명을 입력해보세요"
                className="w-full resize-none rounded-2xl border-2 border-sky-100 px-4 py-2.5 text-sm outline-none focus:border-sky-300"
              />
              <p className="mt-1 text-[10px] text-slate-400 text-right">{description.length}/200</p>
            </div>

            {/* 인원 + 비공개 */}
            <div className="flex items-center gap-3">
              <div className="flex-1">
                <label className="block text-xs font-bold text-slate-700 mb-1.5">최대 인원</label>
                <input
                  type="number"
                  min={2}
                  max={isPrivate ? 30 : 100}
                  value={maxMembers}
                  onChange={(e) => setMaxMembers(Math.max(2, parseInt(e.target.value, 10) || 2))}
                  className="w-full rounded-2xl border-2 border-sky-100 px-4 py-2.5 text-sm outline-none focus:border-sky-300"
                />
              </div>
              <label className="flex flex-col items-center cursor-pointer gap-1.5 pt-5">
                <span className="text-xs font-bold text-slate-700">🔒 비공개</span>
                <input
                  type="checkbox"
                  checked={isPrivate}
                  onChange={(e) => {
                    setIsPrivate(e.target.checked);
                    if (e.target.checked && maxMembers > 30) setMaxMembers(30);
                  }}
                  className="w-5 h-5"
                />
              </label>
            </div>
            {isPrivate && (
              <p className="text-[11px] text-amber-700 bg-amber-50 rounded-xl px-3 py-2" style={{ wordBreak: 'keep-all' }}>
                ⚠ 비공개방은 초대받은 사람만 입장할 수 있어요. 가입 7일 후부터 만들 수 있어요.
              </p>
            )}

            {/* 에러 */}
            {error && (
              <div className="rounded-2xl bg-rose-50 px-4 py-3 text-sm text-rose-600" style={{ wordBreak: 'keep-all' }}>
                {error}
              </div>
            )}
          </div>

          {/* Footer */}
          <div className="border-t border-slate-100 px-5 py-3 flex items-center gap-2">
            <button
              onClick={onClose}
              className="flex-1 rounded-full border-2 border-slate-200 py-3 text-sm font-bold text-slate-600 hover:bg-slate-50"
            >
              취소
            </button>
            <button
              onClick={submit}
              disabled={busy || !name.trim()}
              className="flex-1 rounded-full bg-wildy-ink py-3 text-sm font-bold text-white disabled:bg-slate-300 hover:-translate-y-0.5 transition shadow-ink"
            >
              {busy ? '만드는 중...' : '만들기'}
            </button>
          </div>
        </div>
      </div>
    );
  }

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