/* Bilermen site - Home page */

function HomeHero({ navigate }) {
  return (
    <section className="hero" data-screen-label="Home - Hero">
      <div className="container hero-grid">
        <FadeIn>
          <Eyebrow>{t('hero.eyebrow')}</Eyebrow>
          <h1 className="display-xl hero-company-name">{t('hero.title')} <span className="hero-company-subtle">{t('hero.subtle')}</span></h1>
          <p className="hero-gateway">{t('hero.gateway')}</p>
          <p className="lede">{t('hero.lede')}</p>
          <div className="hero-actions" style={{ marginTop: 36 }}>
            <Button onClick={() => navigate('/contact')}>{t('hero.cta1')}</Button>
            <Button variant="secondary" onClick={() => navigate('/services')}>{t('hero.cta2')}</Button>
          </div>
          <div className="hero-meta">
            <div><strong>{t('hero.meta.founded')}</strong>{t('hero.meta.foundedValue')}</div>
            <div><strong>{t('hero.meta.mandates')}</strong>{t('hero.meta.mandatesValue')}</div>
            <div><strong>{t('hero.meta.practice')}</strong>{t('hero.meta.practiceValue')}</div>
          </div>
        </FadeIn>
        <FadeIn delay={120} className="hero-art-wrap">
          <div className="hero-art">
            <HeroArt />
          </div>
        </FadeIn>
      </div>
    </section>
  );
}

function HomeIntro({ navigate }) {
  const lang = window.SITE_LANG || 'en';
  const introImage = (window.SITE_DATA.INTRO && (window.SITE_DATA.INTRO['image_' + lang] || window.SITE_DATA.INTRO.image))
    || 'assets/intro.jpg';
  return (
    <section className="intro-band">
      <div className="container intro-grid-with-image">
        <FadeIn delay={60}>
          <div className="intro-image">
            <img src={introImage} alt="Bilermen office" loading="lazy" decoding="async" />
          </div>
        </FadeIn>
        <FadeIn delay={120}>
          <Eyebrow>{t('intro.eyebrow')}</Eyebrow>
          <h2 className="intro-heading">{t('intro.heading')}</h2>
          <p>{t('intro.body1')}</p>
          <p>{t('intro.body2')}</p>
          <TextLink onClick={() => navigate('/about')}>{t('intro.cta')}</TextLink>
        </FadeIn>
      </div>
    </section>
  );
}

function HomeServices({ navigate }) {
  const services = window.SITE_DATA.SERVICES;
  const lang = window.SITE_LANG || 'en';
  return (
    <section className="section section-soft">
      <div className="container">
        <FadeIn>
          <div className="section-title">
            <Eyebrow>{t('services.eyebrow')}</Eyebrow>
            <h2 className="display-lg">{t('services.title')}</h2>
            <p>{t('services.lede')}</p>
          </div>
        </FadeIn>
        <div className="services-grid-pro">
          {services.map((s, i) => {
            const title = s['title_' + lang] || s.title;
            const short = s['short_' + lang] || s.short;
            const img = s['image_' + lang] || s.image;
            return (
              <FadeIn key={s.slug} delay={i * 80}>
                <div className="service-pro-card" onClick={() => navigate('/services/' + s.slug)}>
                  <div className="service-pro-header" style={{ position: 'relative', overflow: 'hidden', minHeight: '180px' }}>
                    {img && <img src={img} alt="" loading="lazy" decoding="async" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover' }} />}
                    <div className="service-pro-overlay" style={{ position: 'absolute', inset: 0, background: `linear-gradient(135deg, rgba(0,109,119,0.9), rgba(14,139,149,0.9))`, opacity: 0, transition: 'opacity 0.3s ease' }}></div>
                  </div>
                  <div className="service-pro-body" style={{ padding: '24px 32px 32px' }}>
                    <div className="service-pro-num" style={{ font: '700 12px/1 var(--font-sans)', letterSpacing: '2px', color: 'var(--color-primary)', marginBottom: '8px' }}>{s.no}</div>
                    <h3 className="service-pro-title" style={{ fontFamily: 'var(--font-serif)', fontSize: '22px', color: 'var(--color-ink)', margin: '0 0 12px' }}>{fmtAmp(title)}</h3>
                    <p>{short}</p>
                    <div className="service-pro-cta">{t('services.cta')} <span>&rarr;</span></div>
                  </div>
                </div>
              </FadeIn>
            );
          })}
        </div>
        <FadeIn>
          <div style={{ marginTop: 40 }}>
            <TextLink onClick={() => navigate('/services')}>{t('services.allLink')}</TextLink>
          </div>
        </FadeIn>
      </div>
    </section>
  );
}

function HomeSectors({ navigate }) {
  const sectors = window.SITE_DATA.SECTORS;
  const lang = window.SITE_LANG || 'en';
  return (
    <section className="section">
      <div className="container">
        <FadeIn>
          <div className="section-title">
            <Eyebrow>{t('sectors.eyebrow')}</Eyebrow>
            <h2 className="display-lg">{t('sectors.title')}</h2>
          </div>
        </FadeIn>
        <div className="sector-grid">
          {sectors.map((s, i) => {
            const title = s['title_' + lang] || s.title;
            const tag = s['tag_' + lang] || s.tag;
            return (
              <FadeIn key={s.slug} delay={i * 80}>
                <div className="sector-card" onClick={() => navigate('/sectors/' + s.slug)}>
                  <SectorPhotoArt slug={s.slug} />
                  <div className="body">
                    <small>{tag}</small>
                    <h4>{fmtAmp(title)}</h4>
                  </div>
                </div>
              </FadeIn>
            );
          })}
        </div>
        <FadeIn>
          <div style={{ marginTop: 40 }}>
            <TextLink onClick={() => navigate('/sectors')}>{t('sectors.allLink')}</TextLink>
          </div>
        </FadeIn>
      </div>
    </section>
  );
}

function HomeNews({ navigate }) {
  const news = window.SITE_DATA.NEWS;
  const colors = ['#006D77', '#143038', '#3CB4B4'];
  const lang = window.SITE_LANG || 'en';
  const scrollRef = useRef(null);
  const [canPrev, setCanPrev] = useState(false);
  const [canNext, setCanNext] = useState(true);

  const updateButtons = () => {
    const el = scrollRef.current;
    if (!el) return;
    setCanPrev(el.scrollLeft > 4);
    setCanNext(el.scrollLeft + el.clientWidth < el.scrollWidth - 4);
  };

  useEffect(() => {
    const el = scrollRef.current;
    if (!el) return;
    updateButtons();
    el.addEventListener('scroll', updateButtons);
    window.addEventListener('resize', updateButtons);
    return () => {
      el.removeEventListener('scroll', updateButtons);
      window.removeEventListener('resize', updateButtons);
    };
  }, []);

  const scrollBy = (dir) => {
    if (!scrollRef.current) return;
    const card = scrollRef.current.querySelector('.news-teaser-card');
    const step = card ? card.offsetWidth + 28 : 360;
    scrollRef.current.scrollBy({ left: dir * step, behavior: 'smooth' });
  };
  const dateLocale = lang === 'ru' ? 'ru-RU' : 'en-US';
  return (
    <section className="section section-soft home-news">
      <div className="container">
        <FadeIn>
          <div className="section-title">
            <Eyebrow>{t('news.eyebrow')}</Eyebrow>
            <h2 className="display-lg">{fmtAmp(t('news.title'))}</h2>
            <p>{t('news.lede')}</p>
          </div>
        </FadeIn>
        <div className="home-news-scroll-wrap">
          {canPrev && (
            <button className="news-side-btn news-side-btn-left" onClick={() => scrollBy(-1)} aria-label="Previous">←</button>
          )}
          {canNext && (
            <button className="news-side-btn news-side-btn-right" onClick={() => scrollBy(1)} aria-label="Next">→</button>
          )}
          <div className="home-news-scroll" ref={scrollRef}>
            {news.map((n, i) => {
              const title = n['title_' + lang] || n.title;
              const dek = n['dek_' + lang] || n.dek;
              const category = n['category_' + lang] || n.category;
              return (
                <article key={n.slug} className="news-teaser-card" onClick={() => navigate('/news/' + n.slug)}>
                  {n.image ? (
                    <div className="news-teaser-cover news-teaser-cover-img">
                      <img src={n.image} alt={title} loading="lazy" decoding="async" />
                      <div className="news-teaser-tag">{category}</div>
                    </div>
                  ) : (
                    <div className="news-teaser-cover" style={{ background: `linear-gradient(135deg, ${colors[i % colors.length]}, ${colors[(i+1) % colors.length]})` }}>
                      <div className="news-teaser-cover-pattern"></div>
                      <div className="news-teaser-tag">{category}</div>
                    </div>
                  )}
                  <div className="news-teaser-body">
                    <div className="news-teaser-date">{new Date(n.date).toLocaleDateString(dateLocale, { year: 'numeric', month: 'long' })}</div>
                    <h4 className="news-teaser-title">{fmtAmp(title)}</h4>
                    <p className="news-teaser-dek">{dek}</p>
                    <span className="news-teaser-link">{t('news.readMore')} →</span>
                  </div>
                </article>
              );
            })}
          </div>
        </div>
      </div>
    </section>
  );
}

function HomeContact({ navigate }) {
  const [submitted, setSubmitted] = useState(false);
  const [sending, setSending] = useState(false);
  const [err, setErr] = useState('');
  async function onSubmit(e) {
    e.preventDefault();
    if (sending) return;
    const form = e.target;
    /* Honeypot - bots fill the hidden field; real visitors never see it. */
    if (form.elements['company_url'] && form.elements['company_url'].value) {
      setSubmitted(true); form.reset(); return;
    }
    const payload = {
      name: (form.elements['name'].value || '').trim(),
      company: (form.elements['company'].value || '').trim() || '-',
      website: (form.elements['website'].value || '').trim() || '-',
      email: (form.elements['email'].value || '').trim(),
      message: (form.elements['message'].value || '').trim(),
    };
    setSending(true); setErr('');
    try {
      const resp = await fetch('https://api.web3forms.com/submit', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
        body: JSON.stringify({
          access_key: 'be81c5cd-0fd6-4a26-b265-e4ac70066110',
          subject: 'New Briefing Request from ' + payload.name,
          from_name: 'Bilermen Website',
          replyto: payload.email,
          message: `Name: ${payload.name}\nEmail: ${payload.email}\nCompany: ${payload.company}\nWebsite: ${payload.website}\n\nMessage:\n${payload.message}`
        })
      });
      const result = await resp.json().catch(() => ({}));
      if (!resp.ok || result.success === false) throw new Error('submit failed');
      form.reset();
      setSubmitted(true);
      setTimeout(() => setSubmitted(false), 4000);
    } catch (e2) {
      setErr((window.SITE_LANG === 'ru')
        ? 'Не удалось отправить. Напишите нам напрямую: info@bilermen-partners.com'
        : 'Could not send. Please email us directly at info@bilermen-partners.com');
    } finally {
      setSending(false);
    }
  }
  return (
    <section className="section home-contact">
      <div className="container home-contact-grid">
        <FadeIn>
          <Eyebrow>{t('contact.eyebrow')}</Eyebrow>
          <h2 className="display-lg" style={{ marginTop: 16 }}>{t('contact.title')}</h2>
          <p className="home-contact-lede">{t('contact.lede')}</p>
          <div className="home-contact-info">
            <a className="contact-info-row contact-info-link" href="tel:+99365812893">
              <div className="contact-info-icon">📞</div>
              <div>
                <div className="contact-info-label">{t('contact.phone')}</div>
                <div className="contact-info-value">+993 65 812893 / +993 65 368068</div>
              </div>
            </a>
            <a className="contact-info-row contact-info-link" href="mailto:info@bilermen-partners.com">
              <div className="contact-info-icon">✉</div>
              <div>
                <div className="contact-info-label">{t('contact.email')}</div>
                <div className="contact-info-value">info@bilermen-partners.com</div>
              </div>
            </a>
            <a className="contact-info-row contact-info-link"
               href="https://www.google.com/maps/search/?api=1&query=1908+st+Gundogar+6/2+Ashgabat+Turkmenistan"
               target="_blank" rel="noopener noreferrer">
              <div className="contact-info-icon">📍</div>
              <div>
                <div className="contact-info-label">{t('contact.address')}</div>
                <div className="contact-info-value">{t('contact.addressValue')}</div>
              </div>
            </a>
            <a className="contact-linkedin" href="https://www.linkedin.com/company/107719939" target="_blank" rel="noopener noreferrer">
              <span className="contact-linkedin-icon">in</span>
              <span>{t('contact.linkedin')}</span>
            </a>
          </div>
        </FadeIn>
        <FadeIn delay={120}>
          <form className="home-contact-form" onSubmit={onSubmit}>
            <h3>{t('contact.formTitle')}</h3>
            <input type="text" name="name" placeholder={t('contact.form.namePh')} required />
            <input type="text" name="company" placeholder={t('contact.form.companyPh')} />
            <input type="url" name="website" placeholder={t('contact.form.websitePh')} />
            <input type="email" name="email" placeholder={t('contact.form.emailPh')} required />
            <textarea name="message" placeholder={t('contact.form.scopePh')} rows="5" required></textarea>
            <input type="text" name="company_url" tabIndex="-1" autoComplete="off" aria-hidden="true"
                   style={{ position: 'absolute', left: '-9999px', width: 1, height: 1, opacity: 0 }} />
            {err && <div style={{ color: 'var(--color-error)', font: '500 13px/1.5 var(--font-sans)' }}>{err}</div>}
            <Button type="submit">{sending ? '…' : (submitted ? t('contact.form.sent') : t('contact.form.send') + ' →')}</Button>
          </form>
        </FadeIn>
      </div>
    </section>
  );
}

function HomeScreen({ navigate }) {
  return (
    <>
      <HomeHero navigate={navigate} />
      <HomeIntro navigate={navigate} />
      <HomeServices navigate={navigate} />
      <HomeSectors navigate={navigate} />
      <LogoCarousel />
      <HomeNews navigate={navigate} />
      <HomeContact navigate={navigate} />
    </>
  );
}

window.HomeScreen = HomeScreen;
