/* global React, Icon */

const { useState: useStateU, useEffect: useEffectU, useRef: useRefU } = React;

const DEFAULT_PROFILE = {
  nickname: '나',
  email: 'me@example.com',
  avatarColor: '#f4b731',
  avatarImage: null,
  currency: 'USD',
  notifyPriceAlerts: true,
  notifyMarketOpen: true,
  notifyChat: false,
  loggedIn: true,
};

function loadProfile() {
  try {
    const raw = localStorage.getItem('clab-profile');
    if (!raw) return DEFAULT_PROFILE;
    return { ...DEFAULT_PROFILE, ...JSON.parse(raw) };
  } catch (e) {
    return DEFAULT_PROFILE;
  }
}

function saveProfile(p) {
  try { localStorage.setItem('clab-profile', JSON.stringify(p)); } catch (e) {}
}

function Avatar({ profile, size = 44, fontSize }) {
  const fs = fontSize ?? Math.round(size * 0.4);
  if (profile.avatarImage) {
    return (
      <div style={{
        width: size, height: size, borderRadius: '50%',
        backgroundImage: `url(${profile.avatarImage})`,
        backgroundSize: 'cover', backgroundPosition: 'center',
        flexShrink: 0,
      }} />
    );
  }
  return (
    <div style={{
      width: size, height: size, borderRadius: '50%',
      background: profile.avatarColor, color: '#fff',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      fontWeight: 800, fontSize: fs, flexShrink: 0,
    }}>{(profile.nickname || '?').charAt(0)}</div>
  );
}

function UserMenu({ profile, anchorRef, onClose, goto, onLogout, t }) {
  const ref = useRefU(null);
  useEffectU(() => {
    const onDown = (e) => {
      if (ref.current && !ref.current.contains(e.target) && !anchorRef.current?.contains(e.target)) onClose();
    };
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('mousedown', onDown);
    window.addEventListener('keydown', onKey);
    return () => { document.removeEventListener('mousedown', onDown); window.removeEventListener('keydown', onKey); };
  }, []);

  const item = (label, icon, onClick, danger) => (
    <button onClick={() => { onClose(); onClick(); }} style={{
      display: 'flex', alignItems: 'center', gap: 10, width: '100%',
      padding: '10px 14px', border: 'none', background: 'transparent',
      color: danger ? 'var(--danger)' : 'var(--fg-1)',
      fontSize: 14, fontWeight: 500, cursor: 'pointer', textAlign: 'left',
      borderRadius: 8,
    }}
      onMouseEnter={(e) => e.currentTarget.style.background = 'var(--bg-muted)'}
      onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}
    >
      <span style={{ width: 18, display: 'inline-flex', justifyContent: 'center', color: danger ? 'var(--danger)' : 'var(--fg-2)' }}>{icon}</span>
      {label}
    </button>
  );

  return (
    <div ref={ref} style={{
      position: 'absolute', top: 56, right: 16, width: 280, zIndex: 120,
      background: 'var(--bg-card)', border: '1px solid var(--line)',
      borderRadius: 14, boxShadow: 'var(--shadow-3, 0 8px 32px rgba(0,0,0,0.18))',
      overflow: 'hidden',
    }}>
      <div style={{ padding: 16, borderBottom: '1px solid var(--line-soft)', display: 'flex', alignItems: 'center', gap: 12 }}>
        <Avatar profile={profile} size={44} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontWeight: 700, fontSize: 15 }}>{profile.nickname}</div>
          <div className="t-meta" style={{ fontSize: 12 }}>{profile.email}</div>
        </div>
      </div>
      <div style={{ padding: 6 }}>
        {item(t('myProfile'), '👤', () => goto({ tab: 'settings' }))}
        {item(t('portfolio'), '💼', () => goto({ tab: 'portfolio' }))}
        {item(t('notifySettings'), '🔔', () => goto({ tab: 'settings', section: 'notify' }))}
        {item(t('help'), '?', () => {})}
        <div style={{ height: 1, background: 'var(--line-soft)', margin: '6px 8px' }} />
        {item(t('logout'), '↦', onLogout, true)}
      </div>
    </div>
  );
}

