/* Landing UI kit — components.
   Header, Hero, SearchBox, TrustBadges, CategoryTabs, ProductCard,
   LoginModal, RegisterModal.
   Dùng bare `t(...)` từ i18n.js (window.t). */

const { useState, useEffect, useRef } = React;

// ---- Header --------------------------------------------------------------
function LandingHeader({ onLogin, onRegister }) {
  return (
    <header style={lhStyles.wrap}>
      <div style={lhStyles.inner}>
        <a href="#" style={lhStyles.brand}>
          <img src="img/logo-vietmod.svg" alt="Trainer.id.vn" style={{ height: 36 }} />
        </a>
        <nav style={lhStyles.nav}>
          <a href="#" style={{ ...lhStyles.navLink, ...lhStyles.navActive }}>{t('landing.header.home')}</a>
          <a href="#" style={lhStyles.navLink}>{t('landing.header.gameMod')}</a>
          <a href="#" style={lhStyles.navLink}>{t('landing.header.apps')}</a>
          <a href="#" style={lhStyles.navLink}>{t('landing.header.requests')}</a>
        </nav>
        <div style={lhStyles.actions}>
          <button className="btn btn-ghost btn-pill btn-sm" onClick={onLogin}>{t('common.signIn')}</button>
          <button className="btn btn-hot btn-pill btn-sm" onClick={onRegister}>{t('common.signUp')}</button>
        </div>
      </div>
    </header>
  );
}

const lhStyles = {
  wrap: { position: 'sticky', top: 0, zIndex: 20, background: 'rgba(8,10,18,0.7)', backdropFilter: 'blur(12px)', borderBottom: '1px solid var(--line)' },
  inner: { maxWidth: 1280, margin: '0 auto', height: 72, padding: '0 24px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 24 },
  brand: { display: 'flex', alignItems: 'center' },
  nav: { display: 'flex', alignItems: 'center', gap: 4 },
  navLink: { color: 'var(--ink-2)', fontWeight: 600, fontSize: 14, padding: '8px 14px', borderRadius: 999, transition: 'background-color 150ms var(--ease-out), color 150ms var(--ease-out)' },
  navActive: { color: 'var(--ink-1)', background: 'rgba(255,255,255,0.06)' },
  actions: { display: 'flex', gap: 8 },
};

// ---- Hero ----------------------------------------------------------------
function Hero({ onSearch }) {
  const [q, setQ] = useState('');
  return (
    <section style={heroStyles.wrap}>
      {t('landing.hero.badge') && (
        <div style={heroStyles.badge}>
          <span style={{ width: 6, height: 6, borderRadius: 999, background: 'var(--accent-green)', boxShadow: '0 0 10px var(--accent-green)' }} />
          {t('landing.hero.badge')}
        </div>
      )}
      <h1 style={heroStyles.title}>
        {t('landing.hero.title1')}<br/>
        <span className="text-gradient-hot">{t('landing.hero.title2')}</span>
      </h1>
      <p style={heroStyles.subtitle}>{t('landing.hero.subtitle')}</p>
      <p style={heroStyles.emphasis}>{t('landing.hero.emphasis')}</p>

      <div style={heroStyles.searchWrap}>
        <div style={heroStyles.searchInner}>
          <IconSearch size={20} style={{ color: 'var(--ink-3)' }} />
          <input
            className="input"
            style={heroStyles.searchInput}
            placeholder={t('landing.hero.searchPlaceholder')}
            value={q}
            onChange={(e) => setQ(e.target.value)}
            onKeyDown={(e) => e.key === 'Enter' && onSearch?.(q)}
          />
          <button className="btn btn-hot" onClick={() => onSearch?.(q)}>
            <IconSearch size={16} /> {t('landing.hero.searchBtn')}
          </button>
        </div>
      </div>

      <TrustBadges />
    </section>
  );
}

const heroStyles = {
  wrap: { textAlign: 'center', padding: '96px 24px 64px', maxWidth: 980, margin: '0 auto' },
  badge: { display: 'inline-flex', alignItems: 'center', gap: 8, padding: '6px 14px', borderRadius: 999, background: 'var(--accent-green-soft)', color: 'var(--accent-green)', fontSize: 11, fontWeight: 700, letterSpacing: '0.12em', border: '1px solid var(--accent-green-line)', marginBottom: 24 },
  title: { fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 'clamp(56px, 9vw, 96px)', lineHeight: 0.95, letterSpacing: '-0.03em', margin: 0, color: 'var(--ink-1)' },
  subtitle: { fontSize: 18, color: 'var(--ink-2)', maxWidth: 720, margin: '24px auto 4px', lineHeight: 1.55 },
  emphasis: { fontSize: 16, color: 'var(--ink-1)', fontWeight: 600, marginTop: 0 },
  searchWrap: { marginTop: 40, maxWidth: 720, marginInline: 'auto' },
  searchInner: { display: 'flex', alignItems: 'center', gap: 8, padding: 8, ...window.GLASS, border: '1px solid var(--line-strong)', borderRadius: 16, boxShadow: 'var(--shadow-card)' },
  searchInput: { flex: 1, height: 44, border: 'none', background: 'transparent', fontSize: 16 },
};

function TrustBadges() {
  const items = [
    { icon: <IconShield size={16} />, label: t('landing.trust.noVirus') },
    { icon: <IconZap    size={16} />, label: t('landing.trust.fast') },
    { icon: <IconCheck  size={16} />, label: t('landing.trust.verified') },
  ];
  return (
    <div style={{ display: 'flex', justifyContent: 'center', gap: 16, marginTop: 24, flexWrap: 'wrap' }}>
      {items.map((it, i) => (
        <div key={i} style={{ display: 'inline-flex', alignItems: 'center', gap: 8, padding: '8px 14px', borderRadius: 999, background: 'rgba(255,255,255,0.04)', border: '1px solid var(--line)', color: 'var(--ink-2)', fontSize: 12, fontWeight: 700, letterSpacing: '0.10em' }}>
          <span style={{ color: 'var(--accent-green)' }}>{it.icon}</span>
          {it.label}
        </div>
      ))}
    </div>
  );
}

// ---- Category Tabs + Product Grid ----------------------------------------
function CategoryTabs({ tabs, activeIdx, onChange }) {
  return (
    <div style={{ display: 'flex', gap: 8, padding: '0 24px', maxWidth: 1280, margin: '0 auto', flexWrap: 'wrap' }}>
      {tabs.map((t, i) => (
        <button key={i} className={`tab${i === activeIdx ? ' active' : ''}`} onClick={() => onChange(i)}>
          {t.icon} {t.label}
        </button>
      ))}
    </div>
  );
}

function ProductGrid({ items }) {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(260px, 1fr))', gap: 20, padding: '24px 24px 96px', maxWidth: 1280, margin: '0 auto' }}>
      {items.map((it, i) => <ProductCard key={i} {...it} />)}
    </div>
  );
}

