const { useState, useEffect } = React;

function contentRoot() {
  return window.CONTENT || {};
}

function getServices() {
  return contentRoot().services || [];
}

function getChannels() {
  return contentRoot().channels || [];
}

function getNewsItems() {
  return contentRoot().home?.news?.items || [];
}

function newsKey(item, index) {
  return item.slug || `news-${index + 1}`;
}

function newsPath(item, index) {
  return `/news/${encodeURIComponent(newsKey(item, index))}`;
}

const PageTop = ({ navigate, crumbs, title, subtitle }) => (
  <div className="page-top">
    <div className="wrap">
      <div className="crumb">
        <a href="#/" onClick={e => { e.preventDefault(); navigate('/'); }}>Головна</a>
        {crumbs.map((c, i) => (
          <React.Fragment key={i}>
            <span>›</span>
            {c.path
              ? <a href={`#${c.path}`} onClick={e => { e.preventDefault(); navigate(c.path); }}>{c.label}</a>
              : <span>{c.label}</span>}
          </React.Fragment>
        ))}
      </div>
      <h1 className="h2" style={{ marginTop: 10 }}>{title}</h1>
      {subtitle && <p style={{ fontSize: 16, color: 'rgba(255,255,255,0.65)', marginTop: 8 }}>{subtitle}</p>}
    </div>
  </div>
);

const AboutPage = ({ navigate }) => {
  const about = contentRoot().about || {};
  const values = about.values || {};
  const stats = [
    ['1200+', 'Випускників'],
    [String(getServices().length), 'Програм'],
  ];

  return (
    <>
      <PageTop navigate={navigate} crumbs={[{ label: 'Про нас' }]} title={about.hero?.title || 'Про ТОВ «ЦРПК»'} subtitle={about.hero?.subtitle || ''} />

      <section style={{ padding: '56px 0 0' }}>
        <div className="wrap">
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 380px', gap: 72, alignItems: 'center', paddingBottom: 56, borderBottom: '1px solid rgba(255,255,255,0.1)' }}>
            <div>
              <div className="label">{about.history?.label || 'Про центр'}</div>
              <h2 className="h2" style={{ marginBottom: 24 }}>{about.history?.title || ''}</h2>
              <p style={{ fontSize: 16, color: 'rgba(255,255,255,0.7)', lineHeight: 1.85, marginBottom: 16 }}>{about.history?.paragraph1 || ''}</p>
              <p style={{ fontSize: 16, color: 'rgba(255,255,255,0.7)', lineHeight: 1.85 }}>{about.history?.paragraph2 || ''}</p>
              <div style={{ display: 'flex', gap: 32, marginTop: 32 }}>
                {stats.map(([n, l]) => (
                  <div key={l} style={{ borderLeft: '3px solid #3b82f6', paddingLeft: 16 }}>
                    <div style={{ fontFamily: "'Outfit',sans-serif", fontSize: 36, fontWeight: 900, color: '#93c5fd', lineHeight: 1 }}>{n}</div>
                    <div style={{ fontSize: 13, color: 'rgba(255,255,255,0.65)', marginTop: 4 }}>{l}</div>
                  </div>
                ))}
              </div>
            </div>
            <div className="img-ph" style={{ minHeight: 320, padding: 0 }}>
              <img src="uploads/about-us.jpg" alt="Фото центру" style={{ width: '100%', height: '100%', minHeight: 320, objectFit: 'cover', display: 'block' }} />
            </div>
          </div>
        </div>
      </section>

      <section className="sec">
        <div className="wrap">
          <div className="sec-head c" style={{ marginBottom: 56 }}>
            {/* <div className="label">{values.label || 'Принципи'}</div> */}
            <h2 className="h2">{values.title || 'Місія, цінності, візія'}</h2>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 24 }}>
            {(values.items || []).map((v, i) => (
              <div key={i} style={{
                padding: '40px 32px',
                background: 'rgba(255,255,255,0.04)',
                border: '1px solid rgba(255,255,255,0.1)',
                borderRadius: 20,
                backdropFilter: 'blur(8px)',
                display: 'flex',
                flexDirection: 'column',
                gap: 24,
              }}>
                <div style={{
                  width: 64, height: 64, borderRadius: 16,
                  background: 'linear-gradient(135deg, rgba(37,99,235,0.25), rgba(37,99,235,0.1))',
                  border: '1px solid rgba(147,197,253,0.4)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  color: '#93c5fd',
                }}>
                  <Ico n={i === 1 ? 'book' : i === 2 ? 'medkit' : 'award'} s={28} />
                </div>
                <div>
                  <div style={{ fontFamily: "'Outfit',sans-serif", fontSize: 11, fontWeight: 800, letterSpacing: 2.5, color: 'rgba(255,255,255,0.4)', marginBottom: 8, textTransform: 'uppercase' }}>
                    {v.badge || ''}
                  </div>
                  <h3 className="h3" style={{ marginBottom: 12, color: '#fff' }}>{v.title || ''}</h3>
                  <p style={{ fontSize: 15.5, color: 'rgba(255,255,255,0.72)', lineHeight: 1.7 }}>{v.text || ''}</p>
                </div>
              </div>
            ))}
          </div>
        </div>
      </section>

      <section>
        <div className="wrap" style={{ paddingBottom: 72 }}>
          <div style={{ paddingTop: 64, marginBottom: 8 }}>
            <div className="label">{about.priorities?.label || 'Пріоритети'}</div>
            <h2 className="h2">{about.priorities?.title || 'Що відрізняє нас'}</h2>
          </div>
          {(about.priorities?.items || []).map((text, i) => (
            <div key={i} className="prio-row">
              <div className="prio-num">{String(i + 1).padStart(2, '0')}</div>
              <div>
                <p style={{ fontSize: 16, color: 'rgba(255,255,255,0.7)', lineHeight: 1.85 }}>{text}</p>
              </div>
            </div>
          ))}
        </div>
      </section>
    </>
  );
};

