/* app.jsx — Hero assembly, language state, tweaks, render. */

const { useState, useEffect } = React;

/* ---- helpers ---- */
function hexToRgb(hex) {
  const h = hex.replace('#', '');
  const n = parseInt(h.length === 3 ? h.split('').map(c => c + c).join('') : h, 16);
  return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
}
function lighten([r, g, b], amt) {
  const f = (c) => Math.round(c + (255 - c) * amt);
  return `rgb(${f(r)}, ${f(g)}, ${f(b)})`;
}

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "brand": "#2f59d6",
  "heroBg": "light",
  "font": "'Hanken Grotesk'"
}/*EDITMODE-END*/;

const FONT_LABELS = {
  "'Hanken Grotesk'": "Hanken Grotesk",
  "'Geist'": "Geist",
  "'Manrope'": "Manrope",
};

/* ---------- Hero Dashboard visual ---------- */
function ServerBar({ label, pct, color }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: '0.3rem' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '0.72rem', fontWeight: 600 }}>
        <span style={{ color: 'rgba(var(--brand-deep),0.6)' }}>{label}</span>
        <span style={{ color: 'rgba(var(--brand-deep),0.85)' }}>{pct}%</span>
      </div>
      <div style={{ height: 5, borderRadius: 99, background: 'rgba(var(--brand-deep),0.08)', overflow: 'hidden' }}>
        <div style={{ height: '100%', width: pct + '%', borderRadius: 99,
          background: color || 'var(--brand)',
          transition: 'width 1.2s cubic-bezier(0.16,1,0.3,1)' }} />
      </div>
    </div>
  );
}

function PulseDot({ color }) {
  return (
    <span style={{ position: 'relative', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: 10, height: 10 }}>
      <span style={{ position: 'absolute', width: '100%', height: '100%', borderRadius: '50%',
        background: color || '#22c55e', opacity: 0.4, animation: 'ping 1.8s ease-in-out infinite' }} />
      <span style={{ width: 7, height: 7, borderRadius: '50%', background: color || '#22c55e', flexShrink: 0 }} />
    </span>
  );
}

