/* ════════════════════════════════════════════════════════════════
   sections.jsx — marketing sections for the ZILENT one-pager
   Composes ZILENT design-system components (Button, Input, Badge,
   ProgressBar) with site CSS. Exposes section components on window.
   ════════════════════════════════════════════════════════════════ */

const DS = window.ZILENTSoftwareDesignSystem_2f3f9a;
const { Button, Input, Badge, ProgressBar } = DS;

/* ─── shared smooth-scroll-to-section helper ──────────────────────── */
const NAV_OFFSET = 60;
function scrollToId(id) {
  const el = document.getElementById(id);
  if (el) window.scrollTo({ top: el.getBoundingClientRect().top + window.scrollY - NAV_OFFSET, behavior: 'smooth' });
}
window.scrollToId = scrollToId;

/* ─── keyboard-accessible clickable text (role=button) ────────────── */
function LinkText({ onClick, className = 'lk', children, ariaLabel }) {
  const activate = (e) => { e.preventDefault(); onClick(e); };
  return (
    <span
      className={className}
      role="button"
      tabIndex={0}
      aria-label={ariaLabel}
      onClick={onClick}
      onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') activate(e); }}
    >
      {children}
    </span>
  );
}

/* ─── scroll reveal ───────────────────────────────────────────── */
function Reveal({ children, as: Tag = 'div', className = '', style }) {
  const ref = React.useRef(null);
  React.useEffect(() => {
    const el = ref.current;
    if (!el) return;
    if (!('IntersectionObserver' in window)) { el.classList.add('in'); return; }
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => { if (e.isIntersecting) { e.target.classList.add('in'); io.unobserve(e.target); } });
    }, { threshold: 0.12 });
    io.observe(el);
    return () => io.disconnect();
  }, []);
  return <Tag ref={ref} className={`reveal ${className}`} style={style}>{children}</Tag>;
}

/* ─── Language switcher ───────────────────────────────────────── */
function LangSwitcher({ lang, setLang }) {
  return (
    <div className="lang" role="group" aria-label="Language">
      {window.LANGS.map((l) => (
        <button key={l.code} className="lang__btn" aria-pressed={lang === l.code} onClick={() => setLang(l.code)}>
          {l.label}
        </button>
      ))}
    </div>
  );
}

/* ─── Navigation ──────────────────────────────────────────────── */
function Nav({ t, lang, setLang, onHome }) {
  const [open, setOpen] = React.useState(false);
  const links = [
    { id: 'app', label: t.nav.app },
    { id: 'about', label: t.nav.about },
    { id: 'how', label: t.nav.how },
    { id: 'contact', label: t.nav.contact },
  ];
  const go = (id) => (e) => {
    e.preventDefault();
    setOpen(false);
    onHome();
    requestAnimationFrame(() => scrollToId(id));
  };
  const goTop = () => { setOpen(false); onHome(); window.scrollTo({ top: 0, behavior: 'smooth' }); };
  return (
    <nav className="nav">
      <div className="container nav__inner">
        <div className="brand" role="button" tabIndex={0} aria-label="ZILENT Software — Startseite"
          onClick={goTop}
          onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); goTop(); } }}>
          <span className="brand__mark">ZILENT</span>
          <span className="brand__sub">Software</span>
        </div>
        <div className={`nav-links ${open ? 'open' : ''}`}>
          {links.map((l) => (
            <a key={l.id} className="nav-link" href={'#' + l.id} onClick={go(l.id)}>{l.label}</a>
          ))}
          <LangSwitcher lang={lang} setLang={setLang} />
        </div>
        <button className="nav__toggle" aria-label="Menu" aria-expanded={open} onClick={() => setOpen((o) => !o)}>
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" aria-hidden="true">
            {open
              ? <path d="M6 6l12 12M18 6L6 18" />
              : <React.Fragment><path d="M3 6h18" /><path d="M3 12h18" /><path d="M3 18h18" /></React.Fragment>}
          </svg>
        </button>
      </div>
    </nav>
  );
}

