// Variant 4 — Soft Sky / Cloud Light
const { useState, useMemo, useEffect } = React;
function getFILMS() { return window.ALLIANCE_DATA.FILMS; }
function t(path, lang) { return window.ALLIANCE_DATA.t(path, lang); }
let FILMS = window.ALLIANCE_DATA.FILMS;

function stockLbl(s, lang) {
  if (s === 'high') return t('catalog.stockHigh', lang);
  if (s === 'medium') return t('catalog.stockMed', lang);
  return t('catalog.stockLow', lang);
}

function PageGallery({ pageName, lang }) {
  const [images, setImages] = useState(() => (window.ALLIANCE_DATA.PAGE_IMAGES[pageName] || []).slice());
  useEffect(() => {
    function onUpdate() { setImages((window.ALLIANCE_DATA.PAGE_IMAGES[pageName] || []).slice()); }
    window.addEventListener('alliance-data-updated', onUpdate);
    return () => window.removeEventListener('alliance-data-updated', onUpdate);
  }, [pageName]);
  if (!images.length) return null;
  return (
    <div className="v4-page-gallery">
      <div className="v4-gallery-grid">
        {images.map((img, i) => (
          <div key={i} className="v4-gallery-item">
            <img src={img.src} alt={img.caption ? (img.caption[lang] || '') : ''} />
            {img.caption && img.caption[lang] && <div className="v4-gallery-caption">{img.caption[lang]}</div>}
          </div>
        ))}
      </div>
    </div>
  );
}

function Header({ page, setPage, lang, setLang }) {
  const nav = [['home','nav.home'],['catalog','nav.catalog'],['about','nav.about'],['production','nav.production'],['careers','nav.careers'],['contacts','nav.contacts']];
  return (
    <header className="v4-header">
      <div className="v4-header-inner">
        <a className="v4-logo" onClick={() => setPage('home')}>
          <svg className="v4-logo-mark-svg" viewBox="0 0 44 44" aria-hidden="true">
            <defs>
              <linearGradient id="ai-roll" x1="0" y1="0" x2="1" y2="1">
                <stop offset="0%" stopColor="#9bc0e3" />
                <stop offset="100%" stopColor="#1c4670" />
              </linearGradient>
            </defs>
            <circle cx="22" cy="22" r="20" fill="url(#ai-roll)" />
            <circle cx="22" cy="22" r="14" fill="none" stroke="#fff" strokeOpacity="0.55" strokeWidth="1.3" />
            <circle cx="22" cy="22" r="8" fill="none" stroke="#fff" strokeOpacity="0.7" strokeWidth="1.3" />
            <circle cx="22" cy="22" r="3" fill="#fff" />
            <path d="M 36 14 Q 42 16 42 22" stroke="#fff" strokeWidth="1.6" fill="none" strokeLinecap="round" opacity="0.85" />
          </svg>
          <div className="v4-logo-text">
            <span className="v4-logo-name">
              {lang === 'ua'
                ? <>ТК Альянс Ідеал</>
                : <>TC Alliance Ideal</>}
            </span>
            <small>{lang === 'ua' ? 'Найкраща плівка для вашого пакування' : 'The best film for your packaging'}</small>
          </div>
        </a>
        <div className="v4-nav">
          {nav.map(([k, p]) => (
            <a key={k} className={page === k || (page === 'product' && k === 'catalog') ? 'active' : ''} onClick={() => setPage(k)}>{t(p, lang)}</a>
          ))}
        </div>
        <div className="v4-nav-right">
          <div className="v4-lang">
            <button className={lang === 'ua' ? 'active' : ''} onClick={() => setLang('ua')}>UA</button>
            <button className={lang === 'en' ? 'active' : ''} onClick={() => setLang('en')}>EN</button>
          </div>
          <button className="btn4 btn4-primary" onClick={() => setPage('contacts')}>{t('hero.cta2', lang)}</button>
        </div>
      </div>
    </header>
  );
}

