// Single project detail page

function ProjectPage({ navigate, slug }) {
  const { PROJECTS } = window.feinData;
  const idx = PROJECTS.findIndex(p => p.slug === slug);
  if (idx === -1) {
    return (
      <>
        <Header route="projects" navigate={navigate} />
        <section className="page-hero"><h1>Projekt nicht gefunden</h1></section>
        <Footer navigate={navigate} />
      </>
    );
  }
  const p = PROJECTS[idx];
  const next = PROJECTS[(idx + 1) % PROJECTS.length];
  const prev = PROJECTS[(idx - 1 + PROJECTS.length) % PROJECTS.length];
  React.useEffect(() => { window.scrollTo(0, 0); }, [slug]);

  const renderTitle = (parts) => parts.map((part, i) => typeof part === 'string' ? <span key={i}>{part}</span> : <span key={i} className="ital">{part.ital}</span>);

  return (
    <>
      <Header route="projects" navigate={navigate} />

      <section className="pp-hero">
        <div className="pp-hero__top">
          <div className="crumb"><a onClick={() => navigate('home')}>Start</a> / <a onClick={() => navigate('projects')}>Projekte</a> / {p.nr}</div>
          <h1 className="pp-hero__title">{renderTitle(p.title)}</h1>
          <div className="pp-hero__sub">
            <div className="item"><span className="lbl">Nr.</span><span className="val">{p.nr}</span></div>
            <div className="item"><span className="lbl">Ort</span><span className="val">{p.location}</span></div>
            <div className="item"><span className="lbl">Jahr</span><span className="val">{p.year}</span></div>
            <div className="item"><span className="lbl">Status</span><span className="val">{p.status}</span></div>
            <div className="item"><span className="lbl">Typologie</span><span className="val">{p.typeLabel}</span></div>
          </div>
        </div>
        <img
          className={p.coverFull ? 'pp-hero__cover--full' : 'pp-hero__cover--crop'}
          src={p.cover}
          loading="eager"
          fetchPriority="high"
          width="1920" height="1280"
          alt={p.title.map(t => typeof t === 'string' ? t : t.ital).join('')}
        />
      </section>

      <section className="pp-meta">
        <div className="pp-meta__row">
          <div className="pp-meta__cell"><div className="lbl">{p.clientLabel || 'Bauherrschaft'}</div><div className="val">{p.client}</div></div>
          <div className="pp-meta__cell"><div className="lbl">{p.scopeLabel || 'Leistungs\u00adphasen'}</div><div className="val">{p.scope}</div></div>
          <div className="pp-meta__cell"><div className="lbl">{p.areaLabel || 'Fläche'}</div><div className="val">{p.area}</div></div>
          <div className="pp-meta__cell"><div className="lbl">{p.durationLabel || 'Bauzeit'}</div><div className="val">{p.duration}</div></div>
          <div className="pp-meta__cell"><div className="lbl">Standort</div><div className="val">{p.location}</div></div>
        </div>
      </section>

      <section className="pp-narr">
        <div className="pp-narr__grid">
          <div className="lab">— Über das Projekt</div>
          <div>
            {p.narrativeHead && <h2>{p.narrativeHead}</h2>}
            {!p.narrativeHead && <h2>{p.teaser}</h2>}
            {p.narrative.map((para, i) => {
              const text = typeof para === 'string' ? para : para.text;
              const cls = typeof para === 'object' && para.cls ? `body body--${para.cls}` : 'body';
              const links = typeof para === 'object' && para.links ? para.links : [];
              if (links.length === 0) return <p key={i} className={cls}>{text}</p>;
              // Replace [anchor](url) markers with <a> elements
              let parts = [text];
              links.forEach(({ anchor, url }) => {
                parts = parts.flatMap(part => {
                  if (typeof part !== 'string') return [part];
                  const idx = part.indexOf(anchor);
                  if (idx === -1) return [part];
                  return [
                    part.slice(0, idx),
                    <a key={url} href={url} target="_blank" rel="noopener noreferrer">{anchor}</a>,
                    part.slice(idx + anchor.length)
                  ];
                });
              });
              return <p key={i} className={cls}>{parts}</p>;
            })}
          </div>
        </div>
      </section>

      <section className="pp-gallery">
        {p.gallery[0] && (
          <figure className="pp-gallery__fig pp-gallery__fig--big">
            <img className="pp-gallery__big" src={p.gallery[0].src} loading="lazy" width="1920" height="1280" alt={`Architekt Stuttgart – ${p.gallery[0].cap || p.teaser} – feinplaner`} />
            {p.gallery[0].cap && <figcaption className="pp-gallery__cap">{p.gallery[0].cap}</figcaption>}
          </figure>
        )}
        <div className="pp-gallery__row2">
          {p.gallery[1]
            ? <figure className="pp-gallery__fig"><img className="shot" src={p.gallery[1].src} loading="lazy" width="1920" height="1280" alt={`Architekt Stuttgart – ${p.gallery[1].cap || p.teaser} – feinplaner`} />{p.gallery[1].cap && <figcaption className="pp-gallery__cap">{p.gallery[1].cap}</figcaption>}</figure>
            : <image-slot id={`gal-${p.slug}-1`} placeholder="Foto 02 hier ablegen" style={{ aspectRatio: '4/3', display: 'block' }}></image-slot>}
          {p.gallery[2]
            ? <figure className="pp-gallery__fig"><img className="shot" src={p.gallery[2].src} loading="lazy" width="1920" height="1280" alt={`Architekt Stuttgart – ${p.gallery[2].cap || p.teaser} – feinplaner`} />{p.gallery[2].cap && <figcaption className="pp-gallery__cap">{p.gallery[2].cap}</figcaption>}</figure>
            : <image-slot id={`gal-${p.slug}-2`} placeholder="Foto 03 hier ablegen" style={{ aspectRatio: '4/3', display: 'block' }}></image-slot>}
        </div>
        {(p.gallery[3] || p.gallery[4] || p.gallery[5]) && (
          <div className="pp-gallery__row3">
            {[3,4,5].map(i => p.gallery[i]
              ? <figure key={i} className="pp-gallery__fig"><img className="shot" src={p.gallery[i].src} loading="lazy" width="1920" height="1280" alt={`Architekt Stuttgart – ${p.gallery[i].cap || p.teaser} – feinplaner`} />{p.gallery[i].cap && <figcaption className="pp-gallery__cap">{p.gallery[i].cap}</figcaption>}</figure>
              : <image-slot key={i} id={`gal-${p.slug}-${i}`} placeholder={`Foto 0${i+1} ablegen`} style={{ aspectRatio: '1/1', display: 'block' }}></image-slot>
            )}
          </div>
        )}
      </section>

      {p.plans && p.plans.length > 0 && (
        <section className="pp-plans">
          <div className="pp-plans__inner">
            {p.plans.map((plan, i) => (
              <figure key={i} className="pp-plans__fig">
                <img className="pp-plans__img" src={plan.src} loading="lazy" alt={`Architekt Stuttgart – ${plan.cap || p.teaser} – feinplaner`} />
                {plan.cap && <figcaption className="pp-gallery__cap">{plan.cap}</figcaption>}
              </figure>
            ))}
          </div>
        </section>
      )}

      {p.quote && (
        <section className="pp-quote">
          <blockquote>„{p.quote.text}"</blockquote>
          <div className="by">— {p.quote.by}</div>
        </section>
      )}

      <section className="pp-next">
        <div className="pp-next__head">
          <div className="eyebrow petrol">— Weiter</div>
          <div className="pp-next__nav">
            <button onClick={() => navigate(`project/${prev.slug}`)}>← {prev.nr}</button>
            <button onClick={() => navigate('projects')}>Übersicht</button>
            <button onClick={() => navigate(`project/${next.slug}`)}>{next.nr} →</button>
          </div>
        </div>
        <div className="feat-row" onClick={() => navigate(`project/${next.slug}`)}>
          <div className="feat-row__num">{next.nr}</div>
          <div className="feat-row__title">{renderTitle(next.title)}</div>
          <div className="feat-row__meta">{next.typeLabel}<br />{next.location} · {next.year}</div>
          <img className="feat-row__thumb" src={next.thumb} loading="lazy" alt={next.title.map(t => typeof t === 'string' ? t : t.ital).join('')} />
        </div>
      </section>

      <CtaStrip navigate={navigate} />
      <Footer navigate={navigate} />
    </>
  );
}

window.ProjectPage = ProjectPage;