/* ─── Hero ────────────────────────────────────────────────────── */
function Hero({ t, onScrollWait }) {
  return (
    <header className="hero section--tight" id="top">
      <div className="container hero__grid">
        <Reveal className="hero__head">
          <div className="eyebrow">{t.hero.eyebrow}</div>
          <h1 className="display">
            {t.hero.title1}<span className="accent">{t.hero.titleAccent}</span>{t.hero.title2}
          </h1>
        </Reveal>
        <Reveal className="phone-wrap">
          <div className="phone">
            <div className="phone__screen">
              <img src="assets/home.png" alt={'34A Training App — ' + t.app.shotA} loading="lazy" draggable={false} />
            </div>
            <div className="phone__badge"><Badge variant="orange" size="md">{t.hero.badge}</Badge></div>
          </div>
        </Reveal>
        <Reveal className="hero__body">
          <p className="lead hero__lead">{t.hero.lead}</p>
          <div className="hero__cta">
            <Button variant="primary" size="lg" onClick={onScrollWait}>{t.hero.ctaPrimary} →</Button>
            <Button variant="outlined" size="lg" style={{ color: '#fff' }} onClick={() => scrollToId('app')}>
              {t.hero.ctaSecondary}
            </Button>
          </div>
          <div className="hero__meta">
            <div><span className="k accent">{t.hero.m1k}</span><span className="l">{t.hero.m1l}</span></div>
            <div><span className="k">{t.hero.m2k}</span><span className="l">{t.hero.m2l}</span></div>
            <div><span className="k">{t.hero.m3k}</span><span className="l">{t.hero.m3l}</span></div>
          </div>
        </Reveal>
      </div>
    </header>
  );
}

/* ─── About ───────────────────────────────────────────────────── */
function About({ t }) {
  return (
    <section className="section" id="about">
      <div className="container">
        <Reveal>
          <div className="eyebrow">{t.about.eyebrow}</div>
          <h2 className="display h2" style={{ maxWidth: '20ch' }}>{t.about.title}</h2>
          <p className="lead" style={{ marginTop: '24px' }}>{t.about.lead}</p>
        </Reveal>
        <Reveal className="facts">
          <div className="fact"><div className="k">{t.about.f1k}</div><div className="l">{t.about.f1l}</div></div>
          <div className="fact"><div className="k">{t.about.f2k}</div><div className="l">{t.about.f2l}</div></div>
          <div className="fact"><div className="k">{t.about.f3k}</div><div className="l">{t.about.f3l}</div></div>
        </Reveal>
      </div>
    </section>
  );
}

/* ─── App feature section ─────────────────────────────────────── */
function AppSection({ t }) {
  return (
    <section className="section" id="app" style={{ background: 'var(--color-navy-raised)', borderBlock: '1px solid var(--rule)' }}>
      <div className="container split split--narrow-text">
        <Reveal className="shots">
          <div className="shot">
            <div className="shot__screen"><img src="assets/statistics.png" alt={'34A Training App — ' + t.app.eyebrow} loading="lazy" draggable={false} /></div>
          </div>
          <div className="shot">
            <div className="shot__screen"><img src="assets/quiz.png" alt={'34A Training App — ' + t.app.shotB} loading="lazy" draggable={false} /></div>
          </div>
        </Reveal>
        <Reveal>
          <div className="eyebrow">{t.app.eyebrow}</div>
          <h2 className="display h2">{t.app.title}</h2>
          <p className="lead" style={{ marginTop: '20px' }}>{t.app.lead}</p>

          <div style={{ marginTop: '30px' }}>
            <div className="l" style={{ fontSize: '10px', textTransform: 'uppercase', color: 'var(--text-muted)', marginBottom: '10px' }}>{t.app.topicsLabel}</div>
            <div className="chips">
              {window.TOPICS.map((tp) => <span className="chip" key={tp}>{tp}</span>)}
            </div>
          </div>

          <div className="flist">
            {t.app.f.map((f, i) => (
              <div className="fitem" key={i}>
                <div className="fitem__no">{String(i + 1).padStart(2, '0')}</div>
                <div><h4>{f.t}</h4><p>{f.d}</p></div>
              </div>
            ))}
          </div>
        </Reveal>
      </div>
    </section>
  );
}

