// chrome.jsx — Nav, Search, Footer, Buttons (shared shell)

function Btn({ children, kind = 'ghost', size = 'md', t, onClick, style, leadingIcon, fullWidth }) {
  const sizes = {
    sm: { h: 28, px: 10, fs: 12, rad: 7 },
    md: { h: 34, px: 14, fs: 13, rad: 8 },
    lg: { h: 44, px: 22, fs: 14, rad: 10 },
  };
  const s = sizes[size];
  const base = {
    height: s.h, padding: `0 ${s.px}px`, fontSize: s.fs, borderRadius: s.rad,
    display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 7,
    fontWeight: 600, letterSpacing: '-0.005em', cursor: 'pointer',
    border: '1px solid transparent', transition: 'all 0.12s', whiteSpace: 'nowrap',
    fontFamily: 'inherit', width: fullWidth ? '100%' : undefined,
  };
  const variants = {
    primary: { background: t.accent, color: t.accentInk, border: `1px solid ${t.accent}` },
    secondary: { background: t.surface2, color: t.text, border: `1px solid ${t.border}` },
    ghost: { background: 'transparent', color: t.text },
    outline: { background: 'transparent', color: t.text, border: `1px solid ${t.border}` },
  };
  return (
    <button onClick={onClick} style={{ ...base, ...variants[kind], ...style }}
      onMouseEnter={(e) => { if (kind === 'primary') e.currentTarget.style.filter = 'brightness(0.94)'; else e.currentTarget.style.background = t.surface2; }}
      onMouseLeave={(e) => { e.currentTarget.style.filter = ''; e.currentTarget.style.background = variants[kind].background; }}
    >
      {leadingIcon}{children}
    </button>
  );
}

function Search({ t, str, hue, accent, dark, size = 'md' }) {
  const [q, setQ] = useState('');
  const [focus, setFocus] = useState(false);
  const matches = useMemo(() => {
    if (!q.trim()) return [];
    const lo = q.toLowerCase();
    return GAMES.filter(g => g.title.toLowerCase().includes(lo) || g.creator.toLowerCase().includes(lo)).slice(0, 5);
  }, [q]);

  const heights = { sm: 30, md: 36, lg: 44 };
  const h = heights[size];
  return (
    <div style={{ position: 'relative', flex: 1, maxWidth: 520 }}>
      <div style={{
        position: 'relative', height: h, display: 'flex', alignItems: 'center',
        background: t.surface, borderRadius: 10,
        border: `1px solid ${focus ? t.text : t.border}`,
        transition: 'border-color 0.15s',
      }}>
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" style={{ marginLeft: 12, color: t.muted, flexShrink: 0 }}>
          <circle cx="11" cy="11" r="7" stroke="currentColor" strokeWidth="2"/>
          <path d="m20 20-3.5-3.5" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/>
        </svg>
        <input
          value={q} onChange={(e) => setQ(e.target.value)}
          onFocus={() => setFocus(true)} onBlur={() => setTimeout(() => setFocus(false), 150)}
          placeholder={str.search_ph}
          style={{
            flex: 1, height: '100%', background: 'transparent', border: 'none', outline: 'none',
            padding: '0 12px', fontSize: 13, color: t.text, fontFamily: 'inherit',
          }}
        />
        <kbd style={{
          marginRight: 8, padding: '2px 6px', fontSize: 10, color: t.muted,
          fontFamily: 'ui-monospace, monospace', background: t.surface2, borderRadius: 4,
          border: `1px solid ${t.border}`,
        }}>⌘K</kbd>
      </div>
      {focus && matches.length > 0 && (
        <div style={{
          position: 'absolute', top: h + 6, left: 0, right: 0, zIndex: 50,
          background: t.bg, border: `1px solid ${t.border}`, borderRadius: 12,
          boxShadow: dark ? '0 12px 40px rgba(0,0,0,0.5)' : '0 12px 40px rgba(0,0,0,0.08)',
          overflow: 'hidden',
        }}>
          {matches.map(g => (
            <div key={g.id} style={{
              display: 'flex', gap: 10, alignItems: 'center', padding: '8px 10px',
              cursor: 'pointer', borderBottom: `1px solid ${t.border}`,
            }}
              onMouseEnter={(e) => e.currentTarget.style.background = t.surface}
              onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}
            >
              <div style={{ width: 36, height: 36, flexShrink: 0 }}>
                <Placeholder hue={g.hue} pattern={g.pattern} dark={dark} radius={6} />
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13, fontWeight: 500, color: t.text }}>{g.title}</div>
                <div style={{ fontSize: 11, color: t.muted }}>{str.by} {g.creator} · {fmt(g.players)} {str.online}</div>
              </div>
              <div style={{ fontSize: 10, color: t.faint, fontFamily: 'ui-monospace, monospace', textTransform: 'uppercase' }}>{g.genre}</div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

function Nav({ t, str, dark, lang, setLang, setActive, active, accent, compact, navigate }) {
  const items = [
    { key: 'discover', label: str.nav_discover, route: 'home' },
    { key: 'library', label: str.nav_library, route: 'catalog' },
    { key: 'create', label: str.nav_create, route: 'studio' },
    { key: 'community', label: str.nav_community, route: 'profile' },
  ];
  const go = (it) => {
    if (navigate) navigate(it.route);
    else if (setActive) setActive(it.key);
  };
  return (
    <header style={{
      borderBottom: `1px solid ${t.border}`, background: t.bg,
      position: 'sticky', top: 0, zIndex: 40,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 24, padding: '0 28px', height: 60, maxWidth: 1280, margin: '0 auto' }}>
      <Logo dark={dark} />
      <nav style={{ display: 'flex', gap: 4 }}>
        {items.map(it => (
          <button key={it.key} onClick={() => go(it)} style={{
            background: 'transparent', border: 'none', cursor: 'pointer',
            padding: '6px 10px', borderRadius: 6,
            fontFamily: 'inherit', fontSize: 13, fontWeight: 500,
            color: active === it.key ? t.text : t.muted,
            position: 'relative',
          }}>
            {it.label}
            {active === it.key && (
              <div style={{ position: 'absolute', left: 10, right: 10, bottom: -19, height: 2, background: t.accent, borderRadius: 1 }} />
            )}
          </button>
        ))}
      </nav>
      <div style={{ flex: 1, display: 'flex', justifyContent: 'center' }}>
        <Search t={t} str={str} dark={dark} />
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
        <button onClick={() => setLang(lang === 'ru' ? 'en' : 'ru')} style={{
          background: 'transparent', border: `1px solid ${t.border}`, color: t.muted,
          fontFamily: 'ui-monospace, monospace', fontSize: 11, padding: '5px 8px',
          borderRadius: 6, cursor: 'pointer', textTransform: 'uppercase',
        }}>{lang}</button>
        <AuthSlot t={t} str={str} lang={lang} dark={dark} navigate={navigate} />
      </div>
      </div>
    </header>
  );
}

// Right-side auth widget: Sign in / Sign up when logged out, otherwise a
// small avatar pill with "@username" + dropdown for Profile / Logout.
// Subscribes to Supabase auth state so it flips immediately after login.
function AuthSlot({ t, str, lang, dark, navigate }) {
  const [session, setSession] = useState(null);
  const [profile, setProfile] = useState(null);
  const [open, setOpen]       = useState(false);

  useEffect(() => {
    if (!window.getSupabase) return;
    const sb = window.getSupabase();
    let alive = true;

    async function loadProfile(userId) {
      const { data } = await sb.from('profiles')
        .select('username, display_name')
        .eq('id', userId).maybeSingle();
      if (alive) setProfile(data || null);
    }

    sb.auth.getSession().then(({ data }) => {
      if (!alive) return;
      setSession(data.session || null);
      if (data.session) loadProfile(data.session.user.id);
    });

    const { data: sub } = sb.auth.onAuthStateChange((_evt, sess) => {
      if (!alive) return;
      setSession(sess || null);
      if (sess) loadProfile(sess.user.id); else setProfile(null);
    });

    return () => { alive = false; sub.subscription.unsubscribe(); };
  }, []);

  if (!session) {
    return (
      <React.Fragment>
        <Btn kind="ghost"   size="sm" t={t}
             onClick={() => navigate && navigate('auth', { mode: 'signin' })}>
          {str.sign_in}
        </Btn>
        <Btn kind="primary" size="sm" t={t}
             onClick={() => navigate && navigate('auth', { mode: 'signup' })}>
          {str.sign_up}
        </Btn>
      </React.Fragment>
    );
  }

  const u = profile || {};
  const name = u.display_name || u.username || (session.user.email || 'you');
  const initial = (name || '?').trim().charAt(0).toUpperCase();

  return (
    <div style={{ position: 'relative' }}>
      <button onClick={() => setOpen(o => !o)} style={{
        display: 'inline-flex', alignItems: 'center', gap: 8,
        height: 32, padding: '0 4px 0 4px',
        background: 'transparent', border: `1px solid ${t.border}`,
        borderRadius: 999, cursor: 'pointer',
        fontFamily: 'inherit', color: t.text,
      }}>
        <span style={{
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          width: 24, height: 24, borderRadius: '50%',
          background: t.accent, color: t.accentInk || '#0e1008',
          fontSize: 12, fontWeight: 700,
        }}>{initial}</span>
        <span style={{ fontSize: 12, fontWeight: 500, paddingRight: 8 }}>
          @{u.username || (session.user.email || '').split('@')[0]}
        </span>
      </button>
      {open && (
        <div style={{
          position: 'absolute', top: 38, right: 0, minWidth: 180, zIndex: 60,
          background: t.bg, border: `1px solid ${t.border}`, borderRadius: 10,
          boxShadow: dark ? '0 12px 40px rgba(0,0,0,0.5)' : '0 12px 40px rgba(0,0,0,0.10)',
          overflow: 'hidden',
        }}>
          <div style={{ padding: '10px 12px', borderBottom: `1px solid ${t.border}` }}>
            <div style={{ fontSize: 13, fontWeight: 600, color: t.text }}>{name}</div>
            <div style={{ fontSize: 11, color: t.muted }}>{session.user.email}</div>
          </div>
          <DropItem t={t} label={lang === 'ru' ? 'Профиль'   : 'Profile'}
                    onClick={() => { setOpen(false); navigate && navigate('profile'); }} />
          <DropItem t={t} label={lang === 'ru' ? 'Настройки' : 'Settings'}
                    onClick={() => { setOpen(false); navigate && navigate('settings'); }} />
          <DropItem t={t} label={lang === 'ru' ? 'Выйти' : 'Sign out'}
                    danger
                    onClick={async () => {
                      setOpen(false);
                      const sb = window.getSupabase();
                      await sb.auth.signOut();
                      navigate && navigate('home');
                    }} />
        </div>
      )}
    </div>
  );
}

function DropItem({ t, label, onClick, danger }) {
  return (
    <div onClick={onClick} style={{
      padding: '9px 12px', fontSize: 13, cursor: 'pointer',
      color: danger ? '#d04040' : t.text,
    }}
      onMouseEnter={(e) => e.currentTarget.style.background = t.surface}
      onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}
    >{label}</div>
  );
}

function Stat({ t, label, value, sub }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
      <div style={{
        fontFamily: '"Inter Tight", Inter, sans-serif', fontWeight: 600,
        fontSize: 22, color: t.text, letterSpacing: '-0.02em',
      }}>{value}</div>
      <div style={{ fontSize: 11, color: t.muted, textTransform: 'uppercase', letterSpacing: '0.04em' }}>{label}</div>
      {sub && <div style={{ fontSize: 11, color: t.faint }}>{sub}</div>}
    </div>
  );
}

// Generic GameCard with hover preview state
function GameCard({ g, t, str, dark, size = 'md', onClick }) {
  const [hover, setHover] = useState(false);
  const sizes = {
    sm: { h: 130, fs: 13 },
    md: { h: 170, fs: 14 },
    lg: { h: 220, fs: 15 },
    xl: { h: 280, fs: 16 },
  };
  const sz = sizes[size];
  return (
    <div
      onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      onClick={onClick}
      style={{
        display: 'flex', flexDirection: 'column', gap: 8, cursor: 'pointer',
        transform: hover ? 'translateY(-2px)' : 'none', transition: 'transform 0.18s',
      }}>
      <div style={{ position: 'relative', height: sz.h }}>
        <Placeholder hue={g.hue} pattern={g.pattern} dark={dark} label={g.id} sub={g.genre} />
        {hover && (
          <div style={{
            position: 'absolute', inset: 0, borderRadius: 10,
            background: dark ? 'rgba(0,0,0,0.45)' : 'rgba(255,255,255,0.7)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            backdropFilter: 'blur(2px)', transition: 'opacity 0.15s',
          }}>
            <div style={{
              padding: '8px 14px', background: t.accent, color: t.accentInk,
              borderRadius: 999, fontSize: 12, fontWeight: 600,
            }}>▶ {str.play_now}</div>
          </div>
        )}
        {hover && (
          <div style={{
            position: 'absolute', top: 8, right: 8,
            background: dark ? 'rgba(0,0,0,0.55)' : 'rgba(255,255,255,0.9)',
            color: t.text, fontSize: 10, padding: '3px 7px', borderRadius: 999,
            fontFamily: 'ui-monospace, monospace',
          }}>● {fmt(g.players)} {str.online}</div>
        )}
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 1 }}>
        <div style={{ fontSize: sz.fs, fontWeight: 600, color: t.text, letterSpacing: '-0.01em' }}>{g.title}</div>
        <div style={{ fontSize: 12, color: t.muted, display: 'flex', justifyContent: 'space-between' }}>
          <span>{str.by} {g.creator}</span>
          <span style={{ fontFamily: 'ui-monospace, monospace' }}>★ {g.rating}</span>
        </div>
      </div>
    </div>
  );
}

function CategoryChip({ label, active, t, onClick }) {
  return (
    <button onClick={onClick} style={{
      padding: '6px 12px', borderRadius: 999, cursor: 'pointer',
      fontSize: 12, fontWeight: 500, fontFamily: 'inherit',
      background: active ? t.text : 'transparent',
      color: active ? t.bg : t.muted,
      border: `1px solid ${active ? t.text : t.border}`,
      transition: 'all 0.12s',
    }}>{label}</button>
  );
}

function SectionHead({ t, title, action, kicker }) {
  return (
    <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 16 }}>
      <div>
        {kicker && <div style={{
          fontSize: 11, color: t.faint, fontFamily: 'ui-monospace, monospace',
          textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 4,
        }}>{kicker}</div>}
        <h2 style={{
          margin: 0, fontFamily: '"Inter Tight", Inter, sans-serif',
          fontWeight: 600, fontSize: 22, color: t.text, letterSpacing: '-0.02em',
        }}>{title}</h2>
      </div>
      {action && <button style={{
        background: 'transparent', border: 'none', cursor: 'pointer',
        color: t.muted, fontSize: 12, fontFamily: 'inherit',
      }}>{action} →</button>}
    </div>
  );
}

Object.assign(window, { Btn, Search, Nav, Stat, GameCard, CategoryChip, SectionHead });