function Hero({ lang, setPage }) {
  const [slides, setSlides] = useState(() => window.ALLIANCE_DATA.SLIDES.slice());
  const [idx, setIdx] = useState(0);
  useEffect(() => {
    function onUpdate() { setSlides(window.ALLIANCE_DATA.SLIDES.slice()); setIdx(0); }
    window.addEventListener('alliance-data-updated', onUpdate);
    return () => window.removeEventListener('alliance-data-updated', onUpdate);
  }, []);
  useEffect(() => {
    const id = setInterval(() => setIdx(i => (i + 1) % slides.length), 4500);
    return () => clearInterval(id);
  }, []);
  return (
    <section className="v4-hero">
      <div className="container">
        <div className="v4-hero-grid">
          <div>
            <div className="v4-pill"><span className="dot"></span>{lang === 'ua' ? 'Зі складу в Києві · день-у-день' : 'Ex-stock Kyiv · same day'}</div>
            <h1>{lang === 'ua' ? <>Плівки CPP, BOPP та PET <span className="accent">для гнучкої упаковки</span></> : <>CPP, BOPP & PET films <span className="accent">for flexible packaging</span></>}</h1>
            <p className="sub">{t('hero.sub', lang)}</p>
            <div className="v4-hero-actions">
              <button className="btn4 btn4-primary" onClick={() => setPage('catalog')}>{t('hero.cta1', lang)} →</button>
              <button className="btn4 btn4-ghost" onClick={() => setPage('contacts')}>{t('hero.cta2', lang)}</button>
            </div>
          </div>
          <div className="v4-hero-slideshow">
            {slides.map((s, i) => (
              <div key={i} className={'v4-slide' + (i === idx ? ' is-active' : '')}
                   style={{ backgroundImage: `url(${s.src})` }}>
                <div className="v4-slide-caption">{s.label[lang]}</div>
              </div>
            ))}
            <div className="v4-hero-card">
              <div className="icon-circle"></div>
              <div>
                <div className="t">{lang === 'ua' ? '35+ типів плівок' : '35+ film grades'}</div>
                <div className="s">{lang === 'ua' ? 'CPP · BOPP · PET · OPP у наявності' : 'CPP · BOPP · PET · OPP in stock'}</div>
              </div>
            </div>
            <div className="v4-slide-dots">
              {slides.map((_, i) => (
                <button key={i} className={i === idx ? 'is-active' : ''} onClick={() => setIdx(i)} aria-label={'Slide ' + (i + 1)}></button>
              ))}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function Stats({ lang }) {
  return (
    <section className="v4-stats">
      <div className="container">
        <div className="grid">
          {window.ALLIANCE_DATA.T.stats.map((s, i) => (
            <div className="v4-stat" key={i}>
              <div className="v">{s.v}</div>
              <div className="l">{s.l[lang]}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function Families({ lang, setPage, setFilter }) {
  const cpp = FILMS.filter(f => f.family === 'CPP');
  const bopp = FILMS.filter(f => f.family === 'BOPP');
  const opp = FILMS.filter(f => f.family === 'OPP');
  const pet = FILMS.filter(f => f.family === 'PET');
  const fams = [
    { k: 'CPP', code: 'CPP', cls: 'cpp',
      title: { ua: 'CPP · литий ПП', en: 'CPP · Cast PP' },
      lead: { ua: 'Еластична плівка з відмінною термозварюваністю. Внутрішній шар ламінатів.', en: 'Soft film with excellent heat-sealing. Inner laminate layer.' },
      films: cpp
    },
    { k: 'BOPP', code: 'BOPP', cls: 'bopp',
      title: { ua: 'BOPP · двовісно орієнтований ПП', en: 'BOPP · Biaxially Oriented PP' },
      lead: { ua: 'Жорстка прозора плівка для друку, snek-пакування та етикеток.', en: 'Stiff clear film for print, snack packaging and labels.' },
      films: bopp
    },
    { k: 'PET', code: 'PET', cls: 'pet',
      title: { ua: 'PET · поліестерова плівка', en: 'PET · Polyester film' },
      lead: { ua: 'Термостійка плівка з високою міцністю. Бар\'єр, фольгування, лотки.', en: 'Heat-stable, high-strength film. Barriers, foiling, trays.' },
      films: pet
    },
    { k: 'OPP', code: 'OPP', cls: 'opp',
      title: { ua: 'OPP · спеціальні плівки PP', en: 'OPP · specialty PP films' },
      lead: { ua: 'Монооріентовані та литі PP для тютюну, технічних застосувань.', en: 'Mono-oriented and cast PP for tobacco, technical uses.' },
      films: opp
    }
  ];
  return (
    <section className="v4-section">
      <div className="container">
        <div className="v4-section-head">
          <span className="eyebrow">{lang === 'ua' ? 'СІМЕЙСТВА ПЛІВОК' : 'FILM FAMILIES'}</span>
          <h2>{lang === 'ua' ? 'Чотири технології — повне покриття гнучкої упаковки' : 'Four technologies — complete coverage of flexible packaging'}</h2>
          <p>{lang === 'ua' ? 'CPP, BOPP, PET та OPP — кожна сімʼя під своє завдання. Разом 35+ грейдів у наявності та під замовлення.' : 'CPP, BOPP, PET and OPP — each family for its task. 35+ grades total, ex-stock or on order.'}</p>
        </div>
        <div className="v4-families">
          {fams.map(f => (
            <div className="v4-family" key={f.k} onClick={() => { setFilter(f.k); setPage('catalog'); }}>
              <div className={'v4-family-viz ' + f.cls} data-code={f.code}></div>
              <h3>{f.title[lang]}</h3>
              <div className="lead">{f.lead[lang]}</div>
              <div className="v4-family-grades">{f.films.map(x => <span className="v4-grade-pill" key={x.id}>{x.code}</span>)}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function Advantages({ lang }) {
  const items = window.ALLIANCE_DATA.T.advantages.items;
  return (
    <section className="v4-advantages">
      <div className="container">
        <div className="v4-section-head">
          <span className="eyebrow">{lang === 'ua' ? 'ЧОМУ МИ' : 'WHY US'}</span>
          <h2>{t('advantages.title', lang)}</h2>
        </div>
        <div className="v4-adv-grid">
          {items.map((a, i) => (
            <div className="v4-adv" key={i}>
              <div className="v4-adv-num">0{i + 1}</div>
              <h3>{a.t[lang]}</h3>
              <p>{a.d[lang]}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function CatalogPage({ lang, setPage, setProduct, filter, setFilter }) {
  const [q, setQ] = useState('');
  const list = useMemo(() => FILMS.filter(f => {
    if (filter !== 'all' && f.family !== filter) return false;
    if (q) {
      const lq = q.toLowerCase();
      if (!f.name[lang].toLowerCase().includes(lq) && !f.code.toLowerCase().includes(lq)) return false;
    }
    return true;
  }), [filter, q, lang]);
  return (
    <>
      <div className="v4-cat-head">
        <div className="container">
          <span className="eyebrow" style={{display:'inline-block', marginBottom:14, fontSize:12, fontWeight:600, letterSpacing:'0.12em', color:'var(--sky-700)', textTransform:'uppercase'}}>{lang === 'ua' ? 'КАТАЛОГ' : 'CATALOG'}</span>
          <h1>{t('catalog.title', lang)}</h1>
          <p>{t('catalog.sub', lang)}</p>
        </div>
      </div>
      <div className="v4-cat-body">
        <div className="container">
          <div className="v4-filters">
            {['all', 'CPP', 'BOPP', 'OPP', 'PET'].map(k => (
              <button key={k} className={'v4-chip' + (filter === k ? ' active' : '')} onClick={() => setFilter(k)}>
                {k === 'all' ? t('catalog.all', lang) : k}
              </button>
            ))}
            <input className="v4-search" placeholder={t('catalog.search', lang)} value={q} onChange={e => setQ(e.target.value)} />
          </div>
          <div className="v4-grid">
            {list.map(f => (
              <div className="v4-card" key={f.id} onClick={() => { setProduct(f.id); setPage('product'); }}>
                <div className={'v4-card-viz v4-viz-' + f.code}>
                  <div className="v4-card-badges">
                    <span className="v4-card-fam">{f.family} · {f.code}</span>
                    <span className={'v4-card-stock ' + f.stock}>● {stockLbl(f.stock, lang)}</span>
                  </div>
                </div>
                <div className="v4-card-body">
                  <div className="code">{f.code}</div>
                  <h3>{f.name[lang]}</h3>
                  <div className="tag">{f.tagline[lang]}</div>
                  <div className="meta">
                    <span>{f.thickness}</span>
                    <span>{f.applications[lang].length} {lang === 'ua' ? 'застосувань' : 'uses'}</span>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </>
  );
}

function ProductPage({ lang, productId, setPage }) {
  const f = FILMS.find(x => x.id === productId) || FILMS[0];
  return (
    <section className="v4-product v4-prod">
      <div className="container">
        <a className="v4-back" onClick={() => setPage('catalog')}>← {t('catalog.back', lang)}</a>
        <div className="v4-prod-grid">
          <div className={'v4-prod-viz v4-viz-' + f.code}>
            <div className="badge">{f.family} · {f.code}</div>
          </div>
          <div>
            <div className="v4-prod-code">{f.code} · {f.family}</div>
            <h1>{f.name[lang]}</h1>
            <div className="v4-prod-tag">{f.tagline[lang]}</div>
            <div className="v4-prod-facts">
              <div className="v4-fact"><div className="k">{t('catalog.thickness', lang)}</div><div>{f.thickness}</div></div>
              <div className="v4-fact"><div className="k">{t('catalog.stock', lang)}</div><div>{stockLbl(f.stock, lang)}</div></div>
              <div className="v4-fact"><div className="k">{t('catalog.features', lang)}</div><div>{f.features[lang].map((x, i) => <span className="v4-tag-pill" key={i}>{x}</span>)}</div></div>
              <div className="v4-fact"><div className="k">{t('catalog.applications', lang)}</div><div>{f.applications[lang].map((x, i) => <span className="v4-tag-pill" key={i}>{x}</span>)}</div></div>
            </div>
            <div style={{display:'flex', gap: 10, marginTop: 28}}>
              <button className="btn4 btn4-primary" onClick={() => setPage('contacts')}>{t('catalog.request', lang)}</button>
              <button className="btn4 btn4-ghost" onClick={() => setPage('catalog')}>{t('catalog.back', lang)}</button>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function AboutPage({ lang }) {
  return (
    <section className="v4-about">
      <div className="container">
        <div className="v4-section-head">
          <span className="eyebrow">{lang === 'ua' ? 'ПРО НАС' : 'ABOUT'}</span>
          <h2>{t('about.title', lang)}</h2>
        </div>
        <div className="v4-about-grid">
          <p className="v4-about-lead">{t('about.lead', lang)}</p>
          <div>
            <p>{t('about.p1', lang)}</p>
            <p>{t('about.p2', lang)}</p>
          </div>
        </div>
        <PageGallery pageName="about" lang={lang} />
      </div>
    </section>
  );
}

function LogisticsPage({ lang }) {
  const steps = window.ALLIANCE_DATA.T.logistics.steps;
  return (
    <section className="v4-logistics">
      <div className="container">
        <div className="v4-section-head">
          <span className="eyebrow">{lang === 'ua' ? 'ЛОГІСТИКА' : 'LOGISTICS'}</span>
          <h2>{t('logistics.title', lang)}</h2>
        </div>
        <div className="v4-steps">
          {steps.map((s, i) => (
            <div className="v4-step" key={i}>
              <div className="num">{String(i + 1).padStart(2, '0')}</div>
              <h3>{s.t[lang]}</h3>
              <p>{s.d[lang]}</p>
            </div>
          ))}
        </div>
        <PageGallery pageName="logistics" lang={lang} />
      </div>
    </section>
  );
}

function ProductionPage({ lang, setPage }) {
  const P = window.ALLIANCE_DATA.T.production;
  return (
    <section className="v4-production">
      <div className="container">
        <div className="v4-section-head">
          <span className="eyebrow">{lang === 'ua' ? 'ВИРОБНИЦТВО ТА ПОСТАЧАННЯ' : 'PRODUCTION & SUPPLY'}</span>
          <h2>{P.title[lang]}</h2>
          <p>{P.sub[lang]}</p>
        </div>

        <div className="v4-prod-cap">
          {P.capacity.map((c, i) => (
            <div className="v4-prod-cap-cell" key={i}>
              <div className="v">{c.v}<small> {c.u[lang]}</small></div>
              <div className="l">{c.l[lang]}</div>
            </div>
          ))}
        </div>

        <div className="v4-prod-block">
          <div className="v4-prod-block-head">
            <h3>{P.ourTitle[lang]}</h3>
            <p>{P.ourSub[lang]}</p>
          </div>
          <div className="v4-prod-services">
            {P.services.map((s, i) => (
              <div className="v4-prod-service" key={i}>
                <div className="v4-prod-svc-num">0{i + 1}</div>
                <h4>{s.t[lang]}</h4>
                <p>{s.d[lang]}</p>
                <div className="v4-prod-svc-stat">
                  <strong>{s.stat}</strong>
                  <span>{s.statLabel[lang]}</span>
                </div>
              </div>
            ))}
          </div>
        </div>

        <div className="v4-prod-block">
          <div className="v4-prod-block-head">
            <h3>{P.processTitle[lang]}</h3>
            <p>{P.processSub[lang]}</p>
          </div>
          <div className="v4-prod-steps">
            {P.steps.map((s, i) => (
              <div className="v4-prod-step" key={i}>
                <div className="num">{String(i + 1).padStart(2, '0')}</div>
                <h4>{s.t[lang]}</h4>
                <p>{s.d[lang]}</p>
              </div>
            ))}
          </div>
        </div>

        <div className="v4-prod-block">
          <div className="v4-prod-block-head">
            <h3>{P.partnersTitle[lang]}</h3>
            <p>{P.partnersSub[lang]}</p>
          </div>
          <div className="v4-prod-partners">
            {P.partners.map((p, i) => (
              <div className="v4-prod-partner" key={i}>
                <div className="v4-prod-partner-country">{p.country[lang]}</div>
                <div className="v4-prod-partner-spec">{p.spec[lang]}</div>
              </div>
            ))}
          </div>
        </div>

        <PageGallery pageName="production" lang={lang} />

        <div className="v4-prod-cta">
          <h3>{lang === 'ua' ? 'Замовте порізку або зразок плівки' : 'Order slitting or a film sample'}</h3>
          <p>{lang === 'ua' ? 'Надішліть ТЗ — менеджер запропонує найкращий грейд та підготує комерційну.' : 'Send your spec — our manager will suggest the best grade and prepare a quote.'}</p>
          <button className="btn4 btn4-primary" onClick={() => setPage('contacts')}>{lang === 'ua' ? 'Звʼязатися →' : 'Get in touch →'}</button>
        </div>
      </div>
    </section>
  );
}

function CareersPage({ lang, setPage }) {
  const T = window.ALLIANCE_DATA.T;
  const careers = T.careers;
  const jobs = careers.jobs || [];
  const labels = careers.labels;
  const [selected, setSelected] = useState(null);
  const [filter, setFilter] = useState('all');
  const [sent, setSent] = useState(false);
  const [position, setPosition] = useState('');

  const depts = useMemo(() => {
    const set = new Set(jobs.map(j => j.dept[lang]));
    return ['all', ...Array.from(set)];
  }, [jobs, lang]);

  const filtered = useMemo(() => {
    if (filter === 'all') return jobs;
    return jobs.filter(j => j.dept[lang] === filter);
  }, [jobs, filter, lang]);

  function openJob(j) {
    setSelected(j);
    setPosition(j.title[lang]);
    window.scrollTo(0, 0);
  }
  function applyTo(j) {
    setPosition(j ? j.title[lang] : '');
    setSelected(null);
    setTimeout(() => {
      const el = document.getElementById('careers-apply');
      if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }, 50);
  }

  if (selected) {
    return (
      <section className="v4-careers v4-job">
        <div className="container">
          <a className="v4-back" onClick={() => setSelected(null)}>{labels.back[lang]}</a>
          <div className="v4-job-head">
            <span className="v4-job-dept">{selected.dept[lang]}</span>
            <h1>{selected.title[lang]}</h1>
            <p className="v4-job-summary">{selected.summary[lang]}</p>
            <div className="v4-job-meta">
              <div><span>{labels.location[lang]}</span><strong>{selected.location[lang]}</strong></div>
              <div><span>{labels.type[lang]}</span><strong>{selected.type[lang]}</strong></div>
              <div><span>{labels.salary[lang]}</span><strong>{selected.salary[lang]}</strong></div>
              <div><span>{labels.published[lang]}</span><strong>{selected.published}</strong></div>
            </div>
            <button className="btn4 btn4-primary" onClick={() => applyTo(selected)}>{labels.apply[lang]} →</button>
          </div>
          <div className="v4-job-cols">
            <div className="v4-job-block">
              <h3>{labels.responsibilities[lang]}</h3>
              <ul>{selected.responsibilities[lang].map((r, i) => <li key={i}>{r}</li>)}</ul>
            </div>
            <div className="v4-job-block">
              <h3>{labels.requirements[lang]}</h3>
              <ul>{selected.requirements[lang].map((r, i) => <li key={i}>{r}</li>)}</ul>
            </div>
          </div>
        </div>
      </section>
    );
  }

  return (
    <section className="v4-careers">
      <div className="container">
        <div className="v4-section-head">
          <span className="eyebrow">{lang === 'ua' ? 'РОБОТА В КОМАНДІ' : 'WORK WITH US'}</span>
          <h2>{careers.title[lang]}</h2>
          <p>{careers.sub[lang]}</p>
        </div>

        <div className="v4-culture">
          {careers.culture.map((c, i) => (
            <div className="v4-culture-card" key={i}>
              <div className="v4-culture-num">0{i + 1}</div>
              <h3>{c.t[lang]}</h3>
              <p>{c.d[lang]}</p>
            </div>
          ))}
        </div>

        <div className="v4-jobs-head">
          <h3>{labels.open[lang]} <span>· {jobs.length}</span></h3>
          <div className="v4-jobs-filters">
            {depts.map(d => (
              <button
                key={d}
                className={'v4-chip' + (filter === d ? ' active' : '')}
                onClick={() => setFilter(d)}
              >
                {d === 'all' ? labels.all[lang] : d}
              </button>
            ))}
          </div>
        </div>

        <div className="v4-jobs-list">
          {filtered.map(j => (
            <div className="v4-job-row" key={j.id} onClick={() => openJob(j)}>
              <div className="v4-job-row-main">
                <span className="v4-job-row-dept">{j.dept[lang]}</span>
                <h4>{j.title[lang]}</h4>
                <p>{j.summary[lang]}</p>
              </div>
              <div className="v4-job-row-meta">
                <span>{j.location[lang]}</span>
                <span>{j.salary[lang]}</span>
              </div>
              <div className="v4-job-row-cta">
                <button className="btn4 btn4-soft">{labels.apply[lang]} →</button>
              </div>
            </div>
          ))}
        </div>

        <PageGallery pageName="careers" lang={lang} />

        <div className="v4-apply" id="careers-apply">
          <div className="v4-apply-info">
            <h3>{careers.applyTitle[lang]}</h3>
            <p>{careers.applySub[lang]}</p>
          </div>
          <form className="v4-form" onSubmit={e => { e.preventDefault(); setSent(true); }}>
            {sent && <div className="v4-sent">✓ {careers.form.sent[lang]}</div>}
            <div className="grid2">
              <div className="v4-field"><label>{careers.form.name[lang]}</label><input /></div>
              <div className="v4-field"><label>{careers.form.position[lang]}</label><input value={position} onChange={e => setPosition(e.target.value)} /></div>
            </div>
            <div className="grid2">
              <div className="v4-field"><label>{careers.form.phone[lang]}</label><input /></div>
              <div className="v4-field"><label>{careers.form.email[lang]}</label><input /></div>
            </div>
            <div className="v4-field"><label>{careers.form.cv[lang]}</label><input placeholder="https://" /></div>
            <div className="v4-field"><label>{careers.form.message[lang]}</label><textarea rows="3"></textarea></div>
            <button type="submit" className="btn4 btn4-primary">{careers.form.submit[lang]} →</button>
          </form>
        </div>
      </div>
    </section>
  );
}

function ContactsPage({ lang }) {
  const [fields, setFields] = useState({ company: '', name: '', phone: '', email: '', interest: '', message: '' });
  const [errors, setErrors] = useState({});
  const [sent, setSent]     = useState(false);
  const [sending, setSending] = useState(false);
  const [sendError, setSendError] = useState('');

  const set = k => e => setFields(f => ({ ...f, [k]: e.target.value }));

  const validate = () => {
    const e = {};
    if (!fields.name.trim())
      e.name = lang === 'ua' ? 'Введіть контактну особу' : 'Please enter contact name';
    if (!fields.phone.trim() && !fields.email.trim())
      e.phone = lang === 'ua' ? 'Вкажіть телефон або e-mail' : 'Enter phone or email';
    if (!fields.message.trim())
      e.message = lang === 'ua' ? 'Напишіть повідомлення' : 'Please enter your message';
    return e;
  };

  const handleSubmit = async e => {
    e.preventDefault();
    const errs = validate();
    setErrors(errs);
    if (Object.keys(errs).length) return;
    setSending(true);
    setSendError('');
    try {
      const res = await fetch('/api/contact.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(fields)
      });
      const json = await res.json();
      if (json.ok) {
        setSent(true);
      } else {
        setSendError(lang === 'ua' ? 'Помилка надсилання. Спробуйте пізніше.' : 'Send error. Please try later.');
      }
    } catch {
      setSendError(lang === 'ua' ? 'Помилка з\'єднання. Спробуйте пізніше.' : 'Connection error. Please try later.');
    } finally {
      setSending(false);
    }
  };

  const req = <span style={{color:'#e53e3e', marginLeft:2}}>*</span>;
  const err = k => errors[k] ? <span className="v4-field-error">{errors[k]}</span> : null;

  return (
    <section className="v4-contacts">
      <div className="container">
        <div className="v4-section-head">
          <span className="eyebrow">{lang === 'ua' ? 'КОНТАКТИ' : 'CONTACTS'}</span>
          <h2>{t('contacts.title', lang)}</h2>
          <p>{t('contacts.sub', lang)}</p>
        </div>
        <PageGallery pageName="contacts" lang={lang} />
        <div className="v4-ctx-grid">
          <div className="v4-ctx-card">
            <h3 style={{marginBottom: 16}}>{t('company.legal', lang)}</h3>
            <div className="v4-ctx-line"><div className="k">{lang === 'ua' ? 'Офіс' : 'Office'}</div><div>{t('contacts.office.addr', lang)}</div></div>
            <div className="v4-ctx-line"><div className="k">{lang === 'ua' ? 'Склад' : 'Warehouse'}</div><div>{t('contacts.office.warehouse', lang)}</div></div>
            <div className="v4-ctx-line"><div className="k">{lang === 'ua' ? 'Телефон' : 'Phone'}</div><div>{(window.ALLIANCE_DATA.COMPANY || {}).phone}</div></div>
            <div className="v4-ctx-line"><div className="k">Email</div><div>{(window.ALLIANCE_DATA.COMPANY || {}).email}</div></div>
            <div className="v4-ctx-line"><div className="k">{lang === 'ua' ? 'Години' : 'Hours'}</div><div>{t('contacts.office.hours', lang)}</div></div>
          </div>
          <form className="v4-form" onSubmit={handleSubmit} noValidate>
            {sent && <div className="v4-sent">✓ {t('contacts.form.sent', lang)}</div>}
            {sendError && <div className="v4-send-error">{sendError}</div>}
            {!sent && <>
              <div className="grid2">
                <div className="v4-field"><label>{t('contacts.form.company', lang)}</label><input value={fields.company} onChange={set('company')} /></div>
                <div className="v4-field"><label>{t('contacts.form.name', lang)}{req}</label><input value={fields.name} onChange={set('name')} className={errors.name ? 'v4-input-error' : ''} />{err('name')}</div>
              </div>
              <div className="grid2">
                <div className="v4-field"><label>{t('contacts.form.phone', lang)}{req}</label><input value={fields.phone} onChange={set('phone')} className={errors.phone ? 'v4-input-error' : ''} />{err('phone')}</div>
                <div className="v4-field"><label>{t('contacts.form.email', lang)}</label><input value={fields.email} onChange={set('email')} type="email" /></div>
              </div>
              <div className="v4-field"><label>{t('contacts.form.interest', lang)}</label>
                <select value={fields.interest} onChange={set('interest')}><option value="">—</option>{FILMS.map(f => <option key={f.id} value={f.code}>{f.code} — {f.name[lang]}</option>)}</select>
              </div>
              <div className="v4-field"><label>{t('contacts.form.message', lang)}{req}</label><textarea rows="3" value={fields.message} onChange={set('message')} className={errors.message ? 'v4-input-error' : ''}></textarea>{err('message')}</div>
              <div style={{fontSize:12, color:'#8497ad', marginBottom:8}}>{req} — {lang === 'ua' ? 'обов\'язкові поля' : 'required fields'}</div>
              <button type="submit" className="btn4 btn4-primary" disabled={sending}>{sending ? '...' : t('contacts.form.submit', lang) + ' →'}</button>
            </>}
          </form>
        </div>
      </div>
    </section>
  );
}

function Footer({ lang, setPage }) {
  return (
    <footer className="v4-footer">
      <div className="container">
        <div className="v4-footer-grid">
          <div>
            <h4>{t('company.legal', lang)}</h4>
            <p style={{fontSize: 13, color: '#8497ad'}}>{t('company.role', lang)}</p>
          </div>
          <div><h4>CPP</h4><ul>{FILMS.filter(f=>f.family==='CPP').slice(0,5).map(f=><li key={f.id}><a>{f.code}</a></li>)}</ul></div>
          <div><h4>BOPP</h4><ul>{FILMS.filter(f=>f.family==='BOPP').slice(0,5).map(f=><li key={f.id}><a>{f.code}</a></li>)}</ul></div>
          <div><h4>PET</h4><ul>{FILMS.filter(f=>f.family==='PET').slice(0,5).map(f=><li key={f.id}><a>{f.code}</a></li>)}</ul></div>
          <div><h4>OPP</h4><ul>{FILMS.filter(f=>f.family==='OPP').slice(0,5).map(f=><li key={f.id}><a>{f.code}</a></li>)}</ul></div>
          <div><h4>{lang==='ua'?'Компанія':'Company'}</h4><ul>
            <li><a onClick={()=>setPage('about')}>{t('nav.about',lang)}</a></li>
            <li><a onClick={()=>setPage('production')}>{t('nav.production',lang)}</a></li>
            <li><a onClick={()=>setPage('careers')}>{t('nav.careers',lang)}</a></li>
            <li><a onClick={()=>setPage('contacts')}>{t('nav.contacts',lang)}</a></li>
          </ul></div>
        </div>
        <div className="v4-footer-bottom">
          <div>{t('footer.rights', lang)}</div>
          <div>{t('footer.edrpou', lang)}</div>
        </div>
      </div>
    </footer>
  );
}

function App() {
  const [lang, setLang] = useState('ua');
  const [page, setPage] = useState('home');
  const [product, setProduct] = useState(null);
  const [filter, setFilter] = useState('all');
  const [, setTick] = useState(0);
  useEffect(() => { window.scrollTo(0, 0); }, [page, product]);
  useEffect(() => {
    const onUpdate = () => { FILMS = window.ALLIANCE_DATA.FILMS; setTick(t => t + 1); };
    window.addEventListener('alliance-data-updated', onUpdate);
    window.addEventListener('storage', onUpdate);
    return () => {
      window.removeEventListener('alliance-data-updated', onUpdate);
      window.removeEventListener('storage', onUpdate);
    };
  }, []);
  FILMS = window.ALLIANCE_DATA.FILMS;
  return (
    <div>
      <Header page={page} setPage={setPage} lang={lang} setLang={setLang} />
      {page === 'home' && (<><Hero lang={lang} setPage={setPage} /><Stats lang={lang} /><Families lang={lang} setPage={setPage} setFilter={setFilter} /></>)}
      {page === 'catalog' && <CatalogPage lang={lang} setPage={setPage} setProduct={setProduct} filter={filter} setFilter={setFilter} />}
      {page === 'product' && <ProductPage lang={lang} productId={product} setPage={setPage} />}
      {page === 'about' && <AboutPage lang={lang} />}
      {page === 'production' && <ProductionPage lang={lang} setPage={setPage} />}
      {page === 'careers' && <CareersPage lang={lang} setPage={setPage} />}
      {page === 'contacts' && <ContactsPage lang={lang} />}
      <Footer lang={lang} setPage={setPage} />
    </div>
  );
}

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