// Main scene components with Feedback Modal

function FeedbackModal({ isOpen, onClose, type }) {
  const [title, setTitle] = React.useState('');
  const [content, setContent] = React.useState('');
  const [isSending, setIsSending] = React.useState(false);

  if (!isOpen) return null;

  const handleSubmit = async () => {
    if (!title.trim() || !content.trim()) {
      alert('제목과 내용을 모두 입력해주세요.');
      return;
    }
    const prefix = type === 'bug' ? '[버그제보]' : '[문의/개선점]';
    const fullSubject = `${prefix} ${title}`;

    setIsSending(true);
    try {
      const res = await fetch('https://formspree.io/f/xgoqepkg', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
        body: JSON.stringify({ _subject: fullSubject, message: content })
      });
      setIsSending(false);
      if (res.ok) {
        alert('소중한 의견 감사합니다. 성공적으로 전송되었습니다.');
        setTitle('');
        setContent('');
        onClose();
      } else {
        alert('전송에 실패했습니다. 나중에 다시 시도해주세요.');
      }
    } catch (e) {
      setIsSending(false);
      alert('전송에 실패했습니다. 나중에 다시 시도해주세요.');
    }
  };

  return (
    <div style={{
      position: 'absolute', inset: 0, zIndex: 1000,
      background: 'rgba(0,0,0,0.5)', display: 'flex', alignItems: 'center', justifyContent: 'center',
      backdropFilter: 'blur(4px)'
    }}>
      <div style={{
        width: '90%', maxWidth: 500, background: 'var(--paper-warm)', borderRadius: 24,
        padding: 32, boxShadow: '0 20px 40px rgba(0,0,0,0.12)',
        position: 'relative'
      }}>
        <h2 style={{ fontFamily: 'var(--font-display)', fontSize: 24, marginBottom: 20, color: 'var(--ink)' }}>
          {type === 'bug' ? '버그 제보' : '의견 보내기'}
        </h2>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <input 
            type="text" 
            placeholder="제목을 입력하세요" 
            value={title}
            onChange={(e) => setTitle(e.target.value)}
            style={{
              padding: '14px', borderRadius: 12, border: '1px solid var(--hairline)',
              fontFamily: 'var(--font-body)', fontSize: 16
            }}
          />
          <textarea 
            placeholder="상세 내용을 입력하세요" 
            rows={5}
            value={content}
            onChange={(e) => setContent(e.target.value)}
            style={{
              padding: '14px', borderRadius: 12, border: '1px solid var(--hairline)',
              fontFamily: 'var(--font-body)', fontSize: 16, resize: 'none'
            }}
          />
        </div>
        <div style={{ display: 'flex', gap: 12, marginTop: 24 }}>
          <button 
            onClick={onClose}
            style={{
              flex: 1, padding: '14px', borderRadius: 12, border: '1px solid var(--hairline)',
              background: 'var(--paper)', cursor: 'pointer', fontWeight: 600
            }}
          >취소</button>
          <button 
            onClick={handleSubmit}
            disabled={isSending}
            style={{
              flex: 1, padding: '14px', borderRadius: 12, border: 'none',
              background: 'var(--apple)', color: '#fff', cursor: 'pointer', fontWeight: 600,
              opacity: isSending ? 0.7 : 1
            }}
          >{isSending ? '전송 중...' : '전송하기'}</button>
        </div>
      </div>
    </div>
  );
}

function PrimaryButton({ children, variant = "primary", disabled = false, icon = null, onClick }) {
  const styles = {
    primary: { bg: 'var(--apple)', color: '#fff', border: 'transparent', shadow: '0 1px 0 #6B1212 inset, 0 -2px 0 #8E1A1A inset, 0 8px 18px rgba(155,28,28,0.25)' },
    secondary: { bg: 'var(--paper-warm)', color: 'var(--ink)', border: 'var(--hairline)', shadow: '0 1px 0 rgba(255,255,255,0.6) inset, 0 -2px 0 rgba(0,0,0,0.06) inset, 0 4px 12px rgba(107,66,38,0.08)' },
    ghost: { bg: 'transparent', color: 'var(--ink-soft)', border: 'var(--hairline)', shadow: 'none' },
    dark: { bg: 'var(--ink)', color: '#FAF5EC', border: 'transparent', shadow: '0 1px 0 rgba(255,255,255,0.10) inset, 0 -2px 0 rgba(0,0,0,0.30) inset, 0 8px 18px rgba(0,0,0,0.18)' },
  };
  const s = styles[variant] || styles.primary;
  return (
    <button disabled={disabled} onClick={onClick} style={{
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 10,
      padding: 'clamp(12px, 3vw, 18px) clamp(16px, 4vw, 24px)',
      fontFamily: 'var(--font-body)', fontSize: 'clamp(15px, 2.5vw, 18px)', fontWeight: 700,
      background: s.bg, color: s.color,
      border: '1.5px solid', borderColor: s.border === 'transparent' ? 'transparent' : `var(--hairline)`,
      borderRadius: 14, cursor: disabled ? 'not-allowed' : 'pointer',
      boxShadow: s.shadow,
      opacity: disabled ? 0.5 : 1,
      letterSpacing: '-0.01em', minHeight: 'clamp(48px, 8vw, 60px)', width: '100%'
    }}>
      {icon}{children}
    </button>
  );
}

