'use client';

import { useEffect, useMemo, useState } from 'react';
import { useRouter } from 'next/navigation';
import { useAuth } from '@/contexts/AuthContext';
import Wordmark from '@/components/vyndr/Wordmark';

/**
 * /onboarding (Session 49) — first-run experience. 3 self-contained steps
 * (sports → books → weekly bankroll) → saves to /api/preferences with
 * onboarding_complete:true → /dashboard. Step 1 requires ≥1 sport; books +
 * limit are skippable.
 */

const SPORTS = [
  { id: 'mlb', label: 'MLB' },
  { id: 'nba', label: 'NBA' },
  { id: 'wnba', label: 'WNBA' },
  { id: 'soccer', label: 'Soccer' },
];
const BOOKS = [
  { id: 'draftkings', label: 'DraftKings' },
  { id: 'fanduel', label: 'FanDuel' },
  { id: 'betmgm', label: 'BetMGM' },
  { id: 'caesars', label: 'Caesars' },
  { id: 'bet365', label: 'bet365' },
  { id: 'odawa', label: 'Odawa Online' },
];
const LIMITS = [50, 100, 250, 500, 1000];

const ACCENT = 'var(--g-a)';

function Chip({ label, on, onClick }: { label: string; on: boolean; onClick: () => void }) {
  return (
    <button
      type="button"
      onClick={onClick}
      className="mono"
      style={{
        cursor: 'pointer', padding: '12px 18px', borderRadius: 10, fontSize: 13, fontWeight: 700, letterSpacing: '0.04em',
        background: on ? 'color-mix(in srgb, var(--g-a) 14%, transparent)' : 'var(--bg-2)',
        border: `1px solid ${on ? ACCENT : 'var(--border-hi)'}`,
        color: on ? ACCENT : 'var(--text-1)', transition: '.15s',
      }}
      aria-pressed={on}
    >
      {label}
    </button>
  );
}

