/* IslamPlay — Экраны входа/регистрации (на русском) */

function SplashScreen({ onContinue }) {
  React.useEffect(() => {
    const t = setTimeout(() => onContinue && onContinue(), 2000);
    return () => clearTimeout(t);
  }, []);
  return (
    <IPScreen style={{
      background: 'radial-gradient(ellipse at center, #2a2010 0%, #0f0d0a 60%, #000 100%)',
    }}>
      <IPPattern opacity={0.08}/>
      <div style={{
        position: 'absolute', inset: 0, display: 'flex',
        flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
        gap: 24, padding: 40,
      }}>
        <IPMihrab size={140}>
          <div style={{
            fontFamily: 'Amiri, serif', fontSize: 52,
            color: '#e9c97a', fontWeight: 700,
            textShadow: '0 0 20px rgba(212, 175, 106, 0.5)',
          }}>﷽</div>
        </IPMihrab>
        <div style={{ textAlign: 'center', marginTop: 8 }}>
          <div style={{
            fontFamily: 'Cormorant Garamond, serif', fontWeight: 700,
            fontSize: 40, color: '#e9c97a',
            letterSpacing: 0.5, lineHeight: 1,
          }}>Ислам Плей</div>
          <div style={{
            fontFamily: 'Amiri, serif', fontSize: 18,
            color: IP_THEME.creamMute, marginTop: 10,
          }}>القرآن الكريم</div>
          <div style={{
            fontSize: 11, color: IP_THEME.creamDim,
            letterSpacing: '0.2em', textTransform: 'uppercase',
            marginTop: 14,
          }}>Чтение · Размышление · Покой</div>
        </div>
        <div style={{
          position: 'absolute', bottom: 80, left: 40, right: 40,
          textAlign: 'center',
        }}>
          <div style={{
            height: 2, background: 'linear-gradient(90deg, transparent, rgba(212,175,106,0.5), transparent)',
            borderRadius: 2, marginBottom: 16,
          }}>
            <div style={{
              height: '100%', width: '40%',
              background: IP_THEME.goldLight,
              borderRadius: 2,
              animation: 'ipLoad 2s ease-in-out',
            }}/>
          </div>
          <div style={{ fontSize: 11, color: IP_THEME.creamDim, letterSpacing: '0.15em', textTransform: 'uppercase' }}>
            Подготовка аудиозаписей…
          </div>
        </div>
      </div>
      <style>{`@keyframes ipLoad { 0% { width: 0; } 100% { width: 100%; } }`}</style>
    </IPScreen>
  );
}

function ErrorMsg({ children }) {
  if (!children) return null;
  const map = {
    invalid_email: 'Укажите корректный адрес почты.',
    invalid_name: 'Имя должно содержать минимум 2 символа.',
    weak_password: 'Пароль должен содержать минимум 6 символов.',
    missing_credentials: 'Заполните почту и пароль.',
    invalid_credentials: 'Неверная почта или пароль.',
    email_taken: 'Аккаунт с такой почтой уже существует.',
    server_error: 'Ошибка сервера — попробуйте ещё раз.',
    register_failed: 'Не удалось зарегистрироваться.',
    login_failed: 'Не удалось войти.',
  };
  return (
    <div style={{
      background: 'rgba(201, 111, 74, 0.12)',
      border: `1px solid rgba(201, 111, 74, 0.35)`,
      color: IP_THEME.danger,
      padding: '10px 14px', borderRadius: 10,
      fontSize: 13,
    }}>{map[children] || children}</div>
  );
}