function ProductCard({ title, sub, version, accent = 'purple', tag, color }) {
  return (
    <div className="card" style={{ overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
      <div style={{ aspectRatio: '4 / 3', background: color || 'linear-gradient(135deg, #2A1F5C, #131421)', position: 'relative', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <div style={{ width: 64, height: 64, borderRadius: 16, background: 'rgba(255,255,255,0.10)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'rgba(255,255,255,0.5)', fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 28 }}>{title[0]}</div>
        {tag && (
          <span style={{ position: 'absolute', top: 12, left: 12 }} className={`badge ${accent} dot`}>{tag}</span>
        )}
      </div>
      <div style={{ padding: 16, display: 'flex', flexDirection: 'column', gap: 4 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 8 }}>
          <div style={{ fontWeight: 700, color: 'var(--ink-1)', fontSize: 15 }}>{title}</div>
          <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--ink-3)' }}>{version}</span>
        </div>
        <div style={{ fontSize: 13, color: 'var(--ink-2)', lineHeight: 1.5 }}>{sub}</div>
        <button className="btn btn-secondary btn-sm" style={{ marginTop: 12, justifyContent: 'center' }}>
          <IconDownload size={14} /> {t('common.download')}
        </button>
      </div>
    </div>
  );
}

// ---- Modals --------------------------------------------------------------
function ModalShell({ children, onClose, width = 480 }) {
  useEffect(() => {
    const onKey = (e) => e.key === 'Escape' && onClose?.();
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [onClose]);
  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" style={{ maxWidth: width }} onClick={(e) => e.stopPropagation()}>
        <button className="modal-close" onClick={onClose}><IconX size={16} /></button>
        {children}
      </div>
    </div>
  );
}

function LoginModal({ onClose, onSwitchToRegister, onSubmit, busy }) {
  const [u, setU] = useState('');
  const [p, setP] = useState('');
  const [err, setErr] = useState('');
  const submit = () => {
    if (!u || !p) { setErr(t('landing.login.errEmpty')); return; }
    setErr('');
    onSubmit?.(u, p);
  };
  return (
    <ModalShell onClose={onClose}>
      <h2 style={{ marginBottom: 6 }}>{t('landing.login.title')}</h2>
      <p style={{ color: 'var(--ink-2)', fontSize: 14, marginBottom: 24 }}>{t('landing.login.desc')}</p>
      <div className="stack" style={{ gap: 14 }}>
        <div>
          <label className="label">{t('landing.login.usernameLabel')}</label>
          <input className="input" value={u} onChange={(e) => setU(e.target.value)} placeholder={t('landing.login.usernamePh')} autoFocus />
        </div>
        <div>
          <label className="label">{t('landing.login.passwordLabel')}</label>
          <input className="input" type="password" value={p} onChange={(e) => setP(e.target.value)} onKeyDown={(e) => e.key === 'Enter' && submit()} placeholder={t('landing.login.passwordPh')} />
        </div>
        {err && <div style={{ fontSize: 13, color: 'var(--accent-red-hi)' }}>{err}</div>}
        <button className="btn btn-primary btn-lg" style={{ marginTop: 8 }} disabled={busy} onClick={submit}>
          {busy ? t('common.signingIn') : t('common.signIn')}
        </button>
        <div style={{ textAlign: 'center', fontSize: 13, color: 'var(--ink-2)', marginTop: 4 }}>
          {t('landing.login.noAccount')}{' '}
          <a href="#" onClick={(e) => { e.preventDefault(); onSwitchToRegister(); }}>{t('landing.login.signUpNow')}</a>
        </div>
      </div>
    </ModalShell>
  );
}

function RegisterModal({ onClose, onSwitchToLogin, onSubmit, busy }) {
  const [u, setU] = useState('');
  const [p, setP] = useState('');
  const [p2, setP2] = useState('');
  const [err, setErr] = useState('');
  const submit = () => {
    if (!u || u.length < 3)  { setErr(t('landing.register.errUsername')); return; }
    if (!p || p.length < 8)  { setErr(t('landing.register.errPassword')); return; }
    if (p !== p2)            { setErr(t('landing.register.errMismatch')); return; }
    setErr('');
    onSubmit?.(u, p);
  };
  return (
    <ModalShell onClose={onClose}>
      <h2 style={{ marginBottom: 6 }}>{t('landing.register.title')}</h2>
      <p style={{ color: 'var(--ink-2)', fontSize: 14, marginBottom: 24 }}>{t('landing.register.desc')}</p>
      <div className="stack" style={{ gap: 14 }}>
        <div>
          <label className="label">{t('landing.login.usernameLabel')}</label>
          <input className="input" value={u} onChange={(e) => setU(e.target.value)} placeholder={t('landing.register.usernamePh')} autoFocus />
        </div>
        <div>
          <label className="label">{t('landing.login.passwordLabel')}</label>
          <input className="input" type="password" value={p} onChange={(e) => setP(e.target.value)} placeholder={t('landing.register.passwordPh')} />
        </div>
        <div>
          <label className="label">{t('landing.register.confirmLabel')}</label>
          <input className="input" type="password" value={p2} onChange={(e) => setP2(e.target.value)} onKeyDown={(e) => e.key === 'Enter' && submit()} placeholder={t('landing.login.passwordPh')} />
        </div>
        {err && <div style={{ fontSize: 13, color: 'var(--accent-red-hi)' }}>{err}</div>}
        <button className="btn btn-primary btn-lg" style={{ marginTop: 8 }} disabled={busy} onClick={submit}>
          {busy ? t('common.signingUp') : t('common.signUp')}
        </button>
        <div style={{ textAlign: 'center', fontSize: 13, color: 'var(--ink-2)', marginTop: 4 }}>
          {t('landing.register.haveAccount')}{' '}
          <a href="#" onClick={(e) => { e.preventDefault(); onSwitchToLogin(); }}>{t('common.signIn')}</a>
        </div>
      </div>
    </ModalShell>
  );
}

Object.assign(window, { LandingHeader, Hero, TrustBadges, CategoryTabs, ProductGrid, ProductCard, ModalShell, LoginModal, RegisterModal });