/* ─── How it works (white) ────────────────────────────────────── */
function HowItWorks({ t }) {
  return (
    <section className="section section--light" id="how">
      <div className="container">
        <Reveal>
          <div className="eyebrow">{t.how.eyebrow}</div>
          <h2 className="display h2" style={{ maxWidth: '18ch' }}>{t.how.title}</h2>
          <p className="lead" style={{ marginTop: '20px' }}>{t.how.lead}</p>
        </Reveal>
        <Reveal className="steps">
          {t.how.s.map((s, i) => (
            <div className="step" key={i}>
              <div className="step__no">{String(i + 1).padStart(2, '0')}</div>
              <h4>{s.t}</h4>
              <p>{s.d}</p>
            </div>
          ))}
        </Reveal>
      </div>
    </section>
  );
}

/* ─── Launch / "coming soon" band ─────────────────────────────────
   The waitlist form was removed: there is no backend to receive the
   addresses, so collecting them would be misleading and would not
   match the privacy policy. This band now points visitors to contact. */
function Waitlist({ t }) {
  return (
    <section className="band section--tight" id="wait">
      <div className="container band__grid">
        <Reveal>
          <h2 className="display h2" style={{ maxWidth: '16ch' }}>{t.wait.title}</h2>
          <p className="lead" style={{ marginTop: '16px' }}>{t.wait.lead}</p>
        </Reveal>
        <Reveal style={{ minWidth: 'min(420px, 100%)' }}>
          <Button variant="primary" size="lg" onClick={() => scrollToId('contact')}>{t.wait.cta} →</Button>
        </Reveal>
      </div>
    </section>
  );
}

/* ─── Support / contact form ──────────────────────────────────── */
function Support({ t }) {
  const [f, setF] = React.useState({ name: '', email: '', subject: '', message: '' });
  const [done, setDone] = React.useState(false);
  const set = (k) => (e) => setF((s) => ({ ...s, [k]: e.target.value }));
  const valid = f.name && /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(f.email) && f.message;
  const submit = (e) => {
    e.preventDefault();
    if (!valid) return;
    const subject = encodeURIComponent('[Support] ' + (f.subject || 'Anfrage'));
    const body = encodeURIComponent(`${f.name} <${f.email}>\n\n${f.message}`);
    window.location.href = `mailto:info@zilent.de?subject=${subject}&body=${body}`;
    setDone(true);
  };
  return (
    <section className="section" id="contact">
      <div className="container split" style={{ alignItems: 'start' }}>
        <Reveal>
          <div className="eyebrow">{t.support.eyebrow}</div>
          <h2 className="display h2">{t.support.title}</h2>
          <p className="lead" style={{ marginTop: '18px' }}>{t.support.lead}</p>
          <div className="contact-aside" style={{ marginTop: '34px' }}>
            <div className="contact-row">
              <div className="l">{t.support.asideEmail}</div>
              <a className="v accent" href="mailto:info@zilent.de">info@zilent.de</a>
            </div>
            <div className="contact-row">
              <div className="l">{t.support.asideLoc}</div>
              <div className="v">Hohe Straße 39, 04107 Leipzig</div>
            </div>
            <div className="contact-row">
              <div className="l">{t.support.asideTime}</div>
              <div className="v">{t.support.asideTimeVal}</div>
            </div>
          </div>
        </Reveal>

        <Reveal>
          {done ? (
            <div className="support-ok" role="status">
              <div className="check" aria-hidden="true">✓</div>
              <div>
                <div style={{ fontWeight: 600, marginBottom: '6px' }}>{t.support.okTitle}</div>
                <div className="muted" style={{ fontSize: 'var(--text-base)' }}>{t.support.okText}</div>
              </div>
            </div>
          ) : (
            <form className="form-grid" onSubmit={submit}>
              <Input variant="dark" size="md" label={t.support.name} value={f.name} onChange={set('name')} placeholder={t.support.ph.name} />
              <Input variant="dark" size="md" label={t.support.email} type="email" value={f.email} onChange={set('email')} placeholder={t.support.ph.email} />
              <div className="full">
                <Input variant="dark" size="md" label={t.support.subject} value={f.subject} onChange={set('subject')} placeholder={t.support.ph.subject} />
              </div>
              <div className="full">
                <label htmlFor="support-message" style={{ display: 'block', fontFamily: 'var(--font-mono)', fontSize: 'var(--text-xs)', letterSpacing: 'var(--tracking-mono)', textTransform: 'uppercase', color: 'var(--text-muted)', marginBottom: '4px', fontWeight: 500 }}>
                  {t.support.message}
                </label>
                <textarea id="support-message" className="ta" value={f.message} onChange={set('message')} placeholder={t.support.ph.message}></textarea>
              </div>
              <div className="full">
                <Button variant="primary" size="lg" fullWidth disabled={!valid}>{t.support.submit} →</Button>
              </div>
            </form>
          )}
        </Reveal>
      </div>
    </section>
  );
}