function HeroDashboard({ t }) {
  const isRu = t === I18N.ru;
  const servers = [
    { name: 'VPS-01 Moscow',   cpu: 28, ram: 41 },
    { name: 'VPS-02 Moscow',   cpu: 63, ram: 57 },
    { name: 'Dedicated Frankfurt', cpu: 12, ram: 34 },
  ];
  return (
    <div className="hero-dashboard anim d4">
      {/* Server list card */}
      <div style={{
        background: 'rgba(255,255,255,0.48)', backdropFilter: 'blur(22px)', WebkitBackdropFilter: 'blur(22px)',
        border: '1px solid rgba(255,255,255,0.65)', borderRadius: '1.25rem', padding: '1rem 1.1rem',
        boxShadow: '0 20px 50px -30px rgba(var(--brand-deep),0.4)',
        display: 'flex', flexDirection: 'column', gap: '0.7rem',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <span style={{ fontSize: '0.7rem', fontWeight: 700, letterSpacing: '0.09em', textTransform: 'uppercase', color: 'rgba(var(--brand-deep),0.5)' }}>
            {isRu ? 'Серверы' : 'Servers'}
          </span>
          <span style={{ display: 'flex', alignItems: 'center', gap: '0.3rem', fontSize: '0.68rem', fontWeight: 600, color: '#16a34a' }}>
            <PulseDot />{isRu ? 'Все онлайн' : 'All online'}
          </span>
        </div>
        {servers.map((s, i) => (
          <div key={i} style={{ display: 'flex', alignItems: 'center', gap: '0.55rem', padding: '0.5rem 0.65rem',
            background: 'rgba(255,255,255,0.55)', borderRadius: '0.75rem', border: '1px solid rgba(255,255,255,0.7)' }}>
            <PulseDot color="#22c55e" />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: '0.76rem', fontWeight: 600, color: 'rgba(var(--brand-deep),0.9)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{s.name}</div>
              <div style={{ fontSize: '0.66rem', color: 'rgba(var(--brand-deep),0.45)', marginTop: '0.05rem' }}>CPU {s.cpu}% · RAM {s.ram}%</div>
            </div>
            <span style={{ fontSize: '0.65rem', fontWeight: 600, color: '#16a34a', background: 'rgba(34,197,94,0.1)', borderRadius: '999px', padding: '0.12rem 0.5rem', whiteSpace: 'nowrap' }}>online</span>
          </div>
        ))}
      </div>

      {/* Metrics card */}
      <div style={{
        background: 'rgba(255,255,255,0.48)', backdropFilter: 'blur(22px)', WebkitBackdropFilter: 'blur(22px)',
        border: '1px solid rgba(255,255,255,0.65)', borderRadius: '1.25rem', padding: '1rem 1.1rem',
        boxShadow: '0 20px 50px -30px rgba(var(--brand-deep),0.4)',
        display: 'flex', flexDirection: 'column', gap: '0.65rem',
      }}>
        <span style={{ fontSize: '0.7rem', fontWeight: 700, letterSpacing: '0.09em', textTransform: 'uppercase', color: 'rgba(var(--brand-deep),0.5)' }}>
          {isRu ? 'Мониторинг' : 'Monitoring'}
        </span>
        <ServerBar label="CPU" pct={43} color="var(--brand)" />
        <ServerBar label="RAM" pct={61} color="#6366f1" />
        <ServerBar label={isRu ? 'Диск' : 'Disk'} pct={28} color="#0ea5e9" />
        <ServerBar label={isRu ? 'Сеть' : 'Network'} pct={17} color="#10b981" />
        <div style={{ marginTop: '0.1rem', padding: '0.5rem 0.7rem', background: 'rgba(var(--brand-rgb),0.06)', borderRadius: '0.7rem',
          display: 'flex', alignItems: 'center', gap: '0.4rem' }}>
          <Gauge style={{ width: 13, height: 13, color: 'var(--brand)', flexShrink: 0 }} />
          <span style={{ fontSize: '0.71rem', fontWeight: 600, color: 'rgba(var(--brand-deep),0.75)' }}>
            {isRu ? 'Аптайм 30 дней: ' : '30-day uptime: '}<strong style={{ color: 'var(--brand)' }}>99.98%</strong>
          </span>
        </div>
      </div>

      <style>{`@keyframes ping { 0%,100%{transform:scale(1);opacity:0.4} 50%{transform:scale(2.2);opacity:0} }`}</style>
    </div>
  );
}

/* ---------- Hero ---------- */
function Hero({ t, lang, setLang, deep }) {
  return (
    <>
      {/* Sticky nav — same as inner pages */}
      <div style={{
        position: 'sticky', top: 0, zIndex: 100,
        background: 'rgba(233,237,243,0.82)',
        backdropFilter: 'blur(22px)', WebkitBackdropFilter: 'blur(22px)',
        borderBottom: '1px solid rgba(47,89,214,0.07)',
      }}>
        <Navbar t={t} lang={lang} setLang={setLang} />
      </div>

      <div className="hero-wrap" style={{ paddingTop: 0 }}>
        <section className={"hero-card" + (deep ? " deep" : "")}
                 style={{ height: 'calc(100svh - 68px - 2.5rem)' }}>
          <div className="aurora">
            <span className="blob b1" /><span className="blob b2" /><span className="blob b3" />
            <span className="grain" />
          </div>

          <div className="hero-inner">
            <div className="hero-text">
              <HeroBadge text={t.badge} />
              <h1 className="hero-h1 anim d2">
                {t.h1a}<span className="accent">{t.h1accent}</span>{t.h1b} <span className="soft">{t.h1soft}</span>
              </h1>
              <p className="hero-sub anim d3">{t.sub}</p>
              <div className="hero-actions anim d3">
                <button className="btn btn-primary">{t.ctaPrimary}<ArrowRight /></button>
                <button className="btn btn-ghost">{t.ctaGhost}</button>
              </div>
              <div className="hero-feats anim d4">
                <div className="feat"><Zap />{t.feats[0]}</div>
                <div className="feat"><ShieldCheck />{t.feats[1]}</div>
                <div className="feat"><Gauge />{t.feats[2]}</div>
              </div>
            </div>

            <HeroDashboard t={t} />
            <StatCard t={t} />
            <Corner t={t} />
          </div>
        </section>
      </div>
    </>
  );
}

/* ---------- App ---------- */
function App() {
  const [lang, setLang] = useState(() => localStorage.getItem('hl_lang') || 'ru');
  const [tw, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const t = I18N[lang];
  const revealRef = useReveal();

  useEffect(() => { localStorage.setItem('hl_lang', lang); }, [lang]);
  useEffect(() => { document.documentElement.lang = lang; }, [lang]);

  // Force entrance end-state visible after animations would have finished,
  // so throttled/headless captures never show a blank hero.
  useEffect(() => {
    const id = setTimeout(() => document.documentElement.classList.add('anims-finished'), 300);
    return () => clearTimeout(id);
  }, []);

  // apply brand + font tokens
  useEffect(() => {
    const root = document.documentElement;
    const rgb = hexToRgb(tw.brand);
    root.style.setProperty('--brand', tw.brand);
    root.style.setProperty('--brand-rgb', rgb.join(', '));
    root.style.setProperty('--brand-bright', lighten(rgb, 0.22));
    root.style.setProperty('--font', `${tw.font}, 'Hanken Grotesk', ui-sans-serif, system-ui, sans-serif`);
  }, [tw.brand, tw.font]);

  const deep = tw.heroBg === 'deep';

  return (
    <div className="page" ref={revealRef}>
      <Hero t={t} lang={lang} setLang={setLang} deep={deep} />
      <Features t={t} />
      <Services t={t} />
      <DataCenter t={t} />
      <StatBand t={t} />
      <CTA t={t} />
      <SiteFooter t={t} />

      <TweaksPanel>
        <TweakSection label={lang === 'ru' ? 'Бренд' : 'Brand'} />
        <TweakColor label={lang === 'ru' ? 'Цвет' : 'Color'} value={tw.brand}
          options={['#2f59d6', '#1e40af', '#1d74d6', '#3f3bc4']}
          onChange={(v) => setTweak('brand', v)} />
        <TweakSelect label={lang === 'ru' ? 'Шрифт' : 'Font'} value={tw.font}
          options={Object.entries(FONT_LABELS).map(([value, label]) => ({ value, label }))}
          onChange={(v) => setTweak('font', v)} />

        <TweakSection label={lang === 'ru' ? 'Hero-фон' : 'Hero background'} />
        <TweakRadio label={lang === 'ru' ? 'Стиль' : 'Style'} value={tw.heroBg}
          options={lang === 'ru'
            ? [{ value: 'light', label: 'Светлый' }, { value: 'deep', label: 'Тёмный' }]
            : [{ value: 'light', label: 'Light' }, { value: 'deep', label: 'Deep' }]}
          onChange={(v) => setTweak('heroBg', v)} />

        <TweakSection label={lang === 'ru' ? 'Язык' : 'Language'} />
        <TweakRadio label={lang === 'ru' ? 'Язык интерфейса' : 'Interface'} value={lang}
          options={[{ value: 'ru', label: 'RU' }, { value: 'en', label: 'EN' }]}
          onChange={(v) => setLang(v)} />
      </TweaksPanel>
    </div>
  );
}

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