'use client';
// UserCenter.tsx — 应用外壳：顶栏 + 导航 + 视图切换 + 会话编排。承袭 ucapp.jsx UserCenterApp。
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { Icon, Mark } from './icons';
import { LangSeg } from './shared';
import Login from './Login';
import Overview from './Overview';
import Subscription from './Subscription';
import Redeem from './Redeem';
import Invite from './Invite';
import Settings from './Settings';
import { useUI } from '../lib/theme';
import { makeT } from '../lib/i18n';
import { apiMode, getClient } from '../lib/api/client';
import { hasRefresh } from '../lib/api/session';
import type { Me } from '../lib/api/types';

type View = 'overview' | 'sub' | 'redeem' | 'invite' | 'settings';
const ORDER: View[] = ['overview', 'sub', 'redeem', 'invite', 'settings'];

function useIsMobile() {
  const [m, setM] = useState(false);
  useEffect(() => {
    const f = () => setM(window.innerWidth <= 700);
    f();
    window.addEventListener('resize', f);
    return () => window.removeEventListener('resize', f);
  }, []);
  return m;
}

export default function UserCenter() {
  const { lang, setLang, theme, toggleTheme } = useUI();
  const t = makeT(lang);
  const api = getClient();
  const mobile = useIsMobile();

  const [authed, setAuthed] = useState(false);
  const [ready, setReady] = useState(false);
  const [me, setMe] = useState<Me | null>(null);
  const [view, setView] = useState<View>('overview');
  const [dir, setDir] = useState(0);
  const touchRef = useRef({ x: 0, y: 0 });

  const loadMe = useCallback(() => {
    api.getMe().then(setMe).catch(() => {});
  }, [api]);

  // 启动会话：mock 直接进面板;http 有 refresh 则静默续期,否则去登录
  useEffect(() => {
    let alive = true;
    (async () => {
      if (apiMode() === 'mock') {
        if (alive) setAuthed(true);
      } else if (hasRefresh()) {
        try {
          await api.refresh();
          if (alive) setAuthed(true);
        } catch {
          if (alive) setAuthed(false);
        }
      }
      if (alive) setReady(true);
    })();
    return () => {
      alive = false;
    };
  }, [api]);

  useEffect(() => {
    if (authed) loadMe();
    else setMe(null);
  }, [authed, loadMe]);

  function go(id: View) {
    const a = ORDER.indexOf(view);
    const b = ORDER.indexOf(id);
    setDir(b > a ? 1 : b < a ? -1 : 0);
    setView(id);
    setTimeout(() => setDir(0), 300);
  }
  function onTouchStart(e: React.TouchEvent) {
    const p = e.touches[0];
    touchRef.current = { x: p.clientX, y: p.clientY };
  }
  function onTouchEnd(e: React.TouchEvent) {
    const p = e.changedTouches[0];
    const dx = p.clientX - touchRef.current.x;
    const dy = p.clientY - touchRef.current.y;
    if (Math.abs(dx) > 60 && Math.abs(dx) > Math.abs(dy) * 1.5) {
      const i = ORDER.indexOf(view);
      const ni = dx < 0 ? Math.min(ORDER.length - 1, i + 1) : Math.max(0, i - 1);
      if (ni !== i) go(ORDER[ni]);
    }
  }

  async function signOut() {
    await api.logout().catch(() => {});
    setAuthed(false);
    setView('overview');
  }

  if (!ready) {
    return <div style={{ minHeight: '100vh', background: 'var(--bg)' }} />;
  }
  if (!authed) {
    return <Login onDone={() => { setAuthed(true); setView('overview'); }} />;
  }

  const nav: [View, string, string][] = [
    ['overview', 'layout-dashboard', t('navOverview')],
    ['sub', 'link', t('navSub')],
    ['redeem', 'ticket', t('navRedeem')],
    ['invite', 'users', t('navInvite')],
    ['settings', 'settings', t('navSettings')],
  ];

  let main: React.ReactNode = null;
  if (!me && (view === 'overview')) {
    main = <div style={{ fontSize: 14, color: 'var(--fg3)' }}>{t('loading')}</div>;
  } else if (view === 'overview' && me) {
    main = <Overview t={t} lang={lang} me={me} mobile={mobile} goSub={() => go('sub')} goRedeem={() => go('redeem')} />;
  } else if (view === 'sub') {
    main = <Subscription t={t} mobile={mobile} />;
  } else if (view === 'redeem') {
    main = <Redeem t={t} lang={lang} onRedeemed={loadMe} />;
  } else if (view === 'invite') {
    main = <Invite t={t} />;
  } else if (view === 'settings') {
    main = <Settings t={t} lang={lang} totpEnabled={me?.totpEnabled ?? false} onTotpChange={loadMe} />;
  }

  const navBtns = nav.map(([id, ic, l]) => (
    <button
      key={id}
      onClick={() => go(id)}
      aria-current={view === id ? 'page' : undefined}
      style={{ display: 'inline-flex', alignItems: 'center', gap: 7, border: 'none', cursor: 'pointer', borderRadius: 'var(--radius-md)', padding: '8px 13px', flexShrink: 0, background: view === id ? 'var(--accent-subtle)' : 'transparent', color: view === id ? 'var(--accent)' : 'var(--fg2)', fontFamily: 'var(--font-sans)', fontSize: 13.5, fontWeight: view === id ? 700 : 500, whiteSpace: 'nowrap' }}
    >
      <Icon name={ic} size={15} color={view === id ? 'var(--accent)' : 'var(--fg3)'} />
      {l}
    </button>
  ));

  return (
    <div style={{ minHeight: '100vh', background: 'var(--bg)', fontFamily: 'var(--font-sans)' }}>
      {/* top bar */}
      <div style={{ position: 'sticky', top: 0, zIndex: 10, background: 'color-mix(in srgb, var(--bg) 85%, transparent)', backdropFilter: 'blur(12px)', borderBottom: '1px solid var(--border)' }}>
        <div style={{ maxWidth: 1000, margin: '0 auto', padding: mobile ? '0 16px' : '0 24px', height: mobile ? 54 : 60, display: 'flex', alignItems: 'center', gap: mobile ? 12 : 22 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
            <Mark size={26} />
            <span style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 16.5, color: 'var(--fg1)' }}>穿山甲</span>
          </div>
          {!mobile && <nav style={{ display: 'flex', gap: 4, flex: 1 }}>{navBtns}</nav>}
          {mobile && <div style={{ flex: 1 }} />}
          <button onClick={toggleTheme} aria-label="theme" title="theme" style={{ border: 'none', background: 'transparent', cursor: 'pointer', color: 'var(--fg2)', padding: 6, display: 'flex' }}>
            <Icon name={theme === 'dark' ? 'sun' : 'moon'} size={17} color="var(--fg3)" />
          </button>
          <LangSeg lang={lang} setLang={setLang} />
          <button onClick={signOut} style={{ display: 'inline-flex', alignItems: 'center', gap: 7, border: 'none', background: 'transparent', cursor: 'pointer', color: 'var(--fg2)', fontSize: 13, fontWeight: 600, padding: 6 }}>
            <Icon name="log-out" size={15} color="var(--fg3)" />
            {!mobile && t('signOut')}
          </button>
        </div>
        {mobile && <nav style={{ display: 'flex', gap: 2, padding: '0 12px 8px', overflowX: 'auto' }}>{navBtns}</nav>}
      </div>
      <div
        onTouchStart={mobile ? onTouchStart : undefined}
        onTouchEnd={mobile ? onTouchEnd : undefined}
        style={{ maxWidth: 1000, margin: '0 auto', padding: mobile ? '20px 16px 40px' : '30px 24px 48px' }}
      >
        <div key={view} style={{ animation: dir !== 0 ? `uc-in-${dir === 1 ? 'l' : 'r'} 200ms var(--ease-out)` : 'none' }}>
          {main}
        </div>
      </div>
    </div>
  );
}