/* ─── Footer ──────────────────────────────────────────────────── */
function Footer({ t, lang, setLang, goLegal, onHome }) {
  const year = new Date().getFullYear();
  const legalLinks = [
    { id: 'impressum', label: t.legal.impressum },
    { id: 'datenschutz', label: t.legal.datenschutz },
    { id: 'agb', label: t.legal.agb },
    { id: 'widerruf', label: t.legal.widerruf },
  ];
  const goSection = (id) => () => { onHome(); requestAnimationFrame(() => scrollToId(id)); };
  return (
    <footer className="footer">
      <div className="container">
        <div className="footer__top">
          <div>
            <div className="footer__word">ZILENT</div>
            <div className="footer__tag">{t.footer.tag}</div>
          </div>
          <div className="footer-col">
            <h5>{t.footer.product}</h5>
            <ul>
              <li><LinkText onClick={goSection('app')}>{t.footer.lApp}</LinkText></li>
              <li><LinkText onClick={goSection('about')}>{t.footer.lAbout}</LinkText></li>
            </ul>
          </div>
          <div className="footer-col">
            <h5>{t.footer.legal}</h5>
            <ul>
              {legalLinks.map((l) => (
                <li key={l.id}><LinkText onClick={() => goLegal(l.id)}>{l.label}</LinkText></li>
              ))}
            </ul>
          </div>
        </div>
        <div className="footer__bottom">
          <span>© {year} Zilent Software · {t.footer.rights}</span>
          <LangSwitcher lang={lang} setLang={setLang} />
        </div>
      </div>
    </footer>
  );
}

/* ─── Cookie banner ───────────────────────────────────────────── */
/* Only technically necessary storage is used (no consent required under
   § 25 Abs. 2 TDDDG), so this is a single informational notice — not a
   consent dialog with a misleading accept/reject choice. */
function CookieBanner({ t, onClose, goLegal }) {
  return (
    <div className="cookie" role="region" aria-label="Cookie-Hinweis">
      <div className="container cookie__inner">
        <div className="cookie__text">
          {t.cookie.text}{' '}
          <a href="#datenschutz" onClick={(e) => { e.preventDefault(); goLegal('datenschutz'); onClose(); }}>{t.cookie.link}</a>.
        </div>
        <div className="cookie__btns">
          <Button variant="primary" size="md" onClick={onClose}>{t.cookie.accept}</Button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, {
  Reveal, LangSwitcher, Nav, Hero, About, AppSection, HowItWorks, Waitlist, Support, Footer, CookieBanner,
});
