'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { useAuth } from '@/contexts/AuthContext';
import { currentAccessToken } from '@/lib/authToken';

/**
 * /settings (Session 42 — Player Intelligence design).
 *
 * Replaces the Session-41 redirect with the design's full settings surface.
 * NOTE: /settings/security is a REAL MFA enrollment page — this page LINKS to
 * it, it does not replace it.
 */

const Section = ({ label, color = 'var(--text-1)', dot = 'var(--g-a)', children }: { label: string; color?: string; dot?: string; children: React.ReactNode }) => (
  <div style={{ background: 'var(--bg-1)', border: '1px solid var(--border)', borderRadius: 12, padding: '18px 20px' }}>
    <div style={{ display: 'flex', alignItems: 'center', gap: 9, marginBottom: 16 }}>
      <span style={{ width: 6, height: 6, background: dot, borderRadius: 1 }} />
      <span className="mono" style={{ fontSize: 11, fontWeight: 600, letterSpacing: '0.1em', color }}>{label}</span>
    </div>
    {children}
  </div>
);

const Row = ({ children }: { children: React.ReactNode }) => (
  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '9px 0', gap: 12, flexWrap: 'wrap' }}>{children}</div>
);
const Divider = () => <div style={{ height: 1, background: '#14141E', margin: '4px 0' }} />;

function Toggle({ on, onClick }: { on: boolean; onClick: () => void }) {
  return (
    <button onClick={onClick} aria-pressed={on} style={{ cursor: 'pointer', appearance: 'none', position: 'relative', width: 40, height: 22, borderRadius: 11, border: '1px solid var(--border-hi)', background: on ? 'var(--g-a)' : '#15151f' }}>
      <span style={{ position: 'absolute', top: 1, left: on ? 19 : 1, width: 18, height: 18, borderRadius: '50%', background: on ? '#06060B' : '#7a7a8e', transition: '.18s' }} />
    </button>
  );
}

function tierLabel(tier: string) {
  if (tier === 'desk') return { label: 'DESK', color: '#00ffb8' };
  if (tier === 'analyst') return { label: 'ANALYST', color: 'var(--g-b)' };
  return { label: 'FREE', color: 'var(--text-1)' };
}

const PREF_SPORTS = [
  { id: 'mlb', label: 'MLB' }, { id: 'nba', label: 'NBA' }, { id: 'wnba', label: 'WNBA' }, { id: 'soccer', label: 'Soccer' },
];
const PREF_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' },
];

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

