// RiftRegistrars.jsx — акредитовані реєстратори зон RIFT (rivne.ua / rv.ua)
// Дані: registrars-data.js

const T_REG = {
  uk: {
    eyebrow: 'Реєстратори',
    h1a: 'Акредитовані',
    h1b: 'реєстратори',
    sub: 'РІФТ адмініструє зони rivne.ua, rv.ua та rovno.ua, але не приймає реєстрацій напряму. Домени видають акредитовані партнери. Нижче — повний перевірений список.',
    adminTitle: 'Ви на сайті адміністратора',
    adminDesc: 'rift.org.ua — це адміністратор зони, а не реєстратор. Ми тримаємо реєстр, інфраструктуру та правила; оформлення домену для клієнта робить один з акредитованих реєстраторів зі списку.',
    listTitle: 'Перелік реєстраторів',
    listSubOf: (n) => `Станом на 2026 рік — ${n} акредитованих партнерів. Дані синхронізуються з реєстром адміністратора.`,
    cols: { name: 'Реєстратор', company: 'Юридична особа', visit: 'Сайт' },
    visit: 'Перейти →',
    search: 'Пошук за назвою, доменом або реквізитами',
    showing: (n, t) => `Показано ${n} з ${t}`,
    reset: 'Скинути',
    empty: 'Нічого не знайдено',
    helpTitle: 'Як обрати реєстратора',
    help: [
      { n: '01', t: 'Перевірте акредитацію', d: 'Лише партнери РІФТ мають право видавати домени rivne.ua / rv.ua. Усі в списку — акредитовані.' },
      { n: '02', t: 'Порівняйте підтримку', d: 'Українська локалізація, цілодобова допомога, переїзд DNS, безкоштовний SSL у пакеті.' },
      { n: '03', t: 'Свобода переходу', d: 'Змінити реєстратора можна будь-коли через EPP-код. Перенесення між акредитованими — безкоштовне.' },
    ],
  },
  en: {
    eyebrow: 'Registrars',
    h1a: 'Accredited',
    h1b: 'registrars',
    sub: 'RIFT administers the rivne.ua, rv.ua and rovno.ua zones but does not register directly. Domains are issued by accredited partners. The full verified list is below.',
    adminTitle: 'You are on the administrator\'s site',
    adminDesc: 'rift.org.ua is the zone administrator, not a registrar. We hold the registry, infrastructure and rules; the actual domain registration for a client is done by one of the accredited registrars below.',
    listTitle: 'Registrar list',
    listSubOf: (n) => `As of 2026 — ${n} accredited partners. Data is synced from the administrator registry.`,
    cols: { name: 'Registrar', company: 'Legal entity', visit: 'Site' },
    visit: 'Visit →',
    search: 'Search by name, domain or legal entity',
    showing: (n, t) => `Showing ${n} of ${t}`,
    reset: 'Reset',
    empty: 'Nothing found',
    helpTitle: 'How to choose a registrar',
    help: [
      { n: '01', t: 'Check accreditation', d: 'Only RIFT partners may issue rivne.ua / rv.ua domains. Everyone in the list is accredited.' },
      { n: '02', t: 'Compare support', d: 'Ukrainian localisation, 24/7 help, DNS migration, free SSL included.' },
      { n: '03', t: 'Freedom to switch', d: 'You can change registrar anytime via EPP code. Transfer between accredited partners is free.' },
    ],
  },
};

