/* global React, ReactDOM, CRYPTOLIVE_DATA, Icon, Coin, fmtPrice, fmtPct, HomeScreen, MarketScreen, AssetDetailScreen, PortfolioScreen, HoldingDetailScreen, LiveScreen, UserMenu, LoginScreen, SettingsScreen, Avatar, loadProfile, saveProfile, loadLang, makeT, LangContext, useT */

const { useState, useEffect, useRef } = React;

function SearchModal({ open, onClose, goto }) {
  const t = useT();
  const [q, setQ] = useState('');
  const inputRef = useRef(null);
  useEffect(() => { if (open) inputRef.current?.focus(); }, [open]);
  useEffect(() => {
    const fn = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', fn);
    return () => window.removeEventListener('keydown', fn);
  }, [onClose]);

  if (!open) return null;

  const results = q.trim() === ''
    ? CRYPTOLIVE_DATA.assets().slice(0, 6)
    : CRYPTOLIVE_DATA.assets().filter(a =>
        a.symbol.toLowerCase().includes(q.toLowerCase()) ||
        a.name.toLowerCase().includes(q.toLowerCase()) ||
        a.sector.toLowerCase().includes(q.toLowerCase())
      );

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <div style={{ padding: 16, borderBottom: '1px solid var(--line-soft)', display: 'flex', alignItems: 'center', gap: 12 }}>
          <Icon.search width="20" height="20" style={{ color: 'var(--fg-3)' }} />
          <input
            ref={inputRef}
            value={q}
            onChange={(e) => setQ(e.target.value)}
            placeholder={t('searchPlaceholder')}
            style={{ flex: 1, border: 'none', outline: 'none', fontSize: 16, fontFamily: 'inherit', background: 'transparent' }}
          />
          <kbd style={{ fontSize: 11, padding: '2px 6px', background: 'var(--bg-muted)', borderRadius: 4, color: 'var(--fg-3)', fontFamily: 'inherit' }}>ESC</kbd>
        </div>
        <div style={{ maxHeight: 400, overflowY: 'auto', padding: '8px 0' }}>
          {results.length === 0 ? (
            <div style={{ padding: '32px 16px', textAlign: 'center', color: 'var(--fg-3)' }}>{t('searchEmpty')}</div>
          ) : results.map(a => (
            <div key={a.id} className="row" style={{ margin: '0 8px', padding: '10px 12px', borderRadius: 12, borderBottom: 'none' }}
              onClick={() => { onClose(); goto({ tab: 'detail', assetId: a.id }); }}>
              <Coin id={a.id} symbol={a.symbol} size="sm" />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontWeight: 700, fontSize: 14 }}>{a.symbol} <span className="t-meta" style={{ fontWeight: 500 }}>· {a.name}</span></div>
                <div className="t-meta">{a.class} · {a.sector}</div>
              </div>
              <div className="t-num" style={{ fontWeight: 700, fontSize: 13 }}>${fmtPrice(a.tokenPrice)}</div>
              <div className={`t-num ${a.change24h >= 0 ? 'c-up' : 'c-down'}`} style={{ fontSize: 12, fontWeight: 600, minWidth: 50, textAlign: 'right' }}>
                {fmtPct(a.change24h)}
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function NotificationsPanel({ open, onClose }) {
  const t = useT();
  if (!open) return null;
  return (
    <div style={{ position: 'fixed', inset: 0, zIndex: 100 }} onClick={onClose}>
      <div style={{
        position: 'absolute', top: 60, right: 20, width: 360,
        background: 'white', borderRadius: 16, boxShadow: '0 8px 32px rgba(0,0,0,0.12)',
        overflow: 'hidden', maxHeight: '70vh', display: 'flex', flexDirection: 'column'
      }} onClick={(e) => e.stopPropagation()}>
        <div style={{ padding: 16, borderBottom: '1px solid var(--line-soft)', fontWeight: 700 }}>{t('notifTitle')}</div>
        <div style={{ overflowY: 'auto', padding: 8 }}>
          {CRYPTOLIVE_DATA.liveEvents().map((e, i) => {
            const sevPill = e.sev === 'danger' ? 'pill--danger' : e.sev === 'warn' ? 'pill--warn' : 'pill--blue';
            return (
              <div key={i} style={{ padding: 12, borderRadius: 12 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 2 }}>
                  <span className={`pill ${sevPill}`} style={{ height: 20, fontSize: 11 }}>{t('alertPill')}</span>
                  <span className="t-meta">{t('minsAgo', e.t.toFixed(0))}</span>
                </div>
                <div style={{ fontWeight: 700, fontSize: 14 }}>{e.title}</div>
                <div className="t-body-sm" style={{ marginTop: 2 }}>{e.msg}</div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

function sourceStatusLabel(status) {
  if (!status) return null;
  if (status.error) return `unavailable: ${status.error}`;
  if (status.stale || status.status === 'stale') return 'stale';
  return status.status === 'available' ? null : status.status;
}

function TickerBar({ goto }) {
  const realtimeStatus = CRYPTOLIVE_DATA.realtimeStatus();
  const assets = CRYPTOLIVE_DATA.realtimeAssets();
  const items = [...assets, ...assets];
  return (
    <div className="ticker">
      <div className="ticker-track">
        {items.map((a, i) => (
          <span key={i} className="ticker-item" onClick={() => goto({ tab: 'detail', assetId: a.id })} style={{ cursor: 'pointer' }}>
            <b>{a.symbol}</b>
            <span className="t-num">${fmtPrice(a.tokenPrice)}</span>
            <span className={`t-num ${a.change24h >= 0 ? 'c-up' : 'c-down'}`} style={{ fontWeight: 600 }}>{fmtPct(a.change24h)}</span>
            {sourceStatusLabel(a.sourceStatus) && (
              <span className="t-meta" title={a.sourceStatus.error || a.sourceStatus.source || 'realtime source status'}>{sourceStatusLabel(a.sourceStatus)}</span>
            )}
            {a.realtimeVenue && <span className="t-meta">{a.realtimeVenue}</span>}
          </span>
        ))}
        {realtimeStatus.error && (
          <span className="ticker-item">
            <b>Realtime</b>
            <span className="t-meta">unavailable: mock fallback</span>
          </span>
        )}
      </div>
    </div>
  );
}

function ThemeToggle() {
  const [dark, setDark] = useState(() => {
    try { return localStorage.getItem('clab-theme') === 'dark'; } catch (e) { return false; }
  });
  useEffect(() => {
    document.documentElement.setAttribute('data-theme', dark ? 'dark' : 'light');
    try { localStorage.setItem('clab-theme', dark ? 'dark' : 'light'); } catch (e) {}
  }, [dark]);
  return (
    <button className="icon-btn" onClick={() => setDark(!dark)} title={dark ? '라이트 모드' : '다크 모드'} aria-label="테마 전환">
      {dark ? (
        <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41" stroke="currentColor" strokeWidth="2" strokeLinecap="round" fill="none"/></svg>
      ) : (
        <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><path d="M21 12.8A9 9 0 0 1 11.2 3a7 7 0 1 0 9.8 9.8Z"/></svg>
      )}
    </button>
  );
}

function App() {
  const [route, setRoute] = useState({ tab: 'home' });
  const [searchOpen, setSearchOpen] = useState(false);
  const [notifOpen, setNotifOpen] = useState(false);
  const [userMenuOpen, setUserMenuOpen] = useState(false);
  const [profile, setProfile] = useState(() => loadProfile());
  const [lang, setLang] = useState(() => loadLang());
  const [, setDataVersion] = useState(0);
  const avatarRef = useRef(null);
  const t = makeT(lang);

  useEffect(() => { saveProfile(profile); }, [profile]);
  useEffect(() => {
    const unsubscribe = CRYPTOLIVE_DATA.subscribe(() => setDataVersion((version) => version + 1));
    CRYPTOLIVE_DATA.refresh();
    return unsubscribe;
  }, []);
  useEffect(() => {
    try { localStorage.setItem('clab-lang', lang); } catch (e) {}
    window.__LANG = lang;
  }, [lang]);
  const toggleLang = () => setLang(l => l === 'ko' ? 'en' : 'ko');

  const goto = (r) => {
    setRoute(r);
    setUserMenuOpen(false);
    window.scrollTo({ top: 0, behavior: 'instant' });
  };

  const logout = () => {
    setProfile({ ...profile, loggedIn: false });
    setRoute({ tab: 'login' });
    setUserMenuOpen(false);
  };

  // Cmd/Ctrl+K shortcut
  useEffect(() => {
    const fn = (e) => {
      if ((e.metaKey || e.ctrlKey) && e.key === 'k') {
        e.preventDefault();
        setSearchOpen(true);
      }
    };
    window.addEventListener('keydown', fn);
    return () => window.removeEventListener('keydown', fn);
  }, []);

  const tabs = [
    { id: 'home', label: t('home'), icon: Icon.home },
    { id: 'market', label: t('market'), icon: Icon.market },
    { id: 'portfolio', label: t('portfolio'), icon: Icon.wallet },
    { id: 'live', label: t('live'), icon: Icon.chat },
  ];

  return (
    <LangContext.Provider value={lang}>
      <div className="topbar">
        <div className="topbar-inner">
          <button className="brand" onClick={() => goto({ tab: 'home' })} style={{ cursor: 'pointer' }}>
            <div className="brand-mark">C</div>
            <span className="hide-mobile" style={{ display: 'inline-flex', flexDirection: 'column', alignItems: 'flex-start', lineHeight: 1.05 }}>
              <span style={{ fontWeight: 800, fontSize: 18, letterSpacing: '0.02em' }}>CRIV</span>
              <span style={{ fontWeight: 500, fontSize: 10, color: 'var(--fg-3)', letterSpacing: '0.04em' }}>Crypto Live</span>
            </span>
          </button>
          <div className="navtabs">
            {tabs.map(t => (
              <button key={t.id}
                className={`navtab ${route.tab === t.id || (t.id === 'market' && route.tab === 'detail') || (t.id === 'portfolio' && route.tab === 'holding') ? 'navtab--active' : ''}`}
                onClick={() => goto({ tab: t.id })}>
                {t.label}
              </button>
            ))}
          </div>
          <div className="topbar-actions">
            <button className="icon-btn" onClick={() => setSearchOpen(true)} title={t('search') + ' (Cmd+K)'}>
              <Icon.search width="20" height="20" />
            </button>
            <button className="icon-btn" onClick={() => setNotifOpen(!notifOpen)} title={t('notifications')}>
              <Icon.bell width="20" height="20" />
            </button>
            <button className="icon-btn" onClick={toggleLang} title={t('language')}
              style={{ width: 'auto', padding: '0 10px', fontWeight: 700, fontSize: 12, letterSpacing: '0.04em' }}>
              {lang === 'ko' ? 'KO' : 'EN'}
            </button>
            <ThemeToggle />
            <button ref={avatarRef} className="avatar" onClick={() => setUserMenuOpen(o => !o)}
              style={{ cursor: 'pointer', border: 'none', background: 'transparent', padding: 0 }}
              aria-label={t('profile')}>
              <Avatar profile={profile} size={32} fontSize={13} />
            </button>
            {userMenuOpen && (
              <UserMenu profile={profile} anchorRef={avatarRef} t={t}
                onClose={() => setUserMenuOpen(false)}
                goto={goto} onLogout={logout} />
            )}
          </div>
        </div>
      </div>

      <TickerBar goto={goto} />

      {route.tab === 'home' && <HomeScreen goto={goto} />}
      {route.tab === 'market' && <MarketScreen goto={goto} />}
      {route.tab === 'detail' && <AssetDetailScreen assetId={route.assetId} goto={goto} />}
      {route.tab === 'portfolio' && <PortfolioScreen goto={goto} />}
      {route.tab === 'holding' && <HoldingDetailScreen holding={route.holding} goto={goto} />}
      {route.tab === 'settings' && <SettingsScreen profile={profile} setProfile={setProfile} goto={goto} onLogout={logout} t={t} lang={lang} setLang={setLang} />}
      {route.tab === 'login' && <LoginScreen onLogin={(u) => { setProfile({ ...profile, ...u, loggedIn: true }); setRoute({ tab: 'home' }); }} goto={goto} t={t} />}
      {route.tab === 'live' && <LiveScreen goto={goto} />}

      <div className="bottomnav">
        <div className="bottomnav-inner">
          {tabs.map(t => {
            const active = route.tab === t.id || (t.id === 'market' && route.tab === 'detail') || (t.id === 'portfolio' && route.tab === 'holding');
            return (
              <button key={t.id} className={`bottomtab ${active ? 'bottomtab--active' : ''}`} onClick={() => goto({ tab: t.id })}>
                <t.icon />
                <span>{t.label}</span>
              </button>
            );
          })}
        </div>
      </div>

      <SearchModal open={searchOpen} onClose={() => setSearchOpen(false)} goto={goto} />
      <NotificationsPanel open={notifOpen} onClose={() => setNotifOpen(false)} />
    </LangContext.Provider>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
