/* ============================================================
   studio-wheel.jsx — Колесо фортуны (пользователь)
   GET /api/tg/wheel → статус+призы • POST {mode} → спин
   ============================================================ */

const { useState, useEffect, useRef } = React;

const WHEEL_FALLBACK_COLORS = ['#6B73FF', '#FF6B9D', '#4FACFE', '#43E97B', '#FA709A', '#A18CD1', '#FCCB90', '#96FBC4'];

function WheelPage() {
  const { API_BASE, user, updateUser } = useAuth();
  const { navigate } = useNav();
  const toast = useToast();

  const [status, setStatus] = useState(null);
  const [loading, setLoading] = useState(true);
  const [spinning, setSpinning] = useState(false);
  const [rotation, setRotation] = useState(0);
  const [result, setResult] = useState(null);
  const rotRef = useRef(0);

  async function loadStatus() {
    setLoading(true);
    try {
      const r = await fetch(`${API_BASE}/api/tg/wheel`, { credentials: 'include' });
      if (r.ok) setStatus(await r.json());
      else setStatus(null);
    } catch { setStatus(null); }
    finally { setLoading(false); }
  }

  useEffect(() => { loadStatus(); }, []);

  const prizes = status?.prizes || [];
  const N = prizes.length;
  const sectorAngle = N > 0 ? 360 / N : 0;

  function sectorColor(p, i) { return p.color || WHEEL_FALLBACK_COLORS[i % 8]; }

  /* conic-gradient из секторов */
  const conic = N > 0
    ? `conic-gradient(${prizes.map((p, i) => `${sectorColor(p, i)} ${i * sectorAngle}deg ${(i + 1) * sectorAngle}deg`).join(', ')})`
    : 'var(--surface)';

  async function spin(mode) {
    if (spinning || N === 0) return;
    setSpinning(true);
    setResult(null);
    try {
      const r = await fetch(`${API_BASE}/api/tg/wheel`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ mode }),
        credentials: 'include',
      });
      const data = await r.json();
      if (!r.ok || !data.ok) {
        const msg = {
          not_subscribed: 'Только для Pro/Business',
          not_enough: 'Недостаточно алмазов',
          cooldown: 'Бесплатный спин уже использован',
          disabled: 'Колесо недоступно',
          no_prizes: 'Нет призов',
        }[data.error] || 'Ошибка';
        toast(msg, 'warn');
        setSpinning(false);
        return;
      }

      /* поворот к выигравшему сектору: 5 полных оборотов + точное попадание */
      const desiredMod = (360 - ((data.prizeIndex + 0.5) * sectorAngle) % 360 + 360) % 360;
      const cur = rotRef.current;
      const next = cur + 360 * 5 + ((desiredMod - (cur % 360) + 360) % 360);
      rotRef.current = next;
      setRotation(next);

      /* после анимации (4.2с) — показать результат */
      setTimeout(() => {
        setResult(data);
        updateUser({ bananas: data.newBananas, diamonds: data.newDiamonds });
        setSpinning(false);
        loadStatus();
      }, 4300);
    } catch {
      toast('Ошибка сети', 'warn');
      setSpinning(false);
    }
  }

  return (
    <div>
      <div className="page-head">
        <div className="page-head-text">
          <h1 className="page-title h-display">🎡 Колесо фортуны</h1>
          <p className="page-sub muted">Крути и выигрывай 🍌 бананы — бесплатные генерации Nano Banana</p>
        </div>
      </div>

      {loading ? (
        <div style={{ textAlign: 'center', padding: 60 }}><Spinner /></div>
      ) : !status ? (
        <EmptyState icon="🎡" title="Колесо недоступно" sub="Попробуй позже" />
      ) : !status.enabled ? (
        <EmptyState icon="🎡" title="Колесо временно недоступно" />
      ) : !status.isPremium ? (
        <div className="glass" style={{ padding: '40px 32px', textAlign: 'center', maxWidth: 520 }}>
          <div style={{ fontSize: 48, marginBottom: 16 }}>🔒</div>
          <div style={{ fontSize: 18, fontWeight: 700, marginBottom: 8 }}>Только для подписчиков</div>
          <p className="muted" style={{ marginBottom: 20 }}>Колесо фортуны доступно на тарифах Pro и Business</p>
          <button className="btn btn-accent" onClick={() => navigate('studio-profile')}>Оформить подписку →</button>
        </div>
      ) : (
        <div className="wheel-layout">
          {/* Колесо */}
          <div className="wheel-wrap">
            <div className="wheel-pointer">▼</div>
            <div
              className="wheel"
              style={{
                background: conic,
                transform: `rotate(${rotation}deg)`,
                transition: spinning ? 'transform 4.2s cubic-bezier(.17,.67,.2,1)' : 'none',
              }}
            >
              {prizes.map((p, i) => {
                const a = (i + 0.5) * sectorAngle;
                return (
                  <div
                    key={p.id}
                    className="wheel-label"
                    style={{ transform: `rotate(${a}deg) translateY(-118px) rotate(${-a}deg)` }}
                  >
                    <div style={{ fontWeight: 800, fontSize: 15 }}>{p.diamonds > 0 ? `${p.diamonds}🍌` : '✕'}</div>
                  </div>
                );
              })}
            </div>
            <div className="wheel-center">🎡</div>
          </div>

          {/* Управление + результат */}
          <div className="wheel-side">
            <div className="glass" style={{ padding: 22, marginBottom: 16 }}>
              <div className="muted" style={{ fontSize: 13, marginBottom: 6 }}>Баланс</div>
              <div style={{ fontSize: 24, fontWeight: 800 }}>🍌 {user?.bananas ?? status.bananas ?? 0} · 💎 {user?.diamonds ?? status.diamonds ?? 0}</div>
            </div>

            {result && (
              <div className="glass" style={{ padding: 22, marginBottom: 16, textAlign: 'center', borderColor: result.won ? 'rgba(52,211,153,.4)' : undefined }}>
                <div style={{ fontSize: 40, marginBottom: 8 }}>{result.won ? '🎉' : '😔'}</div>
                <div style={{ fontWeight: 700, fontSize: 18 }}>
                  {result.won ? `Выиграл ${result.diamonds} 🍌!` : 'Не повезло'}
                </div>
                <p className="muted" style={{ fontSize: 13, marginTop: 6 }}>
                  {result.won ? 'Трать на бесплатные генерации Nano Banana' : 'Попробуй завтра — удача любит настойчивых'}
                </p>
              </div>
            )}

            {status.freeAvailable ? (
              <button className="btn btn-accent btn-block btn-lg" onClick={() => spin('free')} disabled={spinning}>
                {spinning ? 'Крутится...' : '🎰 Крутить бесплатно!'}
              </button>
            ) : (
              <>
                <div className="glass" style={{ padding: '12px 16px', marginBottom: 12, textAlign: 'center' }}>
                  <span className="muted" style={{ fontSize: 13 }}>⏳ Бесплатный спин через {status.cooldown.h}ч {status.cooldown.m}мин</span>
                </div>
                <button className="btn btn-accent btn-block btn-lg" onClick={() => spin('paid')} disabled={spinning}>
                  {spinning ? 'Крутится...' : `💎 Крутить за ${status.extraSpinCost}`}
                </button>
              </>
            )}

            {/* Список призов */}
            <div style={{ marginTop: 20 }}>
              <div className="block-title" style={{ marginBottom: 10, fontSize: 14 }}>Призы</div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                {prizes.map((p, i) => (
                  <div key={p.id} style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: 13 }}>
                    <span style={{ width: 14, height: 14, borderRadius: 4, background: sectorColor(p, i), flexShrink: 0 }} />
                    <span>{p.label}</span>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