export default function SettingsPage() {
  const router = useRouter();
  const { user, tier, session } = useAuth();
  const [emailAlerts, setEmailAlerts] = useState(true);
  const [pushAlerts, setPushAlerts] = useState(false);
  const [deleteText, setDeleteText] = useState('');
  const [deleting, setDeleting] = useState(false);
  const [delError, setDelError] = useState('');
  // Session 60 (5.4) — the daily read meter (metered tiers only).
  const [meter, setMeter] = useState<{ unlimited: boolean; used: number | null; limit: number | null; remaining?: number | null } | null>(null);
  useEffect(() => {
    const token = session?.access_token;
    if (!token) return;
    let active = true;
    fetch('/api/user/scan-meter', { headers: { Authorization: `Bearer ${token}` } })
      .then((r) => (r.ok ? r.json() : null))
      .then((data) => { if (active && data && typeof data.unlimited === 'boolean') setMeter(data); })
      .catch(() => { /* meter hides itself */ });
    return () => { active = false; };
  }, [session]);

  // Session 49 — onboarding preferences (load + edit + save).
  const [prefSports, setPrefSports] = useState<string[]>([]);
  const [prefBooks, setPrefBooks] = useState<string[]>([]);
  const [prefLimit, setPrefLimit] = useState<string>('');
  const [prefSaving, setPrefSaving] = useState(false);
  const [prefSaved, setPrefSaved] = useState(false);

  useEffect(() => {
    if (!session?.access_token) return;
    fetch('/api/preferences', { headers: { Authorization: `Bearer ${session.access_token}` } })
      .then((r) => (r.ok ? r.json() : null))
      .then((p) => {
        if (!p) return;
        setPrefSports(Array.isArray(p.sports) ? p.sports : []);
        setPrefBooks(Array.isArray(p.books) ? p.books : []);
        setPrefLimit(p.weekly_limit != null ? String(p.weekly_limit) : '');
      })
      .catch(() => {});
  }, [session]);

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

  const savePrefs = async () => {
    setPrefSaving(true);
    setPrefSaved(false);
    try {
      const res = await fetch('/api/preferences', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', ...(session?.access_token ? { Authorization: `Bearer ${session.access_token}` } : {}) },
        body: JSON.stringify({ sports: prefSports, books: prefBooks, weekly_limit: prefLimit ? Number(prefLimit) : null }),
      });
      if (res.ok) setPrefSaved(true);
    } catch { /* best-effort */ } finally { setPrefSaving(false); }
  };

  // A1 Session 10 — public ledger profile: claim a handle + the ONE explicit
  // publish toggle. PRIVATE BY DEFAULT — nothing is public until the user
  // flips the toggle and saves.
  const [pfHandle, setPfHandle] = useState('');
  const [pfPublished, setPfPublished] = useState(false);
  const [pfSaving, setPfSaving] = useState(false);
  const [pfMsg, setPfMsg] = useState<{ ok: boolean; text: string } | null>(null);
  const [pfLive, setPfLive] = useState<{ handle: string; published: boolean } | null>(null);

  useEffect(() => {
    if (!session?.access_token) return;
    fetch('/api/profiles/me', { headers: { Authorization: `Bearer ${session.access_token}` } })
      .then((r) => (r.ok ? r.json() : null))
      .then((d) => {
        const p = d?.profile;
        if (!p) return;
        setPfHandle(p.handle || '');
        setPfPublished(Boolean(p.published));
        setPfLive({ handle: p.handle || '', published: Boolean(p.published) });
      })
      .catch(() => {});
  }, [session]);

  const saveProfile = async () => {
    setPfSaving(true);
    setPfMsg(null);
    try {
      const res = await fetch('/api/profiles/me', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', ...(session?.access_token ? { Authorization: `Bearer ${session.access_token}` } : {}) },
        body: JSON.stringify({ handle: pfHandle, published: pfPublished }),
      });
      const data = await res.json().catch(() => ({}));
      if (res.ok) {
        setPfLive({ handle: pfHandle, published: pfPublished });
        setPfMsg({ ok: true, text: pfPublished ? 'Published. Your settled record is live.' : 'Saved. Your record stays private.' });
      } else if (res.status === 409) {
        setPfMsg({ ok: false, text: 'That handle is taken.' });
      } else {
        setPfMsg({ ok: false, text: data?.error || 'Could not save profile.' });
      }
    } catch {
      setPfMsg({ ok: false, text: 'Network error. Try again.' });
    } finally {
      setPfSaving(false);
    }
  };

  const plan = tierLabel(tier || 'free');
  const canDelete = deleteText === 'DELETE';

  const handleDelete = async () => {
    if (!canDelete || deleting) return;
    setDeleting(true);
    setDelError('');
    try {
      const token = currentAccessToken();
      const res = await fetch('/api/user/profile', {
        method: 'DELETE',
        headers: token ? { Authorization: `Bearer ${token}` } : {},
      });
      if (res.ok) {
        router.replace('/?deleted=1');
        return;
      }
      // No fake success — if the backend can't process it, say so.
      setDelError('Account deletion could not be completed automatically. Email support@vyndr.app and we will remove your account within 48 hours.');
    } catch {
      setDelError('Network error. Try again, or email support@vyndr.app.');
    } finally {
      setDeleting(false);
    }
  };

  return (
    <section style={{ maxWidth: 640, margin: '0 auto', padding: '24px 16px 120px' }}>
      <div style={{ marginBottom: 24 }}>
        <div className="mono" style={{ fontSize: 11, color: 'var(--g-a)', letterSpacing: '0.12em', marginBottom: 10 }}>SETTINGS</div>
        <h1 style={{ margin: 0, fontSize: 30, fontWeight: 800, letterSpacing: '-0.01em' }}>Settings</h1>
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        {/* ACCOUNT */}
        <Section label="ACCOUNT">
          <Row>
            <span style={{ fontSize: 13, color: 'var(--text-1)' }}>Email</span>
            <span className="mono" style={{ fontSize: 13, color: 'var(--text-0)' }}>{user?.email || '—'}</span>
          </Row>
          <Divider />
          <Row>
            <span style={{ fontSize: 13, color: 'var(--text-1)' }}>Plan</span>
            <span className="mono" style={{ display: 'inline-flex', alignItems: 'center', fontWeight: 700, fontSize: 11, letterSpacing: '0.06em', color: plan.color, background: 'color-mix(in srgb, currentColor 12%, transparent)', border: '1px solid color-mix(in srgb, currentColor 40%, transparent)', padding: '3px 10px', borderRadius: 5 }}>{plan.label}</span>
          </Row>
          <Divider />
          <Row>
            <div>
              <div style={{ fontSize: 13, color: 'var(--text-0)' }}>Security &amp; two-factor</div>
              <div style={{ fontSize: 11, color: 'var(--text-1)', marginTop: 2 }}>Authenticator-app MFA</div>
            </div>
            <a href="/settings/security" className="mono" style={{ cursor: 'pointer', background: 'transparent', border: '1px solid var(--border-hi)', borderRadius: 8, padding: '8px 14px', fontSize: 11, fontWeight: 600, color: 'var(--text-1)', textDecoration: 'none' }}>MANAGE →</a>
          </Row>
        </Section>

        {/* SUBSCRIPTION */}
        <Section label="SUBSCRIPTION">
          {/* Session 60 (5.4) — the daily read meter for METERED tiers, from
              the live limiter's rolling-24h window (never disagrees with the
              gate). Unlimited tiers hide it. */}
          {meter && !meter.unlimited && meter.limit != null && (
            <>
              <Row>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 13, color: 'var(--text-0)' }}>Reads today</div>
                  <div style={{ marginTop: 8, height: 6, background: 'var(--bg-3)', borderRadius: 3, overflow: 'hidden', maxWidth: 260 }}>
                    <div style={{ width: `${Math.min(100, Math.round(((meter.used ?? 0) / meter.limit) * 100))}%`, height: '100%', background: (meter.remaining ?? 1) <= 0 ? 'var(--miss)' : 'var(--g-a)', borderRadius: 3 }} />
                  </div>
                </div>
                <span className="mono" style={{ fontSize: 13, fontWeight: 700, color: (meter.remaining ?? 1) <= 0 ? 'var(--miss)' : 'var(--text-0)' }}>
                  {meter.used ?? 0} of {meter.limit}
                </span>
              </Row>
              <Divider />
            </>
          )}
          <Row>
            <div>
              <div style={{ fontSize: 14, fontWeight: 600, color: '#fff' }}>VYNDR {plan.label === 'FREE' ? 'Free' : plan.label === 'DESK' ? 'Desk' : 'Analyst'}</div>
              <div className="mono" style={{ fontSize: 12, color: 'var(--text-1)', marginTop: 3 }}>
                {meter && !meter.unlimited && meter.limit != null ? `${meter.limit} reads / day` : plan.label === 'FREE' ? '3 reads / day' : 'Active subscription'}
              </div>
            </div>
            <div style={{ display: 'flex', gap: 9 }}>
              {plan.label !== 'FREE' && (
                <button onClick={() => router.push('/profile')} className="mono" style={{ cursor: 'pointer', background: 'transparent', border: '1px solid var(--border-hi)', borderRadius: 8, padding: '9px 15px', fontSize: 11, fontWeight: 600, color: 'var(--text-1)' }}>MANAGE</button>
              )}
              <a href="/pricing" className="mono" style={{ cursor: 'pointer', background: 'var(--g-a)', border: '1px solid var(--g-a)', borderRadius: 8, padding: '9px 15px', fontSize: 11, fontWeight: 700, color: '#06060B', textDecoration: 'none' }}>{plan.label === 'FREE' ? 'UPGRADE' : 'CHANGE PLAN'}</a>
            </div>
          </Row>
        </Section>

        {/* PREFERENCES (Session 49) */}
        <Section label="PREFERENCES">
          <div style={{ fontSize: 13, color: 'var(--text-0)', marginBottom: 8 }}>Sports</div>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginBottom: 18 }}>
            {PREF_SPORTS.map((s) => <PrefChip key={s.id} label={s.label} on={prefSports.includes(s.id)} onClick={() => toggle(prefSports, setPrefSports, s.id)} />)}
          </div>
          <div style={{ fontSize: 13, color: 'var(--text-0)', marginBottom: 8 }}>Books</div>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginBottom: 18 }}>
            {PREF_BOOKS.map((b) => <PrefChip key={b.id} label={b.label} on={prefBooks.includes(b.id)} onClick={() => toggle(prefBooks, setPrefBooks, b.id)} />)}
          </div>
          <div style={{ fontSize: 13, color: 'var(--text-0)', marginBottom: 8 }}>Weekly limit</div>
          <input inputMode="numeric" value={prefLimit} onChange={(e) => setPrefLimit(e.target.value.replace(/[^0-9]/g, ''))} placeholder="$ amount"
            className="mono" style={{ width: 160, padding: '9px 12px', borderRadius: 8, background: 'var(--bg-2)', border: '1px solid var(--border-hi)', color: '#fff', fontSize: 13, outline: 'none', marginBottom: 16 }} />
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <button type="button" onClick={savePrefs} disabled={prefSaving} className="mono"
              style={{ cursor: 'pointer', padding: '9px 16px', borderRadius: 8, fontWeight: 700, fontSize: 11, letterSpacing: '0.04em', border: '1px solid var(--g-a)', background: 'var(--g-a)', color: '#06060B' }}>
              {prefSaving ? 'SAVING…' : 'SAVE'}
            </button>
            {prefSaved && <span className="mono" style={{ fontSize: 12, color: 'var(--g-a)' }}>Saved ✓</span>}
          </div>
        </Section>

        {/* PUBLIC PROFILE (A1 Session 10) */}
        <Section label="PUBLIC PROFILE">
          <p style={{ margin: '0 0 14px', fontSize: 13, lineHeight: 1.55, color: 'var(--text-1)' }}>
            Publishing puts your ENTIRE settled record on a public page — wins and misses. Private by default.
          </p>
          <div style={{ fontSize: 13, color: 'var(--text-0)', marginBottom: 8 }}>Handle</div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 16, flexWrap: 'wrap' }}>
            <span className="mono" style={{ fontSize: 13, color: 'var(--text-1)' }}>vyndr.app/u/</span>
            <input
              value={pfHandle}
              onChange={(e) => setPfHandle(e.target.value.toLowerCase().replace(/[^a-z0-9_]/g, '').slice(0, 20))}
              placeholder="your_handle"
              aria-label="Public profile handle"
              className="mono"
              style={{ width: 200, padding: '9px 12px', borderRadius: 8, background: 'var(--bg-2)', border: '1px solid var(--border-hi)', color: '#fff', fontSize: 13, outline: 'none' }}
            />
          </div>
          <Row>
            <div>
              <div style={{ fontSize: 13, color: 'var(--text-0)' }}>Publish my record</div>
              <div style={{ fontSize: 11, color: 'var(--text-1)', marginTop: 2 }}>Every settled read, nothing curated</div>
            </div>
            <Toggle on={pfPublished} onClick={() => setPfPublished((v) => !v)} />
          </Row>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginTop: 12, flexWrap: 'wrap' }}>
            <button type="button" onClick={saveProfile} disabled={pfSaving || pfHandle.length < 3} className="mono"
              style={{ cursor: pfHandle.length >= 3 ? 'pointer' : 'not-allowed', padding: '9px 16px', borderRadius: 8, fontWeight: 700, fontSize: 11, letterSpacing: '0.04em', border: '1px solid var(--g-a)', background: pfHandle.length >= 3 ? 'var(--g-a)' : 'transparent', color: pfHandle.length >= 3 ? '#06060B' : 'var(--text-1)' }}>
              {pfSaving ? 'SAVING…' : 'SAVE PROFILE'}
            </button>
            {pfMsg && (
              <span className="mono" style={{ fontSize: 12, color: pfMsg.ok ? 'var(--g-a)' : 'var(--miss)' }}>{pfMsg.text}</span>
            )}
            {pfLive?.published && pfLive.handle && (
              <a href={`/u/${pfLive.handle}`} className="mono" style={{ fontSize: 12, color: 'var(--g-a)', textDecoration: 'none' }}>
                VIEW PUBLIC PAGE →
              </a>
            )}
          </div>
        </Section>

        {/* NOTIFICATIONS */}
        <Section label="NOTIFICATIONS">
          <Row>
            <div>
              <div style={{ fontSize: 13, color: 'var(--text-0)' }}>Email alerts</div>
              <div style={{ fontSize: 11, color: 'var(--text-1)', marginTop: 2 }}>Grade locks and line moves</div>
            </div>
            <Toggle on={emailAlerts} onClick={() => setEmailAlerts((v) => !v)} />
          </Row>
          <Divider />
          <Row>
            <div>
              <div style={{ fontSize: 13, color: 'var(--text-0)' }}>Push alerts</div>
              <div style={{ fontSize: 11, color: 'var(--text-1)', marginTop: 2 }}>Injury news for tracked players</div>
            </div>
            <Toggle on={pushAlerts} onClick={() => setPushAlerts((v) => !v)} />
          </Row>
        </Section>

        {/* DISPLAY */}
        <Section label="DISPLAY PREFERENCES">
          <Row>
            <div>
              <div style={{ fontSize: 13, color: 'var(--text-0)' }}>Display, odds format &amp; accessibility</div>
              <div style={{ fontSize: 11, color: 'var(--text-1)', marginTop: 2 }}>Region, odds format, text size, motion, contrast, colorblind-safe</div>
            </div>
            <button onClick={() => window.__prefs?.()} className="mono" style={{ cursor: 'pointer', background: 'transparent', border: '1px solid var(--border-hi)', borderRadius: 8, padding: '8px 14px', fontSize: 11, fontWeight: 600, color: 'var(--text-1)' }}>OPEN</button>
          </Row>
        </Section>

        {/* RESPONSIBLE PLAY */}
        <Section label="RESPONSIBLE PLAY" color="var(--text-1)" dot="var(--amber)">
          <Row>
            <span style={{ fontSize: 13, color: 'var(--text-0)' }}>Set a weekly time limit</span>
            <a href="/responsible-gambling" className="mono" style={{ cursor: 'pointer', background: 'transparent', border: '1px solid var(--border-hi)', borderRadius: 8, padding: '8px 14px', fontSize: 11, fontWeight: 600, color: 'var(--text-1)', textDecoration: 'none' }}>CONFIGURE</a>
          </Row>
          <Divider />
          <Row>
            <span style={{ fontSize: 13, color: 'var(--text-0)' }}>Self-exclusion</span>
            <a href="/responsible-gambling" className="mono" style={{ cursor: 'pointer', background: 'transparent', border: '1px solid #FFB34740', borderRadius: 8, padding: '8px 14px', fontSize: 11, fontWeight: 600, color: 'var(--amber)', textDecoration: 'none' }}>TAKE A BREAK</a>
          </Row>
        </Section>

        {/* DANGER ZONE */}
        <div style={{ background: '#0E0808', border: '1px solid #3A1A1A', borderRadius: 12, padding: '18px 20px' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 9, marginBottom: 14 }}>
            <span style={{ width: 6, height: 6, background: 'var(--miss)', borderRadius: 1 }} />
            <span className="mono" style={{ fontSize: 11, fontWeight: 600, letterSpacing: '0.1em', color: '#FF7A6B' }}>DANGER ZONE</span>
          </div>
          <p style={{ margin: '0 0 14px', fontSize: 13, lineHeight: 1.55, color: '#9A8585' }}>
            Deleting your account is permanent. All grade history and tracked players will be lost. Type{' '}
            <strong className="mono" style={{ color: '#FF7A6B' }}>DELETE</strong> to confirm.
          </p>
          <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
            <input
              value={deleteText}
              onChange={(e) => setDeleteText(e.target.value)}
              placeholder="Type DELETE"
              aria-label="Type DELETE to confirm account deletion"
              className="mono"
              style={{ flex: 1, minWidth: 160, appearance: 'none', background: '#0A0606', border: '1px solid #3A1A1A', borderRadius: 8, padding: '10px 13px', fontSize: 13, color: '#fff', letterSpacing: '0.08em', outline: 'none' }}
            />
            <button
              onClick={handleDelete}
              disabled={!canDelete || deleting}
              className="mono"
              style={{
                cursor: canDelete && !deleting ? 'pointer' : 'not-allowed',
                appearance: 'none',
                background: canDelete ? 'var(--miss)' : '#1A0E0E',
                border: `1px solid ${canDelete ? 'var(--miss)' : '#3A1A1A'}`,
                borderRadius: 8,
                padding: '10px 18px',
                fontSize: 11,
                fontWeight: 700,
                color: canDelete ? '#0A0606' : '#6A4A4A',
                letterSpacing: '0.04em',
                transition: '.15s',
              }}
            >
              {deleting ? 'WORKING…' : 'DELETE ACCOUNT'}
            </button>
          </div>
          {delError && <p className="mono" style={{ marginTop: 12, fontSize: 12, color: '#FFB0A4', lineHeight: 1.5 }}>{delError}</p>}
        </div>
      </div>
    </section>
  );
}