function LoginScreen({ onLogin, onGoRegister }) {
  const [email, setEmail] = React.useState('');
  const [password, setPassword] = React.useState('');
  const [error, setError] = React.useState(null);
  const [busy, setBusy] = React.useState(false);

  async function submit() {
    setError(null);
    setBusy(true);
    try {
      const user = await IP_API.login(email, password);
      onLogin(user);
    } catch (e) {
      setError(e.message);
    } finally {
      setBusy(false);
    }
  }

  return (
    <IPScreen>
      <div style={{ padding: `calc(30px + env(safe-area-inset-top, 0px)) 28px 40px`, display: 'flex', flexDirection: 'column', gap: 22, minHeight: '100%' }}>
        <div style={{ textAlign: 'center', marginTop: 12 }}>
          <div style={{ display: 'inline-block' }}>
            <IPMihrab size={90}>
              <div style={{ fontFamily: 'Amiri, serif', fontSize: 26, color: IP_THEME.goldLight, fontWeight: 700 }}>﷽</div>
            </IPMihrab>
          </div>
          <div style={{
            fontFamily: 'Cormorant Garamond, serif', fontWeight: 600,
            fontSize: 32, color: IP_THEME.goldLight, marginTop: 10,
          }}>С возвращением</div>
          <div style={{ fontSize: 13, color: IP_THEME.creamMute, marginTop: 4 }}>
            Войдите, чтобы продолжить слушать Коран
          </div>
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          <IPField icon="mail" placeholder="Электронная почта" value={email} onChange={setEmail}/>
          <IPField icon="lock" placeholder="Пароль" type="password" value={password} onChange={setPassword}/>
          <ErrorMsg>{error}</ErrorMsg>
        </div>

        <IPButton onClick={submit} style={{ opacity: busy ? 0.7 : 1 }}>
          {busy ? 'Вход…' : 'Войти'}
        </IPButton>

        <div style={{ flex: 1 }}/>

        <div style={{ textAlign: 'center', fontSize: 13, color: IP_THEME.creamMute }}>
          Нет аккаунта?{' '}
          <a onClick={onGoRegister} style={{ color: IP_THEME.goldLight, fontWeight: 600, cursor: 'pointer' }}>
            Создать
          </a>
        </div>
      </div>
    </IPScreen>
  );
}

function RegisterScreen({ onRegister, onGoLogin }) {
  const [name, setName] = React.useState('');
  const [email, setEmail] = React.useState('');
  const [password, setPassword] = React.useState('');
  const [agree, setAgree] = React.useState(true);
  const [error, setError] = React.useState(null);
  const [busy, setBusy] = React.useState(false);
  const [reciter, setReciter] = React.useState(IP_RECITERS[0]?.slug || '');
  // keep first-reciter default even if IP_RECITERS loads after mount
  React.useEffect(() => {
    if (!reciter && IP_RECITERS[0]) setReciter(IP_RECITERS[0].slug);
  }, [IP_RECITERS.length]);

  async function submit() {
    setError(null);
    if (!agree) { setError('Примите условия и политику конфиденциальности.'); return; }
    if (!reciter) { setError('Выберите чтеца.'); return; }
    setBusy(true);
    try {
      const user = await IP_API.register(name, email, password);
      onRegister(user, reciter);
    } catch (e) {
      setError(e.message);
    } finally {
      setBusy(false);
    }
  }

  return (
    <IPScreen>
      <div style={{ padding: `calc(30px + env(safe-area-inset-top, 0px)) 28px 40px`, display: 'flex', flexDirection: 'column', gap: 20, minHeight: '100%' }}>
        <div style={{ textAlign: 'center', marginTop: 8 }}>
          <div style={{
            fontFamily: 'Cormorant Garamond, serif', fontWeight: 600,
            fontSize: 32, color: IP_THEME.goldLight,
          }}>Начните путь</div>
          <div style={{ fontSize: 13, color: IP_THEME.creamMute, marginTop: 6 }}>
            Создайте аккаунт, чтобы сохранять избранное и отслеживать прогресс.
          </div>
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          <IPField icon="user" placeholder="Полное имя" value={name} onChange={setName}/>
          <IPField icon="mail" placeholder="Электронная почта" value={email} onChange={setEmail}/>
          <IPField icon="lock" placeholder="Пароль (мин. 6 символов)" type="password" value={password} onChange={setPassword}/>

          <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '4px 2px' }}>
            <div onClick={() => setAgree(!agree)} style={{
              width: 22, height: 22, borderRadius: 6,
              background: agree ? 'linear-gradient(180deg, #e9c97a, #b8904a)' : 'transparent',
              border: `1px solid ${agree ? 'transparent' : IP_THEME.lineStrong}`,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              cursor: 'pointer', flexShrink: 0,
            }}>
              {agree && <IPIcon name="check" size={14} color="#17130d" stroke={3}/>}
            </div>
            <div style={{ fontSize: 12, color: IP_THEME.creamMute, lineHeight: 1.4 }}>
              Я принимаю <span style={{ color: IP_THEME.goldLight }}>условия</span> и <span style={{ color: IP_THEME.goldLight }}>политику конфиденциальности</span>
            </div>
          </div>
          <ErrorMsg>{error}</ErrorMsg>
        </div>

        {/* Выбор чтеца по умолчанию */}
        {IP_RECITERS.length > 0 && (
          <div>
            <div style={{ fontSize: 11, color: IP_THEME.creamDim, letterSpacing: '0.12em', textTransform: 'uppercase', marginBottom: 10 }}>
              Выберите чтеца
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {IP_RECITERS.map(r => {
                const selected = reciter === r.slug;
                return (
                  <button key={r.slug} type="button" onClick={() => setReciter(r.slug)} style={{
                    display: 'flex', alignItems: 'center', gap: 12,
                    padding: '12px 14px', borderRadius: 14,
                    background: selected ? 'rgba(212, 175, 106, 0.12)' : 'rgba(212, 175, 106, 0.04)',
                    border: `1px solid ${selected ? IP_THEME.gold : IP_THEME.line}`,
                    cursor: 'pointer', textAlign: 'left',
                    transition: 'all 0.15s',
                  }}>
                    <div style={{
                      width: 44, height: 44, borderRadius: '50%',
                      background: `linear-gradient(135deg, hsl(30 40% 22%), hsl(18 50% 12%))`,
                      border: `1px solid ${selected ? IP_THEME.gold : IP_THEME.lineStrong}`,
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                      fontFamily: 'Amiri, serif', fontSize: 16, color: IP_THEME.goldLight,
                      flexShrink: 0,
                    }}>{r.name.split(' ').map(w => w[0]).slice(0, 2).join('')}</div>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 14, fontWeight: 600, color: IP_THEME.cream, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                        {r.name}
                      </div>
                      <div style={{ fontSize: 11, color: IP_THEME.creamDim, marginTop: 2, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                        {r.style} · {r.country}
                      </div>
                    </div>
                    <div style={{
                      width: 22, height: 22, borderRadius: '50%',
                      border: `2px solid ${selected ? IP_THEME.gold : IP_THEME.lineStrong}`,
                      background: selected ? IP_THEME.gold : 'transparent',
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                      flexShrink: 0,
                    }}>
                      {selected && <IPIcon name="check" size={12} color="#17130d" stroke={3}/>}
                    </div>
                  </button>
                );
              })}
            </div>
            <div style={{ fontSize: 11, color: IP_THEME.creamDim, marginTop: 8, textAlign: 'center' }}>
              Можно изменить позже в профиле
            </div>
          </div>
        )}

        <IPButton onClick={submit} style={{ opacity: busy ? 0.7 : 1 }}>
          {busy ? 'Создание…' : 'Создать аккаунт'}
        </IPButton>

        <div style={{ flex: 1 }}/>

        <div style={{ textAlign: 'center', fontSize: 13, color: IP_THEME.creamMute }}>
          Уже есть аккаунт?{' '}
          <a onClick={onGoLogin} style={{ color: IP_THEME.goldLight, fontWeight: 600, cursor: 'pointer' }}>Войти</a>
        </div>
      </div>
    </IPScreen>
  );
}

Object.assign(window, { SplashScreen, LoginScreen, RegisterScreen });
