/* Objektbericht — full project-report detail page (cover + sticky project data +
   running images with lightbox + random related). Bilingual via window.tr.
   Reads its report from window.SITE.reports by id. */
(function () {
  const { useState, useEffect, useMemo } = React;
  const h = React.createElement;

  const FACT = {
    ort:       { de: 'Ort',       en: 'Location' },
    year:      { de: 'Jahr',      en: 'Year' },
    cat:       { de: 'Kategorie', en: 'Category' },
    produkt:   { de: 'Produkt',   en: 'Product' },
    format:    { de: 'Format',    en: 'Format' },
    verlegung: { de: 'Verlegung', en: 'Laying pattern' },
    farbe:     { de: 'Farbe',     en: 'Colour' },
    flaeche:   { de: 'Fläche',    en: 'Area' },
    produzent: { de: 'Produzent', en: 'Producer' },
    planung:   { de: 'Planung',   en: 'Planning' },
  };
  const cap = (s) => (s ? s.charAt(0).toUpperCase() + s.slice(1) : s);

  function Figure(props) {
    const { src, caption, onOpen } = props;
    return h('figure', { className: 'obj-figure', onClick: onOpen },
      h('img', { src: src, alt: '' }),
      h('span', { className: 'obj-figure__zoom', 'aria-hidden': true }, '\u2922'),
      caption ? h('figcaption', { className: 'obj-figcap' }, caption) : null
    );
  }

  const Objektbericht = ({ lang, navigate, id }) => {
    const t = (v) => window.tr(lang, v);
    const all = (window.SITE && window.SITE.reports) || [];
    const cats = (window.SITE && window.SITE.categories) || [];
    const report = all.find((r) => r.id === id) || all[0];
    const [lb, setLb] = useState(-1);

    const imgs = (report && report.images) || [];

    const related = useMemo(() => {
      const pool = all.filter((r) => r.id !== (report && report.id));
      for (let i = pool.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        const x = pool[i]; pool[i] = pool[j]; pool[j] = x;
      }
      return pool.slice(0, 3);
    }, [report && report.id]);

    useEffect(() => {
      const onKey = (e) => {
        if (lb < 0 || !imgs.length) return;
        if (e.key === 'Escape') setLb(-1);
        else if (e.key === 'ArrowRight') { e.preventDefault(); setLb((i) => (i + 1) % imgs.length); }
        else if (e.key === 'ArrowLeft') { e.preventDefault(); setLb((i) => (i - 1 + imgs.length) % imgs.length); }
      };
      window.addEventListener('keydown', onKey);
      return () => window.removeEventListener('keydown', onKey);
    }, [lb, imgs.length]);

    if (!report) {
      return h('section', { className: 'section' }, h('div', { className: 'container' },
        h('p', { className: 'lead' }, t({ de: 'Bericht nicht gefunden.', en: 'Report not found.' }))));
    }

    const catName = (cid) => { const c = cats.find((x) => x.id === cid); return c ? t(c.title) : cid; };
    const f = report.facts || {};
    const specs = [];
    if (f.ort) specs.push([FACT.ort, f.ort]);
    if (report.year) specs.push([FACT.year, report.year]);
    if (report.categories && report.categories.length) specs.push([FACT.cat, report.categories.map(catName).join(' \u00b7 ')]);
    if (f.produkt) specs.push([FACT.produkt, f.produkt + ' \u00b7 EINSTEIN\u00ae']);
    if (f.format) specs.push([FACT.format, f.format]);
    if (f.verlegung) specs.push([FACT.verlegung, f.verlegung]);
    if (f.farbe) specs.push([FACT.farbe, cap(f.farbe)]);
    if (f.flaeche) specs.push([FACT.flaeche, f.flaeche]);
    if (f.produzent) specs.push([FACT.produzent, f.produzent]);
    if (f.planung) specs.push([FACT.planung, f.planung]);

    // running image distribution: [0] after intro, [i+1] per section, rest -> gallery
    const introImg = imgs[0];
    const usedCount = Math.min(imgs.length, 1 + report.sections.length);
    const gallery = imgs.slice(usedCount).map((im, k) => ({ im, idx: usedCount + k }));

    /* ---- Hero cover ---- */
    const hero = h('header', { className: 'obj-hero' },
      h('img', { className: 'obj-hero__img', src: report.img, alt: '' }),
      h('div', { className: 'obj-hero__veil' }),
      h('div', { className: 'container obj-hero__inner' },
        h('button', { className: 'obj-back', onClick: () => navigate('projects') },
          '\u2039 ', t({ de: 'Alle Objekte', en: 'All projects' })),
        h('p', { className: 'eyebrow', style: { color: '#fff' } }, report.categories.map(catName).join(' \u00b7 ')),
        h('h1', { className: 'display display--lg obj-hero__title' }, t(report.title)),
        h('div', { className: 'mono obj-hero__meta' },
          report.place ? h('span', null, report.place) : null,
          report.place ? h('span', { className: 'obj-hero__dot' }, '\u00b7') : null,
          h('span', null, report.year))
      )
    );

    /* ---- Facts rail ---- */
    const rail = h('aside', { className: 'obj-rail' },
      h('div', { className: 'obj-facts' },
        h('h2', { className: 'obj-facts__title' }, t({ de: 'Objektdaten', en: 'Project data' })),
        specs.map(([label, value], i) => h('div', { key: i, className: 'obj-facts__row' },
          h('span', { className: 'obj-facts__k' }, t(label)),
          h('span', { className: 'obj-facts__v' }, value)))
      )
    );

    /* ---- Main column ---- */
    const body = h('div', { className: 'obj-main' },
      h('p', { className: 'obj-lead' }, t(report.lead)),
      (report.intro || []).map((p, i) => h('p', { key: 'in' + i, className: 'obj-para' }, t(p))),
      introImg ? h(Figure, { src: introImg.src, caption: t(introImg.cap), onOpen: () => setLb(0) }) : null,
      report.sections.map((s, i) => {
        const im = imgs[i + 1];
        return h('section', { key: 's' + i, className: 'obj-section' },
          h('span', { className: 'obj-section__bar', 'aria-hidden': true }),
          h('h2', { className: 'obj-section__h' }, t(s.h)),
          (s.ps || []).map((p, j) => h('p', { key: j, className: 'obj-para' }, t(p))),
          im ? h(Figure, { src: im.src, caption: t(im.cap), onOpen: () => setLb(i + 1) }) : null
        );
      }),
      gallery.length ? h('div', { className: 'obj-gallery-wrap' },
        h('span', { className: 'obj-section__bar', 'aria-hidden': true }),
        h('h2', { className: 'obj-section__h' }, t({ de: 'Weitere Eindrücke', en: 'More impressions' })),
        h('div', { className: 'obj-gallery' },
          gallery.map(({ im, idx }) => h('figure', { key: idx, className: 'obj-figure obj-figure--tile', onClick: () => setLb(idx) },
            h('img', { src: im.src, alt: '' }),
            h('span', { className: 'obj-figure__zoom', 'aria-hidden': true }, '\u2922'))))
      ) : null
    );

    /* ---- Related (random) ---- */
    const relatedBlock = h('section', { className: 'section section--sunken', style: { borderTop: '1px solid var(--border-subtle)' } },
      h('div', { className: 'container' },
        h('div', { className: 'obj-rel-head' },
          h('h2', { className: 'display display--md', style: { fontSize: 'var(--h2)' } }, t({ de: 'Weitere Objekte', en: 'More projects' })),
          h('span', { className: 'mono', style: { color: 'var(--text-brand)', fontSize: '12px', textTransform: 'uppercase', letterSpacing: '.06em' } },
            t({ de: '// zufällige Auswahl', en: '// random selection' }))),
        h('div', { className: 'report-grid' },
          related.map((r) => h('article', {
            key: r.id, className: 'report', style: { cursor: 'pointer' },
            onClick: () => navigate('object', { id: r.id }),
          },
            h('div', { className: 'report__img' }, h('img', { src: r.img, alt: t(r.title) })),
            h('div', { className: 'report__body' },
              h('p', { className: 'report__meta' }, h('span', null, r.place || '\u2014'), h('span', null, r.year)),
              h('h3', { className: 'report__title' }, t(r.title)),
              h('span', { className: 'tag report__cat' }, catName(r.category))))))
      )
    );

    /* ---- Lightbox ---- */
    const lightbox = lb >= 0 && imgs[lb] ? h('div', { className: 'obj-lb', onClick: () => setLb(-1) },
      h('button', { className: 'obj-lb__btn obj-lb__close', 'aria-label': 'Close', onClick: () => setLb(-1) }, '\u00d7'),
      imgs.length > 1 ? h('button', {
        className: 'obj-lb__btn obj-lb__prev', 'aria-label': 'Previous',
        onClick: (e) => { e.stopPropagation(); setLb((i) => (i - 1 + imgs.length) % imgs.length); },
      }, '\u2039') : null,
      h('figure', { className: 'obj-lb__fig', onClick: (e) => e.stopPropagation() },
        h('img', { className: 'obj-lb__img', src: imgs[lb].src, alt: '' }),
        h('figcaption', { className: 'obj-lb__cap' },
          t(imgs[lb].cap) ? h('span', { className: 'obj-lb__captext' }, t(imgs[lb].cap)) : null,
          h('span', { className: 'mono obj-lb__count' }, (lb + 1) + ' / ' + imgs.length))),
      imgs.length > 1 ? h('button', {
        className: 'obj-lb__btn obj-lb__next', 'aria-label': 'Next',
        onClick: (e) => { e.stopPropagation(); setLb((i) => (i + 1) % imgs.length); },
      }, '\u203a') : null
    ) : null;

    return h(React.Fragment, null,
      hero,
      h('div', { className: 'reveal-sheet' },
        h('section', { className: 'section' },
          h('div', { className: 'container' },
            h('div', { className: 'obj-detail-grid' }, rail, body)))),
      relatedBlock,
      lightbox
    );
  };

  window.Objektbericht = Objektbericht;
})();
