// components.jsx — shared bits for Craftix Dev site
const { useState, useEffect, useRef, useMemo } = React;

// ── i18n strings ────────────────────────────────────────────
const STRINGS = {
  ru: {
    nav_discover: 'Открой',
    nav_library: 'Каталог',
    nav_create: 'Создать',
    nav_community: 'Сообщество',
    search_ph: 'Найти игры, создателей, миры…',
    sign_in: 'Войти',
    sign_up: 'Регистрация',
    download_player: 'Скачать плеер',
    open_in_studio: 'Открыть в Studio',
    play_now: 'Играть',
    play: 'Играть',
    trending: 'В тренде',
    popular: 'Популярное сейчас',
    new_releases: 'Новые миры',
    top_creators: 'Топ создатели',
    by: 'от',
    online: 'онлайн',
    recommended: 'Рекомендуем тебе',
    categories: 'Категории',
    all: 'Все',
    obby: 'Obby',
    sim: 'Симулятор',
    rpg: 'RPG',
    racing: 'Гонки',
    horror: 'Хоррор',
    tycoon: 'Tycoon',
    rated: 'рейтинг',
    creators: 'создателей',
    worlds: 'миров',
    players_today: 'игроков сегодня',
    hero_title: 'Создавай. Играй. Делись.',
    hero_sub: 'Открытая платформа для миров, сделанных людьми. Скачай Craftix Player или собирай свои игры в Studio.',
    download: 'Скачать',
    studio: 'Studio',
    learn: 'Узнать больше',
    profile_friends: 'Друзья',
    profile_inventory: 'Инвентарь',
    profile_creations: 'Творения',
    profile_about: 'О себе',
    join_friends: 'Зайти к друзьям',
    edit_profile: 'Редактировать',
    follow: 'Подписаться',
    following: 'Подписан',
    description: 'Описание',
    about_game: 'Об игре',
    servers: 'Серверы',
    leaderboard: 'Лидерборд',
    favorites: 'добавили',
    visits: 'посещений',
    updated: 'обновлено',
    genre: 'Жанр',
    max_players: 'Макс. игроков',
    similar: 'Похожие игры',
    badges: 'Бейджи',
    passes: 'Пропуска',
    minutes_ago: 'мин назад',
    hours_ago: 'ч назад',
    days_ago: 'д назад',
    members: 'участников',
    level: 'Уровень',
    xp: 'XP',
    stats: 'Статистика',
  },
  en: {
    nav_discover: 'Discover',
    nav_library: 'Library',
    nav_create: 'Create',
    nav_community: 'Community',
    search_ph: 'Search games, creators, worlds…',
    sign_in: 'Sign in',
    sign_up: 'Sign up',
    download_player: 'Get Player',
    open_in_studio: 'Open in Studio',
    play_now: 'Play',
    play: 'Play',
    trending: 'Trending',
    popular: 'Popular now',
    new_releases: 'New worlds',
    top_creators: 'Top creators',
    by: 'by',
    online: 'online',
    recommended: 'Recommended for you',
    categories: 'Categories',
    all: 'All',
    obby: 'Obby',
    sim: 'Sim',
    rpg: 'RPG',
    racing: 'Racing',
    horror: 'Horror',
    tycoon: 'Tycoon',
    rated: 'rating',
    creators: 'creators',
    worlds: 'worlds',
    players_today: 'players today',
    hero_title: 'Build. Play. Share.',
    hero_sub: 'An open platform for human-made worlds. Get Craftix Player or build your own games in Studio.',
    download: 'Download',
    studio: 'Studio',
    learn: 'Learn more',
    profile_friends: 'Friends',
    profile_inventory: 'Inventory',
    profile_creations: 'Creations',
    profile_about: 'About',
    join_friends: 'Join friends',
    edit_profile: 'Edit profile',
    follow: 'Follow',
    following: 'Following',
    description: 'Description',
    about_game: 'About this game',
    servers: 'Servers',
    leaderboard: 'Leaderboard',
    favorites: 'favorites',
    visits: 'visits',
    updated: 'updated',
    genre: 'Genre',
    max_players: 'Max players',
    similar: 'Similar games',
    badges: 'Badges',
    passes: 'Game passes',
    minutes_ago: 'min ago',
    hours_ago: 'h ago',
    days_ago: 'd ago',
    members: 'members',
    level: 'Level',
    xp: 'XP',
    stats: 'Stats',
  },
};

// ── Empty catalog — content will populate after launch ─────
const GAMES = [];
const CREATORS = [];
const FRIENDS = [];

