const { useState, useEffect } = React;

function getContent() {
  return window.CONTENT || {};
}

function getServices() {
  return (getContent().services || []);
}

function newsPath(item, index) {
  return `/news/${encodeURIComponent(item.slug || `news-${index + 1}`)}`;
}

function linkedService(item) {
  return getServices().find(s => s.slug && s.slug === item.serviceSlug);
}

const NewsCarousel = ({ navigate }) => {
  const news = getContent().home?.news || {};
  const items = news.items?.length ? news.items : [
    {
      slug: 'new-groups',
      title: 'Відкрито набір на нові групи',
      description: 'Актуальні програми для фахівців транспортної галузі.',
      details: 'Оберіть напрям навчання, залиште заявку та отримайте консультацію щодо документів і графіку занять.',
    },
  ];
  const [active, setActive] = useState(0);
  const total = items.length;
  const current = items[Math.min(active, total - 1)] || items[0];
  const service = linkedService(current);

  useEffect(() => {
    if (active > total - 1) setActive(0);
  }, [active, total]);

  useEffect(() => {
    if (total < 2) return;
    const timer = setInterval(() => {
      setActive(i => (i + 1) % total);
    }, 6500);
    return () => clearInterval(timer);
  }, [total]);

  const goTo = index => setActive((index + total) % total);

  return (
    <section className="news-section">
      <div className="wrap">
        <div className="news-head">
          <div>
            {/* <div className="label">{news.label || 'Новини'}</div> */}
            <h2 className="h2">{news.title || 'Актуальне у центрі'}</h2>
          </div>
          {/* <p>{news.subtitle || 'Останні оновлення, анонси та важлива інформація для слухачів.'}</p> */}
        </div>

        <div className="news-carousel">
          <button className="news-arrow news-prev" onClick={() => goTo(active - 1)} aria-label="Попередня новина">
            <Ico n="arrow" s={20} />
          </button>
          <article className="news-feature" role="link" tabIndex="0" onClick={() => navigate(newsPath(current, active))} onKeyDown={e => { if (e.key === 'Enter') navigate(newsPath(current, active)); }}>
            <div className="news-kicker">0{active + 1} / {String(total).padStart(2, '0')}</div>
            <h3>{current.title || ''}</h3>
            <p className="news-desc">{current.description || ''}</p>
            <p className="news-details">{current.details || ''}</p>
            <div className="news-actions">
              <button className="btn btn-blue news-more" onClick={e => { e.stopPropagation(); navigate(newsPath(current, active)); }}>
                Детальніше <Ico n="arrow" s={16} />
              </button>
              {service && (
                <button className="btn btn-outline news-more" onClick={e => { e.stopPropagation(); navigate(`/service/${service.slug}`); }}>
                  Перейти до {service.title} <Ico n="arrow" s={16} />
                </button>
              )}
            </div>
          </article>
          <button className="news-arrow news-next" onClick={() => goTo(active + 1)} aria-label="Наступна новина">
            <Ico n="arrow" s={20} />
          </button>
        </div>

        {/* <div className="news-tabs" role="tablist" aria-label="Список новин">
          {items.map((item, i) => (
            <button
              key={i}
              className={`news-tab ${active === i ? 'active' : ''}`}
              onClick={() => goTo(i)}
              role="tab"
              aria-selected={active === i}
            >
              <span>{String(i + 1).padStart(2, '0')}</span>
              {item.title || 'Новина'}
            </button>
          ))}
        </div> */}
      </div>
    </section>
  );
};