function LoginScreen({ onLogin, goto, t }) {
  const [mode, setMode] = useStateU('login');
  const [email, setEmail] = useStateU('');
  const [pw, setPw] = useStateU('');
  const [nickname, setNickname] = useStateU('');
  const [err, setErr] = useStateU('');

  const submit = (e) => {
    e?.preventDefault();
    if (!email.includes('@')) return setErr(t('errEmail') !== 'errEmail' ? t('errEmail') : 'Please enter a valid email');
    if (pw.length < 6) return setErr('Password must be 6+ characters');
    if (mode === 'signup' && !nickname.trim()) return setErr('Please enter a nickname');
    setErr('');
    onLogin({
      email,
      nickname: mode === 'signup' ? nickname.trim() : email.split('@')[0],
    });
  };

  return (
    <div className="container page" data-screen-label="Login" style={{ display: 'flex', justifyContent: 'center', alignItems: 'flex-start', paddingTop: 40 }}>
      <div className="card card-pad-lg" style={{ width: '100%', maxWidth: 420 }}>
        <div style={{ textAlign: 'center', marginBottom: 24 }}>
          <div style={{
            width: 56, height: 56, borderRadius: 16,
            background: 'linear-gradient(135deg, var(--blue), var(--violet, #9080ff))',
            color: '#fff', display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
            fontWeight: 800, fontSize: 22, marginBottom: 12,
          }}>C</div>
          <div style={{ fontWeight: 800, fontSize: 22, letterSpacing: '-0.01em' }}>
            {mode === 'login' ? t('loginTitle') : t('signupTitle')}
          </div>
          <div className="t-meta" style={{ marginTop: 4 }}>
            {mode === 'login' ? t('loginSub') : t('signupSub')}
          </div>
        </div>

        <form onSubmit={submit}>
          {mode === 'signup' && (
            <div style={{ marginBottom: 12 }}>
              <div className="t-meta" style={{ marginBottom: 6 }}>{t('nickname')}</div>
              <input className="input" value={nickname} onChange={(e) => setNickname(e.target.value)} />
            </div>
          )}
          <div style={{ marginBottom: 12 }}>
            <div className="t-meta" style={{ marginBottom: 6 }}>{t('email')}</div>
            <input className="input" type="email" placeholder="you@example.com" value={email} onChange={(e) => setEmail(e.target.value)} autoFocus />
          </div>
          <div style={{ marginBottom: 16 }}>
            <div className="t-meta" style={{ marginBottom: 6 }}>{t('password')}</div>
            <input className="input" type="password" value={pw} onChange={(e) => setPw(e.target.value)} />
          </div>
          {err && <div style={{ padding: 10, marginBottom: 12, borderRadius: 10, background: 'var(--danger-soft, rgba(255,94,109,0.12))', color: 'var(--danger)', fontSize: 13 }}>{err}</div>}
          <button type="submit" className="btn btn--primary btn--lg btn--block" style={{ width: '100%' }}>
            {mode === 'login' ? t('login') : t('signupCta')}
          </button>
        </form>

        <div style={{ display: 'flex', alignItems: 'center', gap: 8, margin: '20px 0' }}>
          <div style={{ flex: 1, height: 1, background: 'var(--line-soft)' }} />
          <span className="t-meta" style={{ fontSize: 11 }}>{t('or')}</span>
          <div style={{ flex: 1, height: 1, background: 'var(--line-soft)' }} />
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          <button type="button" className="btn btn--lg" style={{ width: '100%' }}>{t('continueGoogle')}</button>
          <button type="button" className="btn btn--lg" style={{ width: '100%' }}>{t('continueApple')}</button>
        </div>

        <div style={{ textAlign: 'center', marginTop: 20, fontSize: 13 }}>
          <span className="t-meta">{mode === 'login' ? t('noAccount') : t('hasAccount')}</span>{' '}
          <button onClick={() => { setMode(mode === 'login' ? 'signup' : 'login'); setErr(''); }}
            style={{ background: 'none', border: 'none', color: 'var(--blue)', fontWeight: 700, cursor: 'pointer', padding: 0 }}>
            {mode === 'login' ? t('signup') : t('login')}
          </button>
        </div>
      </div>
    </div>
  );
}

function SettingsRow({ label, sub, children }) {
  return (
    <div style={{
      display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 16,
      padding: '14px 0', borderBottom: '1px solid var(--line-soft)',
    }}>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontWeight: 600, fontSize: 14 }}>{label}</div>
        {sub && <div className="t-meta" style={{ marginTop: 2, fontSize: 12 }}>{sub}</div>}
      </div>
      <div style={{ flexShrink: 0 }}>{children}</div>
    </div>
  );
}

function Toggle({ on, onChange }) {
  return (
    <button onClick={() => onChange(!on)} style={{
      width: 40, height: 24, borderRadius: 999, border: 'none', cursor: 'pointer',
      background: on ? 'var(--up)' : 'var(--line)', position: 'relative', transition: 'background .15s',
    }}>
      <span style={{
        position: 'absolute', top: 2, left: on ? 18 : 2,
        width: 20, height: 20, borderRadius: '50%', background: '#fff',
        transition: 'left .15s', boxShadow: '0 1px 3px rgba(0,0,0,0.2)',
      }} />
    </button>
  );
}

function SettingsScreen({ profile, setProfile, goto, onLogout, t, lang, setLang }) {
  const [draft, setDraft] = useStateU(profile);
  const [saved, setSaved] = useStateU(false);
  const fileRef = useRefU(null);

  const dirty = JSON.stringify(draft) !== JSON.stringify(profile);

  const save = () => {
    setProfile(draft);
    setSaved(true);
    setTimeout(() => setSaved(false), 2000);
  };

  const onPickImage = (e) => {
    const file = e.target.files?.[0];
    if (!file) return;
    if (file.size > 2 * 1024 * 1024) {
      alert(lang === 'ko' ? '이미지는 2MB 이하만 가능합니다' : 'Image must be 2MB or smaller');
      return;
    }
    const reader = new FileReader();
    reader.onload = () => setDraft({ ...draft, avatarImage: reader.result });
    reader.readAsDataURL(file);
    e.target.value = '';
  };

  const COLORS = ['#f4b731', '#3182f6', '#6a5cf2', '#ff5e6d', '#0f766e', '#c69a3a'];

  return (
    <div className="container page" data-screen-label="Settings">
      <button className="btn btn--ghost btn--sm" onClick={() => goto({ tab: 'home' })} style={{ marginBottom: 12 }}>
        {t('backHome')}
      </button>
      <div style={{ marginBottom: 24 }}>
        <div className="t-h1">{t('settingsTitle')}</div>
        <div className="t-meta" style={{ marginTop: 4 }}>{t('settingsSub')}</div>
      </div>

      <div className="grid" style={{ gridTemplateColumns: '1fr 1.2fr', gap: 16 }}>
        {/* Profile card */}
        <div className="card">
          <div style={{ fontWeight: 700, marginBottom: 16 }}>{t('profile')}</div>

          <div style={{ display: 'flex', alignItems: 'center', gap: 16, marginBottom: 18 }}>
            <Avatar profile={draft} size={72} fontSize={26} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div className="t-meta" style={{ marginBottom: 6, fontSize: 12 }}>{t('avatarImage')}</div>
              <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                <input ref={fileRef} type="file" accept="image/*" onChange={onPickImage} style={{ display: 'none' }} />
                <button className="btn btn--sm" onClick={() => fileRef.current?.click()}>
                  {t('uploadImage')}
                </button>
                {draft.avatarImage && (
                  <button className="btn btn--sm" onClick={() => setDraft({ ...draft, avatarImage: null })}>
                    {t('removeImage')}
                  </button>
                )}
              </div>
            </div>
          </div>

          <div style={{ marginBottom: 14 }}>
            <div className="t-meta" style={{ marginBottom: 6 }}>{t('avatarColor')}</div>
            <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
              {COLORS.map(c => (
                <button key={c} onClick={() => setDraft({ ...draft, avatarColor: c })}
                  style={{
                    width: 28, height: 28, borderRadius: '50%', background: c,
                    border: draft.avatarColor === c ? '2px solid var(--fg-1)' : '2px solid transparent',
                    cursor: 'pointer', padding: 0,
                  }} />
              ))}
            </div>
          </div>

          <div style={{ marginBottom: 14 }}>
            <div className="t-meta" style={{ marginBottom: 6 }}>{t('nickname')}</div>
            <input className="input" value={draft.nickname} maxLength={20}
              onChange={(e) => setDraft({ ...draft, nickname: e.target.value })} />
          </div>
          <div style={{ marginBottom: 14 }}>
            <div className="t-meta" style={{ marginBottom: 6 }}>{t('email')}</div>
            <input className="input" type="email" value={draft.email}
              onChange={(e) => setDraft({ ...draft, email: e.target.value })} />
          </div>

          <div style={{ display: 'flex', gap: 8, marginTop: 8 }}>
            <button className="btn btn--primary btn--lg" style={{ flex: 1 }} disabled={!dirty} onClick={save}>
              {saved ? t('saved') : t('saveChanges')}
            </button>
            {dirty && (
              <button className="btn btn--lg" onClick={() => setDraft(profile)}>{t('revert')}</button>
            )}
          </div>
        </div>

        {/* Preferences */}
        <div className="card">
          <div style={{ fontWeight: 700, marginBottom: 8 }}>{t('preferences')}</div>
          <SettingsRow label={t('language')} sub={t('languageSub')}>
            <div style={{ display: 'inline-flex', border: '1px solid var(--line)', borderRadius: 8, overflow: 'hidden' }}>
              {['ko','en'].map(L => (
                <button key={L} onClick={() => setLang(L)}
                  style={{
                    padding: '6px 14px', fontSize: 12, fontWeight: 700, cursor: 'pointer',
                    border: 'none',
                    background: lang === L ? 'var(--fg-1)' : 'transparent',
                    color: lang === L ? 'var(--bg-card)' : 'var(--fg-2)',
                  }}>
                  {L === 'ko' ? '한국어' : 'English'}
                </button>
              ))}
            </div>
          </SettingsRow>
          <SettingsRow label={t('baseCurrency')} sub={t('baseCurrencySub')}>
            <select className="input" value={draft.currency} onChange={(e) => setDraft({ ...draft, currency: e.target.value })}
              style={{ height: 36, width: 120 }}>
              <option>USD</option>
              <option>KRW</option>
              <option>EUR</option>
            </select>
          </SettingsRow>
          <SettingsRow label={t('priceAlerts')} sub={t('priceAlertsSub')}>
            <Toggle on={draft.notifyPriceAlerts} onChange={(v) => setDraft({ ...draft, notifyPriceAlerts: v })} />
          </SettingsRow>
          <SettingsRow label={t('marketOpenAlerts')} sub={t('marketOpenSub')}>
            <Toggle on={draft.notifyMarketOpen} onChange={(v) => setDraft({ ...draft, notifyMarketOpen: v })} />
          </SettingsRow>
          <SettingsRow label={t('chatAlerts')} sub={t('chatAlertsSub')}>
            <Toggle on={draft.notifyChat} onChange={(v) => setDraft({ ...draft, notifyChat: v })} />
          </SettingsRow>

          <div style={{ paddingTop: 18 }}>
            <button className="btn btn--lg" style={{ width: '100%', color: 'var(--danger)' }} onClick={onLogout}>
              {t('logout')}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { UserMenu, LoginScreen, SettingsScreen, Avatar, loadProfile, saveProfile, DEFAULT_PROFILE });