const ServicesPage = ({ navigate }) => {
  const [open, setOpen] = useState(null);
  const services = getServices();
  const sp = contentRoot().servicesPage || {};
  return (
    <>
      <PageTop
        navigate={navigate}
        crumbs={[{ label: 'Послуги' }]}
        title={sp.hero?.title || `${services.length} програм підвищення кваліфікації`}
        subtitle={sp.hero?.subtitle || ''}
      />

      <section style={{ padding: '40px 0 80px' }}>
        <div className="wrap">
          <div className="acc-list">
            {services.map((s, i) => (
              <div key={s.slug} className="acc-row">
                <button className="acc-head" onClick={() => setOpen(open === i ? null : i)}>
                  <div className="acc-bar" style={{ background: s.color || '#2563eb' }}></div>
                  <div className="acc-ico" style={{ background: s.colorBg || '#dbeafe' }}>
                    <span style={{ color: s.color || '#2563eb' }}><Ico n={s.icon || 'book'} s={26} /></span>
                  </div>
                  <div className="acc-info">
                    <h3>{s.title}{s.isNew && <span className="new-badge">Новинка</span>}</h3>
                    <p>{s.duration} · <span style={{ color: '#86efac', fontWeight: 700 }}>Старт: {window.formatCourseDate(s.slug)}</span></p>
                  </div>
                  <div className="acc-right">
                    <span className="acc-price" style={{ color: '#93c5fd' }}>{s.price}</span>
                    <span className={`acc-chevron ${open === i ? 'open' : ''}`}><Ico n="chevron" s={20} /></span>
                  </div>
                </button>
                <div className={`acc-body ${open === i ? 'open' : ''}`}>
                  <div className="acc-body-left">
                    <p>{s.fullDesc}</p>
                    <button className="btn btn-blue btn-sm" onClick={() => navigate(`/service/${s.slug}`)}>
                      Записатися <Ico n="arrow" s={14} />
                    </button>
                  </div>
                  <div>
                    <div style={{ fontFamily: "'Outfit',sans-serif", fontSize: 12, fontWeight: 700, color: 'rgba(255,255,255,0.6)', textTransform: 'uppercase', letterSpacing: 1.5, marginBottom: 12 }}>
                      {contentRoot().serviceDetail?.docsTitle || 'Документи'}
                    </div>
                    <ul className="acc-docs">{(s.docs || []).map((d, j) => <li key={j}>{d}</li>)}</ul>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </section>

      <div className="cta-band">
        <div className="wrap">
          <h2 className="h2">{sp.cta?.title || 'Потрібна консультація?'}</h2>
          <p>{sp.cta?.subtitle || ''}</p>
          <div className="cta-btns">
            <button className="btn btn-blue btn-lg" onClick={() => navigate('/contact')}>
              {sp.cta?.button || 'Зв\'язатися'} <Ico n="arrow" s={18} />
            </button>
          </div>
        </div>
      </div>
    </>
  );
};

const ServiceDetailPage = ({ navigate, slug }) => {
  const services = getServices();
  const svc = services.find(s => s.slug === slug) || services[0] || {};
  const sd = contentRoot().serviceDetail || {};
  const channels = getChannels();
  const relatedNews = getNewsItems().map((item, index) => ({ item, index }))
    .filter(({ item }) => item.serviceSlug && item.serviceSlug === svc.slug);

  return (
    <>
      <div style={{ height: 6, background: svc.color || '#2563eb' }}></div>
      <div className="page-top">
        <div className="wrap">
          <div className="crumb">
            <a href="#/" onClick={e => { e.preventDefault(); navigate('/'); }}>Головна</a>
            <span>›</span>
            <a href="#/services" onClick={e => { e.preventDefault(); navigate('/services'); }}>Послуги</a>
            <span>›</span>
            <span>{svc.title}</span>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 20, marginTop: 18 }}>
            <div style={{ width: 76, height: 76, borderRadius: 18, background: svc.colorBg || '#dbeafe', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
              <span style={{ color: svc.color || '#2563eb' }}><Ico n={svc.icon || 'book'} s={40} /></span>
            </div>
            <h1 className="h2" style={{ margin: 0 }}>{svc.title}</h1>
          </div>
        </div>
      </div>

      <div className="wrap" style={{ paddingTop: 32 }}>
        <div className="sdet-info-bar">
          <div className="sdet-info-item">
            <div className="sdet-info-lbl">{sd.costLabel || 'Вартість'}</div>
            <div className="sdet-info-val">{svc.price}</div>
          </div>
          <div className="sdet-info-item">
            <div className="sdet-info-lbl">{sd.durationLabel || 'Тривалість'}</div>
            <div className="sdet-info-val">{svc.duration}</div>
          </div>
          <div className="sdet-info-item">
            <div className="sdet-info-lbl">Найближчий старт</div>
            <div className="sdet-info-val" style={{ color: '#86efac' }}>{window.formatCourseDate(svc.slug, { withYear: true })}</div>
          </div>
          <div className="sdet-info-item">
            <div className="sdet-info-lbl">Форма навчання</div>
            <div className="sdet-info-val">Очна або заочна (онлайн)</div>
          </div>
        </div>

        <div className="sdet-grid" style={{ paddingBottom: 80 }}>
          <div>
            <h2 className="h2" style={{ marginBottom: 20 }}>{sd.courseLabel || 'Про програму'}</h2>
            <p style={{ fontSize: 16, color: 'rgba(255,255,255,0.72)', lineHeight: 1.9, marginBottom: 20 }}>{svc.fullDesc}</p>
            <p style={{ fontSize: 15, color: 'rgba(255,255,255,0.65)', lineHeight: 1.85, marginBottom: 40 }}>{sd.legalNote || ''}</p>

            <h3 style={{ fontFamily: "'Outfit',sans-serif", fontSize: 18, fontWeight: 700, marginBottom: 16, color: '#fff' }}>{sd.docsTitle || 'Необхідні документи'}</h3>
            <ul style={{ listStyle: 'none', padding: 0 }}>
              {(svc.docs || []).map((d, i) => (
                <li key={i} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 0', borderBottom: '1px solid rgba(255,255,255,0.1)', fontSize: 15, color: 'rgba(255,255,255,0.85)' }}>
                  <span style={{ width: 22, height: 22, borderRadius: '50%', background: svc.color || '#2563eb', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                    <svg viewBox="0 0 16 16" width="11" height="11" fill="none" stroke="white" strokeWidth="2.5"><polyline points="2 8 6 12 14 4"/></svg>
                  </span>
                  {d}
                </li>
              ))}
            </ul>

            {relatedNews.length > 0 && (
              <div className="service-news">
                <div className="label">Новини</div>
                <h3 className="h3">Пов'язані новини</h3>
                <div className="service-news-list">
                  {relatedNews.map(({ item, index }) => (
                    <button key={newsKey(item, index)} className="service-news-item" onClick={() => navigate(newsPath(item, index))}>
                      <span>{item.title || 'Новина'}</span>
                      <small>{item.description || ''}</small>
                      <strong>Читати <Ico n="arrow" s={14} /></strong>
                    </button>
                  ))}
                </div>
              </div>
            )}
          </div>

          <div className="sdet-form-box">
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 20, paddingBottom: 20, borderBottom: '1px solid rgba(255,255,255,0.12)' }}>
              <div style={{ width: 40, height: 40, borderRadius: 10, background: svc.colorBg || '#dbeafe', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <span style={{ color: svc.color || '#2563eb' }}><Ico n={svc.icon || 'book'} s={20} /></span>
              </div>
              <div>
                <div style={{ fontFamily: "'Outfit',sans-serif", fontSize: 13, fontWeight: 700, color: 'rgba(255,255,255,0.6)', textTransform: 'uppercase', letterSpacing: 1 }}>{sd.enrollTitle || 'Записатися на курс'}</div>
                <div style={{ fontFamily: "'Outfit',sans-serif", fontSize: 15, fontWeight: 700, color: '#fff' }}>{svc.title}</div>
              </div>
            </div>

            <div style={{ background: 'rgba(22,163,74,0.15)', border: '1px solid rgba(22,163,74,0.35)', borderRadius: 10, padding: '12px 14px', marginBottom: 20, display: 'flex', alignItems: 'center', gap: 10 }}>
              <span style={{ width: 8, height: 8, borderRadius: '50%', background: '#22c55e', boxShadow: '0 0 0 3px rgba(34,197,94,0.25)', flexShrink: 0 }}></span>
              <div>
                <div style={{ fontFamily: "'Outfit',sans-serif", fontSize: 11, fontWeight: 700, letterSpacing: 1, textTransform: 'uppercase', color: 'rgba(255,255,255,0.6)' }}>Найближчий старт</div>
                <div style={{ fontFamily: "'Outfit',sans-serif", fontSize: 16, fontWeight: 800, color: '#86efac' }}>{window.formatCourseDate(svc.slug, { withYear: true })}</div>
              </div>
            </div>

            <div style={{ fontFamily: "'Outfit',sans-serif", fontSize: 13, fontWeight: 700, color: 'rgba(255,255,255,0.65)', marginBottom: 12 }}>
              Оберіть зручний спосіб зв'язку:
            </div>

            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              {channels.map(ch => (
                <a key={ch.id} href={ch.href} target={ch.id === 'phone' ? '_self' : '_blank'} rel="noopener noreferrer"
                  className={`qc-btn qc-btn-${ch.id === 'phone' ? 'tel' : ch.id === 'telegram' ? 'tg' : ch.id === 'whatsapp' ? 'wa' : 'vb'}`}>
                  <div className="qc-icon"><Ico n={ch.icon || 'phone'} s={18} /></div>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 11, fontWeight: 600, opacity: 0.85, letterSpacing: 0.5, textTransform: 'uppercase' }}>
                      {ch.id === 'phone' ? 'Зателефонувати' : `Написати у ${ch.label}`}
                    </div>
                    <div style={{ fontSize: 15, fontWeight: 800 }}>{contentRoot().header?.phone || '+38 (067) 264-10-41'}</div>
                  </div>
                  <Ico n="arrow" s={16} />
                </a>
              ))}
            </div>
          </div>
        </div>
      </div>
    </>
  );
};

const NewsDetailPage = ({ navigate, slug }) => {
  const news = contentRoot().home?.news || {};
  const items = getNewsItems();
  const services = getServices();
  const decodedSlug = decodeURIComponent(slug || '');
  const idx = items.findIndex((item, index) => newsKey(item, index) === decodedSlug);
  const activeIndex = idx >= 0 ? idx : 0;
  const item = items[activeIndex];
  const service = services.find(s => s.slug && s.slug === item?.serviceSlug);

  if (!item) {
    return (
      <>
        <PageTop navigate={navigate} crumbs={[{ label: 'Новини' }]} title="Новину не знайдено" />
        <section className="sec">
          <div className="wrap">
            <button className="btn btn-blue" onClick={() => navigate('/')}>Повернутися на головну</button>
          </div>
        </section>
      </>
    );
  }

  return (
    <>
      <PageTop
        navigate={navigate}
        crumbs={[
          { path: '/', label: news.label || 'Новини' },
          { label: item.title || 'Новина' },
        ]}
        title={item.title || 'Новина'}
        subtitle={item.description || ''}
      />

      <section className="news-detail-section">
        <div className="wrap">
          <article className="news-detail-card">
            <div className="news-kicker">{news.label || 'Новини'} · {String(activeIndex + 1).padStart(2, '0')}</div>
            <p className="news-detail-lead">{item.description || ''}</p>
            <div className="news-detail-text">{item.details || ''}</div>
            <div className="news-detail-actions">
              <button className="btn btn-outline" onClick={() => navigate('/')}>До новин</button>
              {service && (
                <button className="btn btn-outline" onClick={() => navigate(`/service/${service.slug}`)}>
                  Перейти до {service.title}
                </button>
              )}
              <button className="btn btn-blue" onClick={() => navigate('/contact')}>Зв'язатися <Ico n="arrow" s={16} /></button>
            </div>
          </article>
        </div>
      </section>
    </>
  );
};

const ContactPage = ({ navigate }) => {
  const c = contentRoot();
  const formCfg = c.contact?.form || {};
  const infoItems = c.contact?.infoSection?.items || [];
  const channels = getChannels();
  const services = getServices();
  const [form, setForm] = useState({ name: '', phone: '', email: '', channel: 'phone', course: '', msg: '' });
  const [ok, setOk] = useState(false);
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);
  const [turnstileToken, setTurnstileToken] = useState('');

  useEffect(() => {
    const siteKey = c.settings?.turnstileSiteKey || '1x00000000000000000000AA';
    if (!window.turnstile) return;
    const container = document.getElementById('turnstile-container');
    if (!container) return;
    container.innerHTML = '';
    window.turnstile.render('#turnstile-container', {
      sitekey: siteKey,
      callback: token => setTurnstileToken(token),
      'expired-callback': () => setTurnstileToken(''),
      'error-callback': () => setTurnstileToken(''),
    });
  }, [c.settings?.turnstileSiteKey]);

  const submit = async e => {
    e.preventDefault();
    setError('');
    setLoading(true);

    const selectedCourse = services.find(s => s.slug === form.course);
    try {
      const r = await fetch('/api/submit', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          source: 'contact',
          courseSlug: form.course,
          courseName: selectedCourse ? selectedCourse.title : '',
          name: form.name,
          phone: form.phone,
          email: form.email,
          message: [
            form.msg ? `Зручний час: ${form.msg}` : '',
            form.channel ? `Бажаний канал: ${form.channel}` : '',
          ].filter(Boolean).join('\n'),
          turnstileToken,
        }),
      });
      const data = await r.json();
      if (!r.ok) {
        setError(data.error || 'Не вдалося надіслати заявку.');
        return;
      }
      setOk(true);
      setForm({ name: '', phone: '', email: '', channel: 'phone', course: '', msg: '' });
      setTurnstileToken('');
    } catch {
      setError('Помилка мережі. Спробуйте ще раз.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="split-contact">
      <div className="sc-left">
        <div className="sc-left-orb"></div>
        <div style={{ position: 'relative', zIndex: 1 }}>
          <div className="crumb" style={{ marginBottom: 32 }}>
            <a href="#/" onClick={e => { e.preventDefault(); navigate('/'); }}>Головна</a>
            <span>›</span><span>Контакти</span>
          </div>
          <div style={{ fontFamily: "'Outfit',sans-serif", fontSize: 12, fontWeight: 700, color: 'rgba(255,255,255,0.5)', textTransform: 'uppercase', letterSpacing: 2, marginBottom: 8 }}>Телефон</div>
          <a href={c.header?.phoneHref || 'tel:+380672641041'} className="sc-phone" style={{ whiteSpace: 'nowrap' }}>{c.header?.phone || '+38 (067) 264-10-41'}</a>
          <div style={{ fontFamily: "'Outfit',sans-serif", fontSize: 12, fontWeight: 700, color: 'rgba(255,255,255,0.5)', textTransform: 'uppercase', letterSpacing: 2, marginTop: 24, marginBottom: 6 }}>Email</div>
          <a href={`mailto:${c.footer?.email || 'cdpc.tov@gmail.com'}`} style={{ fontSize: 17, color: 'rgba(255,255,255,0.85)', textDecoration: 'none', fontWeight: 500 }}>{c.footer?.email || 'cdpc.tov@gmail.com'}</a>

          <div className="sc-divider"></div>

          <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginBottom: 32 }}>
            {channels.filter(ch => ch.id !== 'phone').map(ch => (
              <a key={ch.id} href={ch.href} target="_blank" rel="noopener noreferrer" className={`qc-btn qc-btn-${ch.id === 'telegram' ? 'tg' : ch.id === 'whatsapp' ? 'wa' : 'vb'}`} style={{ width: '100%' }}>
                <div className="qc-icon"><Ico n={ch.icon || 'send'} s={18} /></div>
                <div style={{ flex: 1 }}><div style={{ fontSize: 15, fontWeight: 800 }}>{ch.label}</div></div>
                <Ico n="arrow" s={16} />
              </a>
            ))}
          </div>

          <div className="sc-cinfo">
            {infoItems.map((it, i) => (
              <div key={i} className="sc-ci">
                <div className="sc-ci-dot"></div>
                <div>
                  <div className="sc-ci-lbl">{it.label}</div>
                  <div className="sc-ci-val">{it.value}</div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>

      <div className="sc-right">
        <div style={{ maxWidth: 540 }}>
          <div className="crumb" style={{ marginBottom: 24 }}>
            <a href="#/" onClick={e => { e.preventDefault(); navigate('/'); }}>Головна</a>
            <span>›</span><span>Контакти</span>
          </div>
          <h2 className="h2" style={{ marginBottom: 8 }}>{formCfg.title || 'Замовити дзвінок'}</h2>
          <p style={{ fontSize: 16, color: 'rgba(255,255,255,0.7)', marginBottom: 28 }}>Залиште свої контакти — ми зв'яжемося протягом 1 робочого дня.</p>
          {ok ? (
            <div style={{ background: 'linear-gradient(135deg, #16a34a, #15803d)', color: '#fff', borderRadius: 16, padding: 40, textAlign: 'center' }}>
              <div style={{ fontSize: 40, marginBottom: 12 }}>✓</div>
              <div style={{ fontWeight: 700, fontSize: 20, marginBottom: 8 }}>{formCfg.successTitle || 'Заявку отримано!'}</div>
              <div style={{ opacity: 0.9 }}>{formCfg.successMessage || 'Зв\'яжемося найближчим часом.'}</div>
            </div>
          ) : (
            <form onSubmit={submit}>
              <div className="fg">
                <label className="fl">{formCfg.nameLabel || "Ім'я та прізвище *"}</label>
                <input className="fi" placeholder={formCfg.namePlaceholder || ''} required value={form.name} onChange={e => setForm(f => ({ ...f, name: e.target.value }))} />
              </div>
              <div className="fg">
                <label className="fl">{formCfg.phoneLabel || "Номер для зв'язку *"}</label>
                <input className="fi" placeholder={formCfg.phonePlaceholder || ''} required value={form.phone} onChange={e => setForm(f => ({ ...f, phone: e.target.value }))} />
              </div>
              <div className="fg">
                <label className="fl">{formCfg.emailLabel || 'Email (необов\'язково)'}</label>
                <input className="fi" type="email" placeholder={formCfg.emailPlaceholder || 'you@example.com'} value={form.email} onChange={e => setForm(f => ({ ...f, email: e.target.value }))} />
              </div>

              <div className="fg">
                <label className="fl">{formCfg.channelLabel || 'Куди вам зручніше отримати відповідь?'}</label>
                <div className="channel-grid">
                  {channels.map(ch => (
                    <div key={ch.id} className={`channel-card ${form.channel === ch.id ? 'active' : ''}`} onClick={() => setForm(f => ({ ...f, channel: ch.id }))}>
                      <div className="ch-ico" style={{ background: ch.color || '#2563eb', color: '#fff' }}><Ico n={ch.icon || 'phone'} s={16} /></div>
                      <span>{ch.label}</span>
                    </div>
                  ))}
                </div>
              </div>

              <div className="fg">
                <label className="fl">{formCfg.courseLabel || 'Програма навчання (необов\'язково)'}</label>
                <select className="fsel" value={form.course} onChange={e => setForm(f => ({ ...f, course: e.target.value }))}>
                  <option value="">{formCfg.coursePlaceholder || 'Оберіть програму...'}</option>
                  {services.map(s => <option key={s.slug} value={s.slug}>{s.title} — старт {window.formatCourseDate(s.slug)}</option>)}
                  <option value="other">{formCfg.courseOtherLabel || 'Консультація / Інше'}</option>
                </select>
              </div>

              <div className="fg">
                <label className="fl">{formCfg.messageLabel || 'Повідомлення'}</label>
                <input className="fi" placeholder={formCfg.messagePlaceholder || ''} value={form.msg} onChange={e => setForm(f => ({ ...f, msg: e.target.value }))} />
              </div>

              {(
                <div className="fg">
                  <label className="fl">{formCfg.turnstileLabel || 'Підтвердіть, що ви не робот'}</label>
                  <div id="turnstile-container"></div>
                </div>
              )}

              {error && <p style={{ color: '#fca5a5', marginBottom: 10 }}>{error}</p>}

              <button type="submit" disabled={loading} className="btn btn-blue" style={{ width: '100%', justifyContent: 'center', padding: '15px' }}>
                {loading ? 'Надсилання...' : (formCfg.submitButton || 'Надіслати заявку')} <Ico n="send" s={16} />
              </button>
              <p style={{ fontSize: 12, color: 'rgba(255,255,255,0.55)', marginTop: 10, textAlign: 'center' }}>{formCfg.privacyNote || ''}</p>
            </form>
          )}
        </div>
      </div>
    </div>
  );
};

const DocumentsPage = ({ navigate }) => {
  const d = contentRoot().documents || {};
  const items = d.items || [];

  return (
    <>
      <PageTop navigate={navigate} crumbs={[{ label: 'Документи' }]} title={d.heroTitle || 'Офіційні документи та форми'} subtitle={d.heroSubtitle || ''} />

      <section style={{ padding: '48px 0 80px' }}>
        <div className="wrap">
          <div className="docs-grid">
            {items.map((doc, i) => (
              <div key={i} className="doc-card">
                <div className="doc-card-band" style={{ background: doc.color || '#2563eb' }}></div>
                <div className="doc-card-body">
                  <div className="doc-card-name">{doc.name}</div>
                  <div className="doc-card-desc">{doc.desc}</div>
                </div>
                <div className="doc-card-foot">
                  <a href={doc.file} download className="btn btn-blue btn-sm" style={{ width: '100%', justifyContent: 'center' }}>
                    Завантажити <Ico n="arrow" s={14} />
                  </a>
                </div>
              </div>
            ))}
          </div>

          <div style={{ marginTop: 48, background: 'rgba(255,255,255,0.05)', border: '1px solid rgba(255,255,255,0.1)', borderRadius: 16, padding: '28px 36px', display: 'flex', alignItems: 'center', gap: 32, flexWrap: 'wrap', backdropFilter: 'blur(8px)' }}>
            <div style={{ flex: 1, minWidth: 240 }}>
              <div style={{ fontFamily: "'Outfit',sans-serif", fontWeight: 700, fontSize: 17, marginBottom: 6, color: '#fff' }}>{d.helpTitle || 'Потрібен інший документ?'}</div>
              <p style={{ fontSize: 15, color: 'rgba(255,255,255,0.7)', lineHeight: 1.65 }}>{d.helpText || ''}</p>
            </div>
            <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
              <a href={contentRoot().header?.phoneHref || 'tel:+380672641041'} className="btn btn-outline"><Ico n="phone" s={16} /> {d.phoneButtonText || '+38 (067) 264-10-41'}</a>
              <button className="btn btn-blue" onClick={() => navigate('/contact')}>{d.contactButtonText || 'Написати нам'}</button>
            </div>
          </div>
        </div>
      </section>
    </>
  );
};

Object.assign(window, { AboutPage, ServicesPage, ServiceDetailPage, NewsDetailPage, ContactPage, DocumentsPage });