const FAQBlock = () => {
  const [open, setOpen] = useState(null);
  const faq = getContent().home?.faq || {};
  const items = faq.items || [];
  return (
    <section className="sec" style={{ background: 'var(--off-white)' }}>
      <div className="wrap">
        <div className="sec-head c">
          <div className="label">{faq.label || 'Запитання'}</div>
          <h2 className="h2">{faq.title || 'Часті запитання'}</h2>
        </div>
        <div className="faq-wrap">
          {items.map((item, i) => (
            <div key={i} className="faq-item">
              <button className={`faq-q ${open === i ? 'open' : ''}`} onClick={() => setOpen(open === i ? null : i)}>
                {item.q}<Ico n="chevron" s={20} />
              </button>
              <div className={`faq-a ${open === i ? 'open' : ''}`}>{item.a}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
};

const TestiBlock = () => {
  const t = getContent().home?.testimonials || {};
  const items = t.items || [];
  return (
    <section className="sec">
      <div className="wrap">
        <div className="sec-head c">
          <div className="label">{t.label || 'Відгуки'}</div>
          <h2 className="h2">{t.title || 'Що кажуть випускники'}</h2>
        </div>
        <div className="testi-grid">
          {items.map((it, i) => (
            <div key={i} className="testi-card">
              <div className="testi-stars">★★★★★</div>
              <p className="testi-text">«{it.text || ''}»</p>
              <div className="testi-auth">
                <div className="tav">{it.initials || ''}</div>
                <div>
                  <div className="tav-name">{it.name || ''}</div>
                  <div className="tav-role">{it.role || ''}</div>
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
};

const HomePage = ({ navigate }) => {
  const c = getContent();
  const h = c.home?.hero || {};
  const adv = c.home?.advantages || {};
  const process = c.home?.process || {};
  const cta2 = c.home?.cta2 || {};
  const services = getServices();

  return (
    <>
      <section className="home-hero">
        <div className="wrap">
          <div className="home-hero-grid">
            <div>
              {/* <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8, background: 'var(--blue-bg)', border: '1px solid rgba(37,99,235,0.2)', padding: '6px 14px', borderRadius: 20, marginBottom: 28 }}>
                <span style={{ width: 8, height: 8, borderRadius: '50%', background: 'var(--green)', display: 'inline-block' }}></span>
                <span style={{ fontFamily: "'Outfit',sans-serif", fontSize: 13, fontWeight: 700, color: 'var(--blue)' }}>{h.label || 'Офіційне підвищення кваліфікації'}</span>
              </div> */}
              <h1 className="display" style={{ color: 'var(--navy)', marginBottom: 24 }}>
                {h.title || 'Навчайтесь.'}<br />
                <span style={{ color: 'var(--blue)' }}>{h.titleSuffix || 'Зростайте.'}</span><br />
                {h.titleHighlight || 'Досягайте.'}
              </h1>
              <p style={{ fontSize: 18, color: 'var(--muted)', lineHeight: 1.75, marginBottom: 36, maxWidth: 520 }}>
                {h.subtitle || ''}
              </p>
              <div style={{ display: 'flex', gap: 14, flexWrap: 'wrap', marginBottom: 40 }}>
                <button className="btn btn-blue btn-lg" onClick={() => navigate('/services')}>
                  {h.ctaPrimary || 'Обрати програму'} <Ico n="arrow" s={18} />
                </button>
                <button className="btn btn-outline btn-lg" onClick={() => navigate('/contact')}>
                  {h.ctaSecondary || 'Консультація'}
                </button>
              </div>
              {/* <div style={{ display: 'flex', gap: 28, flexWrap: 'wrap', paddingTop: 24, borderTop: '1px solid var(--border)' }}>
                {(h.trustItems || []).map((txt, i) => (
                  <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <div style={{ width: 8, height: 8, borderRadius: '50%', background: i === 1 ? 'var(--blue)' : i === 2 ? 'var(--amber)' : 'var(--green)' }}></div>
                    <span style={{ fontFamily: "'Outfit',sans-serif", fontSize: 14, fontWeight: 600, color: 'var(--muted)' }}>{txt}</span>
                  </div>
                ))}
              </div> */}
            </div>

            <div>
              <div style={{ fontFamily: "'Outfit',sans-serif", fontSize: 12, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 2, color: 'var(--muted)', marginBottom: 14 }}>
                {h.watermark || 'Наші програми навчання'}
              </div>
              <div className="course-tiles">
                {services.map(s => (
                  <div key={s.slug} className="course-tile" style={{ background: s.colorBg, borderColor: (s.color || '#2563eb') + '30' }} onClick={() => navigate(`/service/${s.slug}`)}>
                    <div className="ct-icon" style={{ background: (s.color || '#2563eb') + '20' }}>
                      <span style={{ color: s.color || '#2563eb' }}><Ico n={s.icon || 'book'} s={18} /></span>
                    </div>
                    <div>
                      <div className="ct-name">{s.title}</div>
                      <div style={{ fontFamily: "'Outfit',sans-serif", fontSize: 10, fontWeight: 700, color: '#16a34a', marginTop: 4, letterSpacing: 0.3 }}>
                        Старт: {window.formatCourseDate(s.slug, { short: true })}
                      </div>
                      {s.isNew && <span style={{ fontFamily: "'Outfit',sans-serif", fontSize: 10, fontWeight: 800, background: 'var(--amber)', color: '#fff', padding: '1px 6px', borderRadius: 6, display: 'inline-block', marginTop: 4, letterSpacing: 0.5 }}>НОВЕ</span>}
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>
      </section>

      <NewsCarousel navigate={navigate} />

      <section className="sec">
        <div className="wrap">
          <div className="sec-head c" style={{ marginBottom: 56 }}>
            {/* <div className="label">{adv.label || 'Переваги'}</div> */}
            <h2 className="h2">{adv.title || 'Чому обирають ЦРПК'}</h2>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 24 }}>
            {(adv.items || []).map((item, i) => (
              <div key={i} style={{
                padding: '40px 36px',
                background: 'rgba(255,255,255,0.04)',
                border: '1px solid rgba(255,255,255,0.1)',
                borderRadius: 20,
                backdropFilter: 'blur(8px)',
                display: 'flex',
                gap: 28,
                alignItems: 'flex-start',
              }}>
                <div style={{
                  width: 64, height: 64, borderRadius: 16, flexShrink: 0,
                  background: 'linear-gradient(135deg, rgba(37,99,235,0.25), rgba(37,99,235,0.1))',
                  border: '1px solid rgba(147,197,253,0.35)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  color: '#93c5fd',
                }}>
                  <Ico n={item.icon || 'award'} s={28} />
                </div>
                <div style={{ flex: 1 }}>
                  {/* <div style={{ fontFamily: "'Outfit',sans-serif", fontSize: 11, fontWeight: 800, letterSpacing: 2.5, color: 'rgba(255,255,255,0.4)', marginBottom: 8 }}>
                    {String(i + 1).padStart(2, '0')}
                  </div> */}
                  <h3 className="h3" style={{ marginBottom: 12, color: '#fff' }}>{item.title || ''}</h3>
                  <p style={{ fontSize: 15.5, color: 'rgba(255,255,255,0.72)', lineHeight: 1.7 }}>{item.desc || ''}</p>
                </div>
              </div>
            ))}
          </div>
        </div>
      </section>

      <section className="sec" style={{ background: 'var(--navy)' }}>
        <div className="wrap">
          <div className="sec-head c">
            <div className="label green">{process.label || 'Як це працює'}</div>
            <h2 className="h2" style={{ color: '#fff' }}>{process.title || 'Три кроки до свідоцтва'}</h2>
          </div>
          <div className="process-grid">
            {(process.items || []).map((s, idx) => (
              <div key={idx} className="proc-item">
                <div className="proc-num">{idx + 1}</div>
                <h4 className="h3" style={{ marginBottom: 10, color: '#fff' }}>{s.title || ''}</h4>
                <p style={{ fontSize: 15, color: 'rgba(255,255,255,0.55)', lineHeight: 1.65 }}>{s.desc || ''}</p>
              </div>
            ))}
          </div>
        </div>
      </section>

      <TestiBlock />
      <FAQBlock />

      <section style={{ background: 'var(--blue)', padding: '56px 0', textAlign: 'center' }}>
        <div className="wrap">
          <h2 className="h2" style={{ color: '#fff', marginBottom: 12 }}>{cta2.title || 'Готові підвищити кваліфікацію?'}</h2>
          <p style={{ fontSize: 17, color: 'rgba(255,255,255,0.75)', margin: '0 auto 28px', maxWidth: 460 }}>
            {cta2.subtitle || ''}
          </p>
          <div style={{ display: 'flex', gap: 14, justifyContent: 'center', flexWrap: 'wrap' }}>
            <button className="btn btn-white btn-lg" onClick={() => navigate('/contact')}>{cta2.ctaPrimary || 'Залишити заявку'}</button>
            <button className="btn btn-ghost btn-lg" onClick={() => navigate('/services')}>{cta2.ctaSecondary || 'Переглянути програми'}</button>
          </div>
        </div>
      </section>
    </>
  );
};

Object.assign(window, { HomePage, NewsCarousel, TestiBlock, FAQBlock });
