import { useState, useEffect } from 'react';
import { Avatar } from '../components/shared/Avatar';
import { useAppStore } from '../store/appStore';
import { creaturesApi } from '../services/api';
import { t } from '../i18n';
import styles from './ProfilePage.module.css';

const APP_VERSION = '1.0.0';

const fmt = (n: number | null) => (n == null ? '—' : n.toLocaleString('ru-RU'));

export function ProfilePage() {
  const telegramUser = useAppStore((s) => s.telegramUser);
  const myUserId = useAppStore((s) => s.myUserId);
  const xp = useAppStore((s) => s.xp);
  const level = useAppStore((s) => s.level);
  const cellsExplored = useAppStore((s) => s.revealedCells.length);
  const giftAnimations = useAppStore((s) => s.giftAnimations);
  const setGiftAnimations = useAppStore((s) => s.setGiftAnimations);

  // Caught-gifts count — the size of the user's collection (fetched once).
  const [caught, setCaught] = useState<number | null>(null);

  useEffect(() => {
    if (!telegramUser) return;
    let alive = true;
    creaturesApi
      .getCollection()
      .then((list) => {
        if (alive) setCaught(Array.isArray(list) ? list.length : 0);
      })
      .catch(() => {
        if (alive) setCaught(0);
      });
    return () => {
      alive = false;
    };
  }, [telegramUser]);

  if (!telegramUser) {
    return (
      <div className={styles.container}>
        <div className={styles.header}>
          <h1 className={styles.title}>{t('profilePage.title')}</h1>
        </div>
        <div className={styles.loading}>
          <div className={styles.spinner} />
          <p>{t('profilePage.loading')}</p>
          <p className={styles.loadingHint}>{t('profilePage.loadingHint')}</p>
        </div>
      </div>
    );
  }

  const avatarUrl = telegramUser.photo_url || undefined;

  return (
    <div className={styles.container}>
      <div className={styles.header}>
        <h1 className={styles.title}>{t('profilePage.title')}</h1>
      </div>

      <div className={styles.body}>
        <div className={styles.hero}>
          <div className={styles.avatarWrapper}>
            <Avatar src={avatarUrl} alt={telegramUser.first_name} size="large" />
            <div className={styles.levelBadge}>{level}</div>
          </div>
          <h2 className={styles.name}>
            {telegramUser.first_name} {telegramUser.last_name || ''}
          </h2>
          {telegramUser.username && (
            <p className={styles.username}>@{telegramUser.username}</p>
          )}
        </div>

        <div className={styles.stats}>
          <div className={styles.statCard}>
            <div className={styles.statValue}>{level}</div>
            <div className={styles.statLabel}>{t('profilePage.statLevel')}</div>
            <div className={styles.statSub}>{fmt(xp)} XP</div>
          </div>
          <div className={styles.statCard}>
            <div className={styles.statValue}>{fmt(caught)}</div>
            <div className={styles.statLabel}>{t('profilePage.statCaught')}</div>
            <div className={styles.statSub}>{t('profilePage.statGifts')}</div>
          </div>
          <div className={styles.statCard}>
            <div className={styles.statValue}>{fmt(cellsExplored)}</div>
            <div className={styles.statLabel}>{t('profilePage.statExplored')}</div>
            <div className={styles.statSub}>{t('profilePage.statCells')}</div>
          </div>
        </div>

        {/* settings */}
        <div className={styles.infoRow} style={{ alignItems: 'center' }}>
          <div className={styles.infoItem} style={{ flex: 1 }}>
            <span className={styles.infoLabel}>{t('profilePage.giftAnimations')}</span>
            <span className={styles.infoValue} style={{ fontSize: 11, opacity: 0.6 }}>{t('profilePage.giftAnimationsHint')}</span>
          </div>
          <button
            type="button"
            role="switch"
            aria-checked={giftAnimations}
            onClick={() => setGiftAnimations(!giftAnimations)}
            style={{
              width: 52, height: 30, borderRadius: 999, border: 0, cursor: 'pointer', flex: 'none',
              background: giftAnimations ? 'linear-gradient(135deg,#3a9fff,#7bd1ff)' : 'rgba(255,255,255,.18)',
              position: 'relative', transition: 'background .2s ease',
            }}
          >
            <span
              style={{
                position: 'absolute', top: 3, left: giftAnimations ? 25 : 3, width: 24, height: 24,
                borderRadius: '50%', background: '#fff', boxShadow: '0 2px 6px rgba(0,0,0,.35)',
                transition: 'left .2s ease',
              }}
            />
          </button>
        </div>

        <div className={styles.infoRow}>
          <div className={styles.infoItem}>
            <span className={styles.infoLabel}>{t('profilePage.version')}</span>
            <span className={styles.infoValue}>{APP_VERSION}</span>
          </div>
          <div className={styles.infoItem}>
            <span className={styles.infoLabel}>ID</span>
            <span className={styles.infoValue}>{myUserId || '—'}</span>
          </div>
        </div>
      </div>
    </div>
  );
}