export default function OnboardingPage() {
  const router = useRouter();
  const { user, session, loading } = useAuth();
  const [step, setStep] = useState(1);
  const [sports, setSports] = useState<string[]>([]);
  const [books, setBooks] = useState<string[]>([]);
  const [weeklyLimit, setWeeklyLimit] = useState<number | null>(null);
  const [customLimit, setCustomLimit] = useState('');
  const [saving, setSaving] = useState(false);

  // Must be signed in (our session lives client-side).
  useEffect(() => {
    if (!loading && !user) router.replace('/login?next=/onboarding');
  }, [loading, user, router]);

  const toggle = (list: string[], set: (v: string[]) => void, id: string) =>
    set(list.includes(id) ? list.filter((x) => x !== id) : [...list, id]);

  const finish = useMemo(() => async () => {
    setSaving(true);
    const limit = weeklyLimit ?? (customLimit ? Number(customLimit) : null);
    try {
      await fetch('/api/preferences', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', ...(session?.access_token ? { Authorization: `Bearer ${session.access_token}` } : {}) },
        body: JSON.stringify({ sports, books, weekly_limit: limit, onboarding_complete: true }),
      });
    } catch { /* still proceed — prefs are best-effort */ }
    setStep(4);
    setTimeout(() => router.replace('/dashboard'), 2000);
  }, [sports, books, weeklyLimit, customLimit, session, router]);

  if (loading || !user) {
    return <section style={{ minHeight: '60vh', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><p className="mono" style={{ color: 'var(--text-2)' }}>Loading…</p></section>;
  }

  return (
    <section className="scanlines" style={{ maxWidth: 560, margin: '0 auto', padding: '40px 16px 120px', minHeight: '70vh' }}>
      <div style={{ textAlign: 'center', marginBottom: 28 }}>
        <Wordmark size="md" />
        {step <= 3 && (
          <div className="mono" style={{ marginTop: 14, fontSize: 11, color: 'var(--text-2)', letterSpacing: '0.12em' }}>
            STEP {step} OF 3
          </div>
        )}
      </div>

      {/* STEP 1 — sports */}
      {step === 1 && (
        <div data-step="1">
          <h1 style={{ fontSize: 26, fontWeight: 800, letterSpacing: '-0.01em', marginBottom: 8 }}>What do you follow?</h1>
          <p style={{ color: 'var(--text-1)', fontSize: 14, marginBottom: 22 }}>Select the sports you bet on. VYNDR will prioritize your slate.</p>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 10, marginBottom: 28 }}>
            {SPORTS.map((s) => <Chip key={s.id} label={s.label} on={sports.includes(s.id)} onClick={() => toggle(sports, setSports, s.id)} />)}
          </div>
          <button type="button" disabled={sports.length === 0} onClick={() => setStep(2)} className="mono"
            style={{ width: '100%', padding: '14px', borderRadius: 10, fontWeight: 700, letterSpacing: '0.06em', cursor: sports.length ? 'pointer' : 'not-allowed', border: 'none', background: sports.length ? ACCENT : 'var(--bg-3)', color: sports.length ? '#06060B' : 'var(--text-2)' }}>
            NEXT →
          </button>
        </div>
      )}

      {/* STEP 2 — books */}
      {step === 2 && (
        <div data-step="2">
          <h1 style={{ fontSize: 26, fontWeight: 800, letterSpacing: '-0.01em', marginBottom: 8 }}>Where do you bet?</h1>
          <p style={{ color: 'var(--text-1)', fontSize: 14, marginBottom: 22 }}>Connect your book so VYNDR can show you the best lines and enable one-tap betting.</p>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 10, marginBottom: 28 }}>
            {BOOKS.map((b) => <Chip key={b.id} label={b.label} on={books.includes(b.id)} onClick={() => toggle(books, setBooks, b.id)} />)}
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
            <button type="button" onClick={() => setStep(3)} className="mono"
              style={{ flex: 1, padding: '14px', borderRadius: 10, fontWeight: 700, letterSpacing: '0.06em', cursor: 'pointer', border: 'none', background: ACCENT, color: '#06060B' }}>NEXT →</button>
            <button type="button" onClick={() => { setBooks([]); setStep(3); }} className="mono" style={{ background: 'transparent', border: 'none', color: 'var(--text-2)', cursor: 'pointer', fontSize: 12 }}>Skip</button>
          </div>
        </div>
      )}

      {/* STEP 3 — weekly limit */}
      {step === 3 && (
        <div data-step="3">
          <h1 style={{ fontSize: 26, fontWeight: 800, letterSpacing: '-0.01em', marginBottom: 8 }}>Set your weekly bankroll</h1>
          <p style={{ color: 'var(--text-1)', fontSize: 14, marginBottom: 22 }}>VYNDR helps you stay disciplined. We&apos;ll track your weekly action.</p>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 10, marginBottom: 16 }}>
            {LIMITS.map((l) => <Chip key={l} label={`$${l}`} on={weeklyLimit === l} onClick={() => { setWeeklyLimit(l); setCustomLimit(''); }} />)}
          </div>
          <input
            inputMode="numeric" value={customLimit}
            onChange={(e) => { setCustomLimit(e.target.value.replace(/[^0-9]/g, '')); setWeeklyLimit(null); }}
            placeholder="Custom amount ($)"
            className="mono"
            style={{ width: '100%', padding: '12px 14px', borderRadius: 10, background: 'var(--bg-2)', border: '1px solid var(--border-hi)', color: '#fff', fontSize: 14, marginBottom: 28, outline: 'none' }}
          />
          <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
            <button type="button" disabled={saving} onClick={finish} className="mono"
              style={{ flex: 1, padding: '14px', borderRadius: 10, fontWeight: 700, letterSpacing: '0.06em', cursor: 'pointer', border: 'none', background: ACCENT, color: '#06060B' }}>
              {saving ? 'SAVING…' : 'FINISH →'}
            </button>
            <button type="button" onClick={() => { setWeeklyLimit(null); setCustomLimit(''); finish(); }} className="mono" style={{ background: 'transparent', border: 'none', color: 'var(--text-2)', cursor: 'pointer', fontSize: 12 }}>Skip</button>
          </div>
        </div>
      )}

      {/* COMPLETION */}
      {step === 4 && (
        <div data-step="done" style={{ textAlign: 'center', paddingTop: 30 }}>
          <div className="mono glitch-hover amber-glow" data-text="SIGNAL ACTIVE" style={{ fontSize: 22, fontWeight: 800, color: ACCENT, letterSpacing: '0.12em', marginBottom: 14 }}>SIGNAL ACTIVE</div>
          <h1 style={{ fontSize: 28, fontWeight: 800, letterSpacing: '-0.01em', marginBottom: 10 }}>You&apos;re locked in.</h1>
          <p className="mono" style={{ color: 'var(--text-1)', fontSize: 13 }}>Taking you to your slate…</p>
        </div>
      )}
    </section>
  );
}