function MainScreen({ onStart, onRecords, onLeaderboard, user, onLogin, onLogout, onLoginAsGuest, onMultiplayer, onNicknameEdit }) {
  const [modalOpen, setModalOpen] = React.useState(false);
  const [askName, setAskName] = React.useState(false);
  const [guestName, setGuestName] = React.useState('');

  const soloStart = async () => {
    if (!user) await onLoginAsGuest('');
    onStart();
  };
  const multiStart = async () => {
    if (user) return onMultiplayer();
    if (!askName) return setAskName(true);
    await onLoginAsGuest(guestName);
    onMultiplayer();
  };

  const btn = { display: 'block', width: '100%', padding: 15, borderRadius: 12, border: 'none', cursor: 'pointer',
    fontFamily: 'var(--font-body)', fontSize: 16, fontWeight: 600, background: 'var(--paper)', color: 'var(--ink)' };
  const small = { ...btn, flex: 1, fontSize: 15, fontWeight: 500 };
  const link = { background: 'none', border: 'none', padding: 0, marginLeft: 8, cursor: 'pointer', fontFamily: 'inherit',
    fontSize: 13, fontWeight: 600, color: 'var(--ink)', textDecoration: 'underline', textUnderlineOffset: 3 };

  return (
    <div style={{ width: '100%', minHeight: '100%', background: 'var(--paper-warm)', fontFamily: 'var(--font-body)',
      display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '32px 0' }}>
      <div style={{ width: 'min(340px, 88vw)', textAlign: 'center' }}>
        <img src="face.png" alt="" width="168" height="168" style={{ display: 'block', margin: '0 auto' }} />
        <h1 style={{ fontFamily: 'var(--font-display)', fontSize: 26, fontWeight: 700, letterSpacing: '-0.02em', color: 'var(--ink)', margin: '6px 0 0' }}>사과사과게임</h1>
        <p style={{ fontSize: 14, color: 'var(--ink-mute)', margin: '6px 0 0' }}>합이 10이 되게 묶어서 따기</p>

        <div style={{ marginTop: 36, display: 'flex', flexDirection: 'column', gap: 10 }}>
          <button onClick={soloStart} style={{ ...btn, background: 'var(--apple)', color: '#fff' }}>혼자 하기</button>
          {askName && !user && (
            <input autoFocus value={guestName} maxLength={12} placeholder="닉네임 (비우면 자동)"
              onChange={(e) => setGuestName(e.target.value)}
              onKeyDown={(e) => { if (e.key === 'Enter') multiStart(); }}
              style={{ padding: 14, borderRadius: 12, border: '1px solid var(--hairline)', fontSize: 16,
                fontFamily: 'inherit', textAlign: 'center', background: '#fff' }} />
          )}
          <button onClick={multiStart} style={btn}>{askName && !user ? '이 닉네임으로 같이 하기' : '같이 하기'}</button>
          <div style={{ display: 'flex', gap: 10 }}>
            {user && <button onClick={onRecords} style={small}>기록</button>}
            <button onClick={onLeaderboard} style={small}>랭킹</button>
            <button onClick={() => setModalOpen(true)} style={small}>의견 보내기</button>
          </div>
        </div>

        <p style={{ marginTop: 28, fontSize: 13, color: 'var(--ink-mute)' }}>
          {!user ? (<>로그인하면 기록이 남습니다<button onClick={onLogin} style={link}>구글 로그인</button></>)
            : (<>{user.displayName || user.name}
                {!isGuest && onNicknameEdit && <button onClick={onNicknameEdit} style={link}>닉네임 변경</button>}
                <button onClick={onLogout} style={link}>{isGuest ? '나가기' : '로그아웃'}</button></>)}
        </p>
      </div>
      <FeedbackModal isOpen={modalOpen} onClose={() => setModalOpen(false)} type="suggestion" />
    </div>
  );
}

Object.assign(window, { MainScreen, PrimaryButton });
