// FartBet — shared UI primitives (window.FB_UI.*)
// Avatar, PCoin, Badge, Pill, Button, Modal, Sidebar, Header
const { useState, useEffect, useRef, useMemo, useCallback } = React;

function cx(...xs) { return xs.filter(Boolean).join(' '); }

function formatPC(n) {
  if (n == null || isNaN(n)) return '0';
  return Math.round(n).toLocaleString('ru-RU').replace(/,/g, ' ');
}

// — Gold coin icon with PC monogram
function CoinIcon({ size = 16 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" style={{ display: 'inline-block', verticalAlign: '-2px' }}>
      <defs>
        <linearGradient id="cg" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="#FFE25E" />
          <stop offset="60%" stopColor="#FFC400" />
          <stop offset="100%" stopColor="#B47700" />
        </linearGradient>
      </defs>
      <circle cx="12" cy="12" r="11" fill="url(#cg)" stroke="#7a4f00" strokeWidth="1" />
      <circle cx="12" cy="12" r="8.2" fill="none" stroke="rgba(255,255,255,.45)" strokeWidth="0.6" />
      <text x="12" y="15.7" textAnchor="middle" fontSize="9" fontWeight="900" fill="#3a2400"
            fontFamily="Onest, system-ui, sans-serif" letterSpacing="-0.5">PC</text>
    </svg>
  );
}

function PCoin({ amount, big = false, muted = false, signed = false }) {
  const sign = signed && amount > 0 ? '+' : '';
  return (
    <span className={cx('pc', big && 'pc-big', muted && 'pc-muted')}>
      <CoinIcon size={big ? 22 : 15} />
      <span className="pc-num">{sign}{formatPC(amount)}</span>
      <span className="pc-unit">PC</span>
    </span>
  );
}

function Avatar({ user, size = 36, ring = false }) {
  if (!user) return null;
  const initials = user.name.split(' ').map(w => w[0]).join('').slice(0, 2).toUpperCase();
  return (
    <div className={cx('avatar', ring && 'avatar-ring')}
         style={{ width: size, height: size, background: user.color, fontSize: size * 0.42 }}
         title={user.name}>
      {initials}
    </div>
  );
}

function StatusDot({ status }) {
  // live | open | closed | settled
  const map = {
    live:    { c: '#FF3D3D', t: 'LIVE',     pulse: true },
    open:    { c: '#00C853', t: 'OPEN',     pulse: false },
    closed:  { c: '#9AA0A6', t: 'CLOSED',   pulse: false },
    settled: { c: '#FFD600', t: 'SETTLED',  pulse: false },
  };
  const m = map[status] || map.open;
  return (
    <span className={cx('status-pill', `status-${status}`)}>
      <span className={cx('status-dot', m.pulse && 'pulse')} style={{ background: m.c }}></span>
      {m.t}
    </span>
  );
}

function CategoryTag({ cat, data }) {
  const c = data.CATEGORIES[cat];
  if (!c) return null;
  return <span className="cat-tag">{c.short}</span>;
}

function HeaderBar({ user, route, setRoute, onLogout, onOpenAuth, onSearch, searchQuery }) {
  const inputRef = React.useRef(null);

  React.useEffect(() => {
    const onKey = (e) => {
      if (e.key === '/' && document.activeElement.tagName !== 'INPUT' && document.activeElement.tagName !== 'TEXTAREA') {
        e.preventDefault();
        inputRef.current && inputRef.current.focus();
      }
    };
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, []);

  return (
    <header className="hdr">
      <div className="hdr-left">
        <div className="logo" onClick={() => setRoute({ name: 'home' })}>
          <span className="logo-mark">F</span>
          <span className="logo-text">FART<span className="logo-accent">BET</span></span>
          <span className="logo-tag">BETA</span>
        </div>
        <nav className="hdr-nav">
          <button className={cx('hdr-nav-btn', route.name === 'home'   && 'active')} onClick={() => setRoute({ name: 'home' })}>Линия</button>
          <button className={cx('hdr-nav-btn', route.name === 'board'  && 'active')} onClick={() => setRoute({ name: 'board' })}>Board</button>
          <button className={cx('hdr-nav-btn', route.name === 'rating' && 'active')} onClick={() => setRoute({ name: 'rating' })}>Рейтинг</button>
          <button className={cx('hdr-nav-btn', route.name === 'history'&& 'active')} onClick={() => setRoute({ name: 'history' })}>Мои ставки</button>
          {user && user.role === 'admin' && (
            <button className={cx('hdr-nav-btn', route.name === 'admin' && 'active')} onClick={() => setRoute({ name: 'admin' })}>
              <span className="dot-admin"></span>Админ
            </button>
          )}
        </nav>
      </div>

      <div className="hdr-right">
        <div className="hdr-search">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/></svg>
          <input
            ref={inputRef}
            placeholder="Поиск события или игрока"
            value={searchQuery || ''}
            onChange={e => onSearch && onSearch(e.target.value)}
            onKeyDown={e => e.key === 'Escape' && (onSearch && onSearch(''), e.target.blur())}
          />
          {searchQuery ? (
            <button style={{background:'none',border:'none',cursor:'pointer',color:'var(--text-3)',padding:'0 2px'}} onClick={() => onSearch('')}>✕</button>
          ) : <kbd>/</kbd>}
        </div>
        {user ? (
          <>
            <button className="bal-pill" onClick={() => setRoute({ name: 'profile' })}>
              <PCoin amount={user.balance} />
              <span className="bal-add">+</span>
            </button>
            <button className="user-chip" onClick={() => setRoute({ name: 'profile' })}>
              <Avatar user={user} size={28} ring />
              <span>{user.name.split(' ')[0]}</span>
              <svg width="10" height="10" viewBox="0 0 24 24"><path d="M6 9l6 6 6-6" stroke="currentColor" strokeWidth="2" fill="none"/></svg>
            </button>
          </>
        ) : (
          <button className="btn btn-primary" onClick={onOpenAuth}>Войти</button>
        )}
      </div>
    </header>
  );
}

function LeftRail({ route, setRoute, user, data, onOpenAuth }) {
  const liveCount = data.EVENTS.filter(e => e.status === 'live').length;
  const openCount = data.EVENTS.filter(e => e.status === 'open').length;

  const items = [
    { key: 'home',    label: 'Линия',        icon: 'list',    badge: openCount },
    { key: 'live',    label: 'Live',         icon: 'pulse',   badge: liveCount, pulse: true },
    { key: 'board',   label: 'Board',        icon: 'feed' },
    { key: 'rating',  label: 'Рейтинг',      icon: 'cup' },
    { key: 'history', label: 'Мои ставки',   icon: 'ticket', authReq: true },
    { key: 'profile', label: 'Профиль',      icon: 'user',   authReq: true },
  ];

  const handle = (it) => {
    if (it.authReq && !user) { onOpenAuth(); return; }
    if (it.key === 'live') { setRoute({ name: 'home', filter: 'live' }); return; }
    setRoute({ name: it.key });
  };

  return (
    <aside className="rail">
      <div className="rail-sect">
        {items.map(it => (
          <button key={it.key}
            className={cx('rail-item',
              (route.name === it.key || (it.key === 'live' && route.name === 'home' && route.filter === 'live')) && 'active')}
            onClick={() => handle(it)}>
            <RailIcon name={it.icon} />
            <span className="rail-lbl">{it.label}</span>
            {it.badge != null && it.badge > 0 && (
              <span className={cx('rail-badge', it.pulse && 'rail-badge-live')}>{it.badge}</span>
            )}
          </button>
        ))}
      </div>

      <div className="rail-sect">
        <div className="rail-title">Категории</div>
        {Object.entries(data.CATEGORIES).map(([k, c]) => (
          <button key={k} className="rail-cat" onClick={() => setRoute({ name: 'home', cat: k })}>
            <span className="rail-cat-pill">{c.short}</span>
            <span>{c.label}</span>
            <span className="rail-cat-count">{data.EVENTS.filter(e => e.cat === k).length}</span>
          </button>
        ))}
      </div>

      {user && user.role === 'admin' && (
        <div className="rail-sect">
          <button className={cx('rail-item rail-admin', route.name === 'admin' && 'active')} onClick={() => setRoute({ name: 'admin' })}>
            <RailIcon name="bolt" />
            <span className="rail-lbl">Админка</span>
          </button>
        </div>
      )}

      <div className="rail-foot">
        <div className="rail-disclaim">
          18+ · только PCOIN <br />
          Реальные деньги не используются
        </div>
      </div>
    </aside>
  );
}

function RailIcon({ name }) {
  const p = {
    list:   <><path d="M4 6h16M4 12h16M4 18h10" strokeLinecap="round"/></>,
    pulse:  <><path d="M3 12h4l2-6 3 12 2-8 3 4h4" strokeLinejoin="round" strokeLinecap="round"/></>,
    feed:   <><rect x="3" y="5" width="18" height="14" rx="2"/><path d="M7 9h10M7 13h10M7 17h6"/></>,
    cup:    <><path d="M7 4h10v4a5 5 0 0 1-10 0V4z"/><path d="M5 6H3v2a3 3 0 0 0 3 3M19 6h2v2a3 3 0 0 1-3 3M10 14v3h4v-3M8 20h8"/></>,
    ticket: <><path d="M3 8a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v2a2 2 0 0 0 0 4v2a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-2a2 2 0 0 0 0-4V8z"/><path d="M12 6v12" strokeDasharray="2 2"/></>,
    user:   <><circle cx="12" cy="8" r="4"/><path d="M4 21c0-4 4-7 8-7s8 3 8 7"/></>,
    bolt:   <><path d="M13 2 4 14h7l-1 8 9-12h-7l1-8z" strokeLinejoin="round"/></>,
  };
  return (
    <svg className="rail-ic" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7">
      {p[name] || null}
    </svg>
  );
}

function Modal({ open, onClose, children, width = 440 }) {
  if (!open) return null;
  return (
    <div className="modal-back" onClick={onClose}>
      <div className="modal-card" style={{ maxWidth: width }} onClick={e => e.stopPropagation()}>
        {children}
      </div>
    </div>
  );
}

// — Sparkline for rating page
function Spark({ data: pts, w = 90, h = 26 }) {
  if (!pts || pts.length < 2) return null;
  const min = Math.min(...pts), max = Math.max(...pts);
  const span = max - min || 1;
  const step = w / (pts.length - 1);
  const d = pts.map((v, i) => {
    const x = i * step;
    const y = h - ((v - min) / span) * (h - 2) - 1;
    return `${i === 0 ? 'M' : 'L'}${x.toFixed(1)},${y.toFixed(1)}`;
  }).join(' ');
  const up = pts[pts.length - 1] >= pts[0];
  const stroke = up ? '#00C853' : '#FF3D3D';
  return (
    <svg width={w} height={h} className="spark">
      <path d={d} fill="none" stroke={stroke} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

// Toast / inline confirmation
function Toast({ msg, kind = 'ok' }) {
  if (!msg) return null;
  return <div className={cx('toast', `toast-${kind}`)}>{msg}</div>;
}

// Cookie consent banner
function CookieBanner() {
  const [visible, setVisible] = React.useState(() => !localStorage.getItem('fb_cookies_ok'));
  if (!visible) return null;
  const accept = () => { localStorage.setItem('fb_cookies_ok', '1'); setVisible(false); };
  return (
    <div className="cookie-banner">
      <span>🍪 Мы используем cookies для авторизации и сохранения сессии. Без них не получится запомнить ваш вход.</span>
      <button className="btn btn-primary btn-sm" onClick={accept}>Принять</button>
    </div>
  );
}

Object.assign(window, {
  cx, formatPC,
  CoinIcon, PCoin, Avatar, StatusDot, CategoryTag,
  HeaderBar, LeftRail, RailIcon, Modal, Spark, Toast, CookieBanner,
});