const RegistrarsPage = ({ lang }) => {
  const t = T_REG[lang];

  // Shuffle all registrars, but always keep ВМХостинг within the top 5.
  const PINNED = 'ua.vmhosting';
  const arrange = React.useCallback((list) => {
    const rest = [];
    let pinned = null;
    list.forEach(r => { if (r.id === PINNED) pinned = r; else rest.push(r); });
    for (let i = rest.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [rest[i], rest[j]] = [rest[j], rest[i]];
    }
    if (pinned) {
      const slot = Math.floor(Math.random() * Math.min(5, rest.length + 1)); // 0..4
      rest.splice(slot, 0, pinned);
    }
    return rest;
  }, []);

  // Live data from the RIFT public API, with the bundled snapshot as offline fallback.
  const [ALL, setALL] = React.useState(null); // null = loading
  const [source, setSource] = React.useState('api'); // 'api' | 'cache'
  React.useEffect(() => {
    let alive = true;
    const fromBundle = () => arrange((window.REGISTRARS_DATA || [])
      .filter(r => r.id !== 'ua.rv_reg' && r.id !== 'ua.system')
      .map(r => ({ id: r.id, company: r.company, website: r.website || '' })));
    fetch('https://api.rift.org.ua/public/registrars')
      .then(r => { if (!r.ok) throw new Error('http ' + r.status); return r.json(); })
      .then(data => {
        const list = ((data && data.registrars) || [])
          .filter(reg => reg.identifier !== 'ua.system' && reg.identifier !== 'ua.rv_reg')
          .map(reg => ({ id: reg.identifier, company: reg.company, website: (reg.website || '').trim() }));
        if (!alive) return;
        if (list.length) { setALL(arrange(list)); setSource('api'); }
        else { setALL(fromBundle()); setSource('cache'); }
      })
      .catch(() => { if (alive) { setALL(fromBundle()); setSource('cache'); } });
    return () => { alive = false; };
  }, [arrange]);

  const loading = ALL === null;
  const LIST = ALL || [];
  const TOTAL = LIST.length;

  const [q, setQ] = React.useState('');
  const filtered = React.useMemo(() => {
    const qq = q.trim().toLowerCase();
    if (!qq) return LIST;
    return LIST.filter(r =>
      (r.website || '').toLowerCase().includes(qq) ||
      (r.company || '').toLowerCase().includes(qq) ||
      (r.id || '').toLowerCase().includes(qq)
    );
  }, [LIST, q]);

  const siteOf = (r) => (r.website || '').replace(/^https?:\/\//, '').replace(/\/$/, '');
  const displayOf = (r) => siteOf(r).replace(/^www\./, '') || r.id;

  return (
    <main className="rb-page">
      <section className="rb-pagehead rb-pagehead--reg">
        <div className="rb-eyebrow"><span className="rb-eyebrow__dot" />{t.eyebrow}</div>
        <h1 className="rb-h1 rb-h1--page">
          <span className="rb-h1__a">{t.h1a}</span>
          <span className="rb-h1__b">{t.h1b}</span>
        </h1>
        <p className="rb-lead">{t.sub}</p>
      </section>

      {/* ADMIN BLOCK — RIFT itself */}
      <section className="rb-section">
        <div className="rb-admin" style={{ display: 'grid', gridTemplateColumns: 'auto 1fr', gap: 32, alignItems: 'center' }}>
          <div className="rb-admin__badge" style={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <img src="assets/rift-logo.svg" alt="ТОВ «РІФТ»" loading="lazy" decoding="async" style={{ width: 160, height: 'auto', display: 'block' }} />
          </div>
          <div className="rb-admin__body" style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            <div className="rb-admin__label">{t.adminTitle}</div>
            <div className="rb-admin__name" style={{ fontFamily: 'var(--rb-font-serif)', fontSize: 32, lineHeight: 1, letterSpacing: '-0.02em' }}>ТОВ «РІФТ» <span style={{ color: 'var(--rb-muted)', fontSize: 18 }}>· rift.org.ua</span></div>
            <p className="rb-admin__desc" style={{ fontSize: 15, color: 'var(--rb-muted)', margin: '4px 0', lineHeight: 1.55, maxWidth: 760 }}>{t.adminDesc}</p>
            <div className="rb-admin__meta" style={{ display: 'flex', flexWrap: 'wrap', gap: 20, paddingTop: 12, borderTop: '1px solid var(--rb-line)', marginTop: 8, fontFamily: 'var(--rb-font-mono)', fontSize: 12, color: 'var(--rb-muted)' }}>
              <span><b style={{ color: 'var(--rb-ink)' }}>{lang === 'uk' ? 'Заснування' : 'Founded'}:</b> 2011</span>
              <span><b style={{ color: 'var(--rb-ink)' }}>{lang === 'uk' ? 'Зони' : 'Zones'}:</b> rivne.ua · rv.ua · rovno.ua</span>
              <span><b style={{ color: 'var(--rb-ink)' }}>{lang === 'uk' ? 'Партнерів' : 'Partners'}:</b> {TOTAL}</span>
              <span><b style={{ color: 'var(--rb-ink)' }}>{lang === 'uk' ? 'Активних доменів' : 'Active domains'}:</b> 1200+</span>
            </div>
          </div>
        </div>
      </section>

      {/* REGISTRARS LIST */}
      <section className="rb-section" style={{ paddingTop: 0 }}>
        <div className="rb-section__head">
          <h2 className="rb-h2">{t.listTitle}</h2>
          <p className="rb-sub">{loading ? (lang === 'uk' ? 'Завантаження зі служби реєстру…' : 'Loading from the registry service…') : t.listSubOf(TOTAL)}</p>
        </div>

        <div className="rb-regtools">
          <input className="rb-regtools__search" placeholder={t.search} value={q} onChange={e => setQ(e.target.value)} disabled={loading} />
          <div className="rb-regtools__meta">
            <span>{loading ? '…' : t.showing(filtered.length, TOTAL)}</span>
            {q && <button className="rb-regtools__reset" onClick={() => setQ('')}>{t.reset} ×</button>}
          </div>
        </div>

        <div className="rb-regs">
          <div className="rb-regs__head">
            <span>{t.cols.name}</span>
            <span>{t.cols.company}</span>
            <span>{t.cols.visit}</span>
          </div>
          {loading && [0, 1, 2, 3, 4, 5].map(i => (
            <div key={'sk' + i} className="rb-regs__row rift-regs__sk">
              <div className="rb-regs__name">
                <span className="rb-regs__idx">{String(i + 1).padStart(2, '0')}</span>
                <div style={{ minWidth: 0, flex: 1 }}>
                  <div className="rift-sk rift-sk--t"></div>
                  <div className="rift-sk rift-sk--s"></div>
                </div>
              </div>
              <div className="rift-sk rift-sk--c"></div>
              <div className="rift-sk rift-sk--b"></div>
            </div>
          ))}
          {!loading && filtered.map((r, i) => (
            <div key={r.id} className="rb-regs__row">
              <div className="rb-regs__name">
                <span className="rb-regs__idx">{String(i + 1).padStart(2, '0')}</span>
                <div style={{ minWidth: 0 }}>
                  <div className="rb-regs__title">{displayOf(r)}</div>
                  <div className="rift-regs__handle">
                    <span className="rb-regs__chk" title="RIFT accredited">✓</span>
                    <span>{r.id}</span>
                  </div>
                </div>
              </div>
              <div className="rb-regs__company">{r.company}</div>
              {siteOf(r)
                ? <a href={`https://${siteOf(r)}`} target="_blank" rel="noopener noreferrer" className="rb-regs__cta">{t.visit}</a>
                : <span className="rb-regs__cta" style={{ opacity: 0.4, pointerEvents: 'none' }}>—</span>}
            </div>
          ))}
          {!loading && filtered.length === 0 && <div className="rb-regs__empty">{t.empty}</div>}
        </div>
        {!loading && (
          <p style={{ fontFamily: 'var(--rb-font-mono)', fontSize: 11.5, color: 'var(--rb-muted)', marginTop: 14, letterSpacing: '0.02em' }}>
            {source === 'api'
              ? (lang === 'uk' ? '● Дані в реальному часі з api.rift.org.ua/public/registrars' : '● Live data from api.rift.org.ua/public/registrars')
              : (lang === 'uk' ? '○ Збережений знімок реєстру (служба тимчасово недоступна)' : '○ Cached registry snapshot (service temporarily unavailable)')}
          </p>
        )}
      </section>

      {/* HELP */}
      <section className="rb-section rb-section--alt">
        <div className="rb-section__head">
          <h2 className="rb-h2">{t.helpTitle}</h2>
        </div>
        <div className="rb-helpgrid">
          {t.help.map(h => (
            <div key={h.n} className="rb-helpcard">
              <div className="rb-helpcard__num">{h.n}</div>
              <div className="rb-helpcard__t">{h.t}</div>
              <div className="rb-helpcard__d">{h.d}</div>
            </div>
          ))}
        </div>
      </section>
    </main>
  );
};
window.RegistrarsPage = RegistrarsPage;