// ── Visual primitives ──────────────────────────────────────
function Placeholder({ hue = 220, pattern = 'stripes', label, sub, height = '100%', radius = 10, dark }) {
  const baseL = dark ? 22 : 92;
  const fg = dark ? 'rgba(255,255,255,0.07)' : 'rgba(0,0,0,0.05)';
  const bg = `oklch(${baseL}% 0.04 ${hue})`;
  const patterns = {
    stripes: `repeating-linear-gradient(135deg, ${fg} 0 1px, transparent 1px 12px)`,
    grid: `linear-gradient(${fg} 1px, transparent 1px), linear-gradient(90deg, ${fg} 1px, transparent 1px)`,
    dots: `radial-gradient(${fg} 1px, transparent 1.5px)`,
    noise: `repeating-linear-gradient(45deg, ${fg} 0 1px, transparent 1px 6px), repeating-linear-gradient(-45deg, ${fg} 0 1px, transparent 1px 6px)`,
  };
  const sizes = { stripes: 'auto', grid: '20px 20px', dots: '14px 14px', noise: 'auto' };
  return (
    <div style={{
      position: 'relative', width: '100%', height, borderRadius: radius,
      background: bg, overflow: 'hidden',
      boxShadow: dark ? 'inset 0 0 0 1px rgba(255,255,255,0.04)' : 'inset 0 0 0 1px rgba(0,0,0,0.04)'
    }}>
      <div style={{
        position: 'absolute', inset: 0,
        backgroundImage: patterns[pattern], backgroundSize: sizes[pattern],
      }} />
      {label && (
        <div style={{
          position: 'absolute', left: 10, bottom: 8,
          fontFamily: 'ui-monospace, "SF Mono", Menlo, monospace',
          fontSize: 9, letterSpacing: '0.05em', textTransform: 'uppercase',
          color: dark ? 'rgba(255,255,255,0.5)' : 'rgba(0,0,0,0.45)',
        }}>{label}{sub && <span style={{ opacity: 0.55 }}> · {sub}</span>}</div>
      )}
    </div>
  );
}

function Logo({ size = 22, mono = true, dark }) {
  const c = dark ? '#fff' : '#0c0c0d';
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
      <svg width={size} height={size} viewBox="0 0 24 24" fill="none" aria-hidden>
        <rect x="2"  y="2"  width="9"  height="9"  rx="1.5" fill={c} />
        <rect x="13" y="2"  width="9"  height="9"  rx="1.5" fill="none" stroke={c} strokeWidth="1.6" />
        <rect x="2"  y="13" width="9"  height="9"  rx="1.5" fill="none" stroke={c} strokeWidth="1.6" />
        <rect x="13" y="13" width="9"  height="9"  rx="1.5" fill={c} />
      </svg>
      <span style={{ fontFamily: '"Inter Tight", Inter, system-ui, sans-serif', fontWeight: 700, fontSize: 15, letterSpacing: '-0.02em', color: c }}>
        craftix<span style={{ opacity: 0.4, fontWeight: 500 }}>/dev</span>
      </span>
    </div>
  );
}

function Avatar({ hue = 220, size = 32, dark, label }) {
  const initials = (label || 'CX').slice(0, 2).toUpperCase();
  return (
    <div style={{
      width: size, height: size, borderRadius: 8,
      background: `oklch(${dark ? 28 : 88}% 0.06 ${hue})`,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      fontFamily: 'ui-monospace, monospace', fontSize: Math.max(9, size * 0.32),
      color: dark ? 'rgba(255,255,255,0.7)' : 'rgba(0,0,0,0.55)',
      letterSpacing: '0.04em', flexShrink: 0,
      boxShadow: dark ? 'inset 0 0 0 1px rgba(255,255,255,0.06)' : 'inset 0 0 0 1px rgba(0,0,0,0.06)',
    }}>{initials}</div>
  );
}

// Number formatter
function fmt(n) {
  if (n >= 1000000) return (n / 1000000).toFixed(1) + 'M';
  if (n >= 1000) return (n / 1000).toFixed(n >= 10000 ? 0 : 1) + 'k';
  return String(n);
}

// ── Theme tokens ──────────────────────────────────────────
function theme(dark, accent) {
  return {
    bg:      dark ? 'oklch(13% 0.005 250)' : 'oklch(98.5% 0.003 250)',
    surface: dark ? 'oklch(17% 0.006 250)' : 'oklch(96% 0.003 250)',
    surface2: dark ? 'oklch(20% 0.007 250)' : 'oklch(93% 0.003 250)',
    border:  dark ? 'oklch(26% 0.008 250)' : 'oklch(89% 0.004 250)',
    text:    dark ? 'oklch(96% 0.004 250)' : 'oklch(18% 0.005 250)',
    muted:   dark ? 'oklch(62% 0.008 250)' : 'oklch(48% 0.008 250)',
    faint:   dark ? 'oklch(45% 0.008 250)' : 'oklch(65% 0.008 250)',
    accent,
    accentInk: dark ? 'oklch(13% 0.005 250)' : 'oklch(13% 0.005 250)',
  };
}

Object.assign(window, { STRINGS, GAMES, CREATORS, FRIENDS, Placeholder, Logo, Avatar, fmt, theme, EmptyState });

function EmptyState({ t, title, sub, action, onAction, height = 240 }) {
  return (
    <div style={{
      minHeight: height, padding: '40px 24px',
      border: `1px dashed ${t.border}`, borderRadius: 14,
      display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
      gap: 10, textAlign: 'center', background: 'transparent',
    }}>
      <div style={{
        fontSize: 11, color: t.faint, fontFamily: 'ui-monospace, monospace',
        textTransform: 'uppercase', letterSpacing: '0.08em',
      }}>— empty —</div>
      <div style={{ fontFamily: '"Inter Tight", sans-serif', fontSize: 20, fontWeight: 600, color: t.text, letterSpacing: '-0.01em' }}>{title}</div>
      {sub && <div style={{ fontSize: 13, color: t.muted, maxWidth: 380, lineHeight: 1.55 }}>{sub}</div>}
      {action && <button onClick={onAction} style={{
        marginTop: 6, padding: '8px 14px', borderRadius: 8, border: `1px solid ${t.border}`,
        background: 'transparent', color: t.text, fontSize: 13, fontWeight: 500, cursor: 'pointer', fontFamily: 'inherit',
      }}>{action}</button>}
    </div>
  );
}
