/* Tessera main app — uses PROJECTS, T, Pictos, cssVarsFor from window (tessera-data.jsx) */

const { useState, useEffect, useRef, useMemo, useLayoutEffect } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "phoneWidth": 300,
  "sideScale": 0.5,
  "sideOpacity": 0.75,
  "carouselGap": 232
}/*EDITMODE-END*/;

/* ============ MAIN APP ============ */
function App() {
  const [cursor, setCursor] = useState(0); // unbounded integer; wraps via modulo
  const [lang, setLang] = useState('fr');
  const [phase, setPhase] = useState('in'); // 'in' | 'out'
  const [scrollY, setScrollY] = useState(0);
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const n = PROJECTS.length;
  const idx = ((cursor % n) + n) % n;
  const project = PROJECTS[idx];

  // phone-carousel width is driven by a CSS var so it's directly tweakable
  useLayoutEffect(() => {
    document.documentElement.style.setProperty('--phone-w', t.phoneWidth + 'px');
  }, [t.phoneWidth]);

  // adaptive CSS vars on <html>
  useLayoutEffect(() => {
    const vars = cssVarsFor(project);
    const root = document.documentElement;
    Object.entries(vars).forEach(([k,v]) => root.style.setProperty(k, v));
    root.dataset.theme = vars['--theme'];
    document.documentElement.lang = lang;
  }, [idx, lang]);

  // switch with fade-slide. delta: signed integer step (or absolute new cursor)
  const lastFire = useRef(0);
  const stepCursor = (delta) => {
    const now = performance.now();
    if (now - lastFire.current < 240) return; // throttle to avoid pile-up
    lastFire.current = now;
    setCursor(c => c + delta);
    setPhase('out');
    setTimeout(() => requestAnimationFrame(() => setPhase('in')), 360);
  };
  const setCursorAbs = (target) => {
    const delta = target - cursor;
    if (delta === 0) return;
    stepCursor(delta);
  };

  // keyboard ←/→
  useEffect(() => {
    const h = (e) => {
      if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA') return;
      if (e.key === 'ArrowLeft') stepCursor(-1);
      if (e.key === 'ArrowRight') stepCursor(+1);
    };
    window.addEventListener('keydown', h);
    return () => window.removeEventListener('keydown', h);
  }, [cursor, phase]);

  // scroll for parallax
  useEffect(() => {
    let raf;
    const onScroll = () => {
      cancelAnimationFrame(raf);
      raf = requestAnimationFrame(() => setScrollY(window.scrollY));
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  return (
    <div className={"root phase-" + phase}>
      <TopBar cursor={cursor} lang={lang} setLang={setLang} stepCursor={stepCursor} setCursorAbs={setCursorAbs} />
      <Hero project={project} lang={lang} idx={idx} count={n} onPrev={() => stepCursor(-1)} onNext={() => stepCursor(+1)} phase={phase} />
      <Presentation project={project} lang={lang} scrollY={scrollY} tweaks={t} />
      <Technical project={project} lang={lang} scrollY={scrollY} />
      <Footer project={project} lang={lang} />

      <TweaksPanel>
        <TweakSection label="Carrousel téléphones · DIALY / Wiccan" />
        <TweakSlider label="Largeur téléphone" value={t.phoneWidth} min={220} max={420} step={4} unit="px"
                     onChange={(v) => setTweak('phoneWidth', v)} />
        <TweakSlider label="Écartement latéral" value={t.carouselGap} min={160} max={320} step={4} unit="px"
                     onChange={(v) => setTweak('carouselGap', v)} />
        <TweakSlider label="Taille tél. latéraux" value={t.sideScale} min={0.35} max={0.7} step={0.05}
                     onChange={(v) => setTweak('sideScale', v)} />
        <TweakSlider label="Opacité tél. latéraux" value={t.sideOpacity} min={0.3} max={1} step={0.05}
                     onChange={(v) => setTweak('sideOpacity', v)} />
      </TweaksPanel>
    </div>
  );
}

/* ============ TOP BAR (fixed opaque) ============ */
function TopBar({ cursor, lang, setLang, stepCursor, setCursorAbs }) {
  return (
    <header className="topbar" data-screen-label="00 TopBar">
      <div className="topbar-inner">
        <div className="tb-left">
          <div className="lang" role="group" aria-label="Language">
            <button className={lang === 'fr' ? 'active' : ''} onClick={() => setLang('fr')}>FR</button>
            <span className="sep">/</span>
            <button className={lang === 'en' ? 'active' : ''} onClick={() => setLang('en')}>EN</button>
          </div>
        </div>

        <div className="tb-center">
          <button type="button" className="nav-arrow" onClick={() => stepCursor(-1)} aria-label={T.prev[lang]}>
            <span className="glyph" aria-hidden="true">‹</span>
          </button>
          <PictoCarousel cursor={cursor} setCursorAbs={setCursorAbs} />
          <button type="button" className="nav-arrow" onClick={() => stepCursor(+1)} aria-label={T.next[lang]}>
            <span className="glyph" aria-hidden="true">›</span>
          </button>
        </div>

        <div className="tb-right">
          <a href="mailto:filliat.t@gmail.com" aria-label="Mail" className="tb-ic">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4"><rect x="3" y="5" width="18" height="14" rx="1"/><path d="M3 7l9 7 9-7"/></svg>
            <span>MAIL</span>
          </a>
          <a href="https://linkedin.com/in/thibaut-filliat" target="_blank" rel="noreferrer" aria-label="LinkedIn" className="tb-ic">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4"><rect x="3" y="3" width="18" height="18" rx="2"/><path d="M7 10v7M7 7v.01M11 17v-4a2 2 0 0 1 4 0v4M11 10v7"/></svg>
            <span>LINKEDIN</span>
          </a>
          <a href="https://github.com/thibaut-filliat" target="_blank" rel="noreferrer" aria-label="GitHub" className="tb-ic">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4"><path d="M9 19c-4 1.5-4-2-6-2.5M15 22v-3.87a3.37 3.37 0 0 0-.94-2.61c3.14-.35 6.44-1.54 6.44-7a5.44 5.44 0 0 0-1.5-3.75 5.07 5.07 0 0 0-.09-3.77s-1.18-.35-3.91 1.48a13.38 13.38 0 0 0-7 0C5.27 1.62 4.09 2 4.09 2a5.07 5.07 0 0 0-.09 3.77 5.44 5.44 0 0 0-1.5 3.75c0 5.42 3.3 6.61 6.44 7A3.37 3.37 0 0 0 8 19.13V22"/></svg>
            <span>GITHUB</span>
          </a>
        </div>
      </div>
    </header>
  );
}

function PictoCarousel({ cursor, setCursorAbs }) {
  const SPACING = 78; // px between picto slots
  const n = PROJECTS.length;
  // render 5 slots centered on cursor so wrap-around slides in from the correct side
  const items = [];
  for (let s = cursor - 2; s <= cursor + 2; s++) {
    const i = ((s % n) + n) % n;
    items.push({ slot: s, p: PROJECTS[i], dist: s - cursor });
  }
  return (
    <div className="picto-carousel">
      {items.map(({ slot, p, dist }) => {
        const isActive = dist === 0;
        const visible = Math.abs(dist) <= 1;
        return (
          <button
            key={slot}
            type="button"
            className={"picto" + (isActive ? " active" : "")}
            onClick={() => setCursorAbs(slot)}
            tabIndex={visible ? 0 : -1}
            aria-current={isActive ? 'true' : undefined}
            aria-label={p.name}
            style={{
              transform: `translate(calc(-50% + ${dist * SPACING}px), -50%) scale(${isActive ? 1 : 0.6})`,
              opacity: visible ? (isActive ? 1 : 0.4) : 0,
              pointerEvents: visible ? 'auto' : 'none',
              color: isActive ? 'var(--accent)' : 'var(--text)',
            }}
          >
            <span className="picto-glyph">{Pictos[p.pictoKey]}</span>
            <span className="picto-name">{p.name.toUpperCase()}</span>
          </button>
        );
      })}
    </div>
  );
}

/* ============ HERO ============ */
function Hero({ project, lang, idx, count, onPrev, onNext, phase }) {
  return (
    <section className="hero" id="top" data-screen-label={`01 Hero · ${project.name}`}>
      <div className="hero-inner">
        <div className={"slide-anim eyebrow"}>
          <span>{T.project[lang]}</span>
          <span className="dia" aria-hidden="true"></span>
          <span>{String(idx+1).padStart(2,'0')}</span>
        </div>

        <div className="title-row slide-anim">
          <button className="arrow" onClick={onPrev} aria-label={T.prev[lang]}>
            <span className="diamond" aria-hidden="true"></span>
            <span className="glyph" aria-hidden="true">‹</span>
          </button>
          <h1 className="project-title">
            <img src={project.logo} alt={project.name} className="project-logo" style={{ '--logo-scale': project.logoScale || 1 }} />
            <span className="visually-hidden">{project.name}</span>
          </h1>
          <button className="arrow" onClick={onNext} aria-label={T.next[lang]}>
            <span className="diamond" aria-hidden="true"></span>
            <span className="glyph" aria-hidden="true">›</span>
          </button>
        </div>

        <p className="project-tagline slide-anim">{project.tagline[lang]}</p>
        <p className="project-desc slide-anim">{project.description[lang]}</p>
      </div>

      <div className="carousel-foot">
        <div className="scroll-hint" aria-hidden="true">
          <span className="sh-text">
            {lang === 'fr' ? <>Dérouler pour<br />découvrir l'app</> : <>Scroll to<br />discover the app</>}
          </span>
          <svg className="sh-arrow" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round" strokeLinejoin="round"><path d="M6 9l6 6 6-6" /></svg>
        </div>
        <div className="dots" aria-hidden="true">
          {PROJECTS.map((_,i) => <span key={i} className={"d" + (i === idx ? " on" : "")}></span>)}
        </div>
      </div>
    </section>
  );
}

/* ============ PRESENTATION ============ */
function Presentation({ project, lang, scrollY, tweaks }) {
  const ref = useRef(null);
  const [offset, setOffset] = useState(0);
  const [previewCursor, setPreviewCursor] = useState(0); // unbounded; wraps via modulo

  const previews = project.previews || null;
  const nPrev = previews ? previews.length : 0;
  const previewIdx = nPrev ? ((previewCursor % nPrev) + nPrev) % nPrev : 0;

  // reset preview index when project changes
  useEffect(() => { setPreviewCursor(0); }, [project.id]);

  useEffect(() => {
    if (!ref.current) return;
    const rect = ref.current.getBoundingClientRect();
    const center = rect.top + rect.height / 2 - window.innerHeight / 2;
    setOffset(Math.max(-80, Math.min(80, -center * 0.12)));
  }, [scrollY]);

  const goPreview = (delta) => setPreviewCursor(c => c + delta);
  // jump to an absolute index by the shortest signed delta from current
  const setPreviewTo = (i) => setPreviewCursor(c => {
    const cur = ((c % nPrev) + nPrev) % nPrev;
    let d = i - cur;
    if (d > nPrev / 2) d -= nPrev;
    if (d < -nPrev / 2) d += nPrev;
    return c + d;
  });
  const currentPreview = previews ? previews[previewIdx] : null;

  if (previews) {
    return (
      <section className="block presentation" ref={ref} data-screen-label={`02 Presentation · ${project.name}`}>
        <div className="container has-previews">
          <div className="prez-text">
            <div className="section-tag">
              <span className="num">02 /</span>
              <span className="bar"></span>
              <span>{T.presentation[lang]}</span>
            </div>
            <h2 className="section-title section-logo-title">
              <img src={project.logoMono} alt={project.name} className="section-logo" />
              <span className="visually-hidden">{project.name}</span>
            </h2>
            <p className="section-lede">{project.tagline[lang]}</p>

            <div className="demo-text" key={previewIdx}>
              <div className="demo-eyebrow">
                <span className="demo-num">{String(previewIdx + 1).padStart(2, '0')}</span>
                <span className="demo-bar"></span>
                <span className="demo-kind">{currentPreview.kind[lang]}</span>
              </div>
              <div className="demo-h">{currentPreview.h[lang]}</div>
              <div className="demo-d">{currentPreview.d[lang]}</div>
              {currentPreview.q && (
                <blockquote className="demo-q">« {currentPreview.q[lang]} »</blockquote>
              )}
            </div>
          </div>

          {(project.id === 'dialy' || project.id === 'wiccan') ? (
            <PhoneShowcase
              project={project}
              lang={lang}
              offset={offset}
              cursor={previewCursor}
              idx={previewIdx}
              setIdx={setPreviewTo}
              go={goPreview}
              tweaks={tweaks}
            />
          ) : (
            <LaptopShowcase
              project={project}
              lang={lang}
              offset={offset}
              idx={previewIdx}
              setIdx={setPreviewTo}
              go={goPreview}
            />
          )}
        </div>
      </section>
    );
  }

  return (
    <section className="block presentation" ref={ref} data-screen-label={`02 Presentation · ${project.name}`}>
      <div className="container">
        <div className="prez-text">
          <div className="section-tag">
            <span className="num">02 /</span>
            <span className="bar"></span>
            <span>{T.presentation[lang]}</span>
          </div>
          <h2 className="section-title section-logo-title">
            <img src={project.logoMono} alt={project.name} className="section-logo" />
            <span className="visually-hidden">{project.name}</span>
          </h2>
          <p className="section-lede">{project.tagline[lang]}</p>
          <p className="section-body">{project.description[lang]}</p>

          <div className="feature-list">
            {project.features.map((f,i) => (
              <div className="feature" key={i}>
                <span className="dia" aria-hidden="true"></span>
                <div className="ftext">
                  <div className="fhead">{f[lang].h}</div>
                  <div className="fdesc">{f[lang].d}</div>
                </div>
              </div>
            ))}
          </div>
        </div>

        <div className="device-stack" style={{ transform: `translateY(${offset}px)` }}>
          <div className="device d1">
            <div className="mini-bar"><i></i><i></i><i></i></div>
            <span className="corner">SCREEN · 01</span>
            <div className="device-body">
              <div>
                <div className="label">{project.name}</div>
                <div className="screen-sub">{project.captions.step[lang].toUpperCase()}</div>
              </div>
              <div className="meta">
                <div className="row"><span>01</span><span>FRAME · 01/06</span></div>
                <div className="row"><span>02</span><span>STATE · ACTIVE</span></div>
                <div className="row"><span>03</span><span>FLOW · GUIDED</span></div>
                <div className="row"><span>04</span><span>USER · YOU</span></div>
              </div>
            </div>
            <span className="caption">{project.captions.app[lang].toUpperCase()}</span>
          </div>

          <div className="device d2">
            <div className="mini-bar"><i></i><i></i><i></i></div>
            <span className="corner">SCREEN · 02</span>
            <div className="device-body">
              <div>
                <div className="label" style={{ fontSize: 14 }}>{project.captions.ocr[lang]}</div>
              </div>
              <div className="meta">
                <div className="row"><span>STEP 01</span><span>· · · 92%</span></div>
                <div className="row"><span>STEP 02</span><span>OK</span></div>
                <div className="row"><span>STEP 03</span><span>READY</span></div>
              </div>
            </div>
            <span className="caption">{project.captions.ocr[lang].toUpperCase()}</span>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ============ DEMO SHOWCASE — browser-chrome window with StaQ app + previews nav ============ */
function LaptopShowcase({ project, lang, offset, idx, setIdx, go }) {
  const previews = project.previews || [];
  const n = previews.length;
  const current = previews[idx];

  return (
    <div className="demo-stage" style={{ transform: `translateY(${offset}px)` }}>
      <div className="demo-window">
        <div className="demo-chrome" aria-hidden="true">
          <div className="chrome-dot" style={{ background: '#ff5f56' }}></div>
          <div className="chrome-dot" style={{ background: '#ffbd2e' }}></div>
          <div className="chrome-dot" style={{ background: '#27c93f' }}></div>
          <div className="chrome-url">app.{project.id}.fr · {current ? current.label[lang] : ''}</div>
        </div>

        <div className="demo-slides">
          {previews.map((p, i) => (
            <div className={"demo-slide" + (i === idx ? ' on' : '')} key={i} aria-hidden={i !== idx}>
              {i === 0 && project.id === 'staq' ? (
                <StaqPatchworkDemo active={i === idx} />
              ) : i === 1 && project.id === 'staq' ? (
                <StaqAppDemo active={i === idx} />
              ) : i === 2 && project.id === 'staq' ? (
                <StaqShareDemo active={i === idx} />
              ) : i === 3 && project.id === 'staq' ? (
                <StaqAgentsDemo active={i === idx} />
              ) : p.src ? (
                p.type === 'video' ? (
                  <video src={p.src} className="laptop-media" autoPlay={i === idx} muted loop playsInline />
                ) : (
                  <img src={p.src} alt={p.label[lang]} className="laptop-media" />
                )
              ) : (
                <div className="demo-slide-placeholder">
                  <span className="lp-kind">{p.kind[lang].toUpperCase()}</span>
                  <span className="lp-label">{p.label[lang]}</span>
                  <span className="lp-hint">{lang === 'fr' ? 'Démo à venir' : 'Demo coming soon'}</span>
                </div>
              )}
            </div>
          ))}
        </div>
      </div>

      <PreviewNav lang={lang} idx={idx} n={n} current={current} setIdx={setIdx} go={go} />
    </div>
  );
}

/* ============ PHONE CAROUSEL — 3-up phone carousel (center full, sides 50%/75%) ============ */
/* phone size adapts to the viewport: smaller phones, tighter spacing and a shorter stage on narrow screens */
function usePhoneMetrics(tweaks) {
  const [vw, setVw] = useState(typeof window !== 'undefined' ? window.innerWidth : 1280);
  useEffect(() => {
    const onResize = () => setVw(window.innerWidth);
    window.addEventListener('resize', onResize);
    return () => window.removeEventListener('resize', onResize);
  }, []);
  const base = tweaks ? tweaks.phoneWidth : 300;
  const gap = tweaks ? tweaks.carouselGap : 232;
  const small = vw <= 900;
  const w = small ? Math.round(Math.min(base, Math.max(150, vw * 0.46))) : base;
  return { w, shift: gap * (w / base), h: small ? Math.round(w * 2.12 + 56) : 680 };
}

function PhoneShowcase({ project, lang, offset, cursor, idx, setIdx, go, tweaks }) {
  const previews = project.previews || [];
  const n = previews.length;
  const current = previews[idx];
  const sideScale = tweaks ? tweaks.sideScale : 0.5;
  const sideOpacity = tweaks ? tweaks.sideOpacity : 0.75;
  const metrics = usePhoneMetrics(tweaks);
  const touchX = useRef(null);

  // render 5 slots centered on cursor so the entering phone slides in from the far side
  const SHIFT = metrics.shift; // px between adjacent phone slots
  const slots = [];
  for (let s = cursor - 2; s <= cursor + 2; s++) {
    const i = ((s % n) + n) % n;
    slots.push({ slot: s, p: previews[i], rel: s - cursor, i });
  }

  const onTouchStart = (e) => { touchX.current = e.touches[0].clientX; };
  const onTouchEnd = (e) => {
    if (touchX.current == null) return;
    const dx = e.changedTouches[0].clientX - touchX.current;
    touchX.current = null;
    if (Math.abs(dx) > 40) go(dx < 0 ? 1 : -1);
  };

  return (
    <div className="demo-stage phone-stage" style={{ transform: `translateY(${offset}px)` }}>
      <div
        className="phone-carousel"
        style={{ '--phone-w': metrics.w + 'px', '--carousel-h': metrics.h + 'px' }}
        onTouchStart={onTouchStart}
        onTouchEnd={onTouchEnd}
      >
        {slots.map(({ slot, p, rel, i }) => {
          const abs = Math.abs(rel);
          const isCenter = rel === 0;
          const visible = abs <= 1;
          return (
            <div
              key={slot}
              className={"phone" + (isCenter ? " is-center" : "")}
              style={{
                transform: `translate(calc(-50% + ${rel * SHIFT}px), -50%) scale(${isCenter ? 1 : sideScale}) rotateY(${rel * -16}deg)`,
                opacity: visible ? (isCenter ? 1 : sideOpacity) : 0,
                zIndex: isCenter ? 3 : (abs === 1 ? 2 : 1),
                pointerEvents: isCenter ? 'auto' : 'none',
              }}
              aria-hidden={!isCenter}
            >
              <PhoneFrame project={project} preview={p} lang={lang} index={i} active={isCenter} />
            </div>
          );
        })}
      </div>

      <PreviewNav lang={lang} idx={idx} n={n} current={current} setIdx={setIdx} go={go} />
    </div>
  );
}

function PhoneFrame({ project, preview, lang, index, active }) {
  const vidRef = useRef(null);
  const frameRef = useRef(null);
  const wrapRef = useRef(null);
  const [scale, setScale] = useState(0.76);
  const isVideo = preview && preview.src && preview.type === 'video';
  const isHtml = preview && preview.src && preview.type === 'html';

  useEffect(() => {
    const v = vidRef.current;
    if (!v) return;
    if (active) {
      v.play().catch(() => {});
    } else {
      v.pause();
      v.currentTime = 0;
    }
  }, [active, isVideo, preview && preview.src]);

  // html demo: fit a 370px wide screen to the phone, and tell it whether it is the centre phone
  useLayoutEffect(() => {
    const el = wrapRef.current;
    if (!el || !isHtml) return;
    const fit = () => setScale(el.clientWidth / 370);
    fit();
    const ro = new ResizeObserver(fit);
    ro.observe(el);
    return () => ro.disconnect();
  }, [isHtml]);
  const tell = () => {
    const f = frameRef.current;
    if (f && f.contentWindow) f.contentWindow.postMessage({ wiccanDemo: active ? 'active' : 'idle' }, '*');
  };
  useEffect(() => { if (isHtml) tell(); }, [active, isHtml]);

  return (
    <div className="phone-frame">
      <span className="phone-notch" aria-hidden="true"></span>
      <div className="phone-screen" ref={wrapRef} style={isHtml ? { aspectRatio: '370 / 780' } : undefined}>
        {preview && preview.src ? (
          isHtml ? (
            <iframe
              ref={frameRef}
              src={preview.src}
              title={preview.label[lang]}
              className="phone-embed"
              style={{ transform: `scale(${scale})` }}
              onLoad={tell}
              tabIndex={active ? 0 : -1}
            />
          ) : preview.type === 'video' ? (
            <video ref={vidRef} src={preview.src} className="phone-media" muted loop playsInline preload="metadata" />
          ) : (
            <img src={preview.src} alt={preview.label[lang]} className="phone-media" />
          )
        ) : (
          <div className="demo-slide-placeholder phone-placeholder">
            <span className="lp-kind">{preview.kind[lang].toUpperCase()}</span>
            <span className="lp-label">{preview.label[lang]}</span>
            <span className="lp-hint">{lang === 'fr' ? 'Démo à venir' : 'Demo coming soon'}</span>
          </div>
        )}
      </div>
    </div>
  );
}

/* shared preview navigation row (arrows + counter + dots) */
function PreviewNav({ lang, idx, n, current, setIdx, go }) {
  return (
    <div className="laptop-nav" role="group" aria-label={lang === 'fr' ? 'Navigation des aperçus' : 'Preview navigation'}>
      <button type="button" className="ln-arrow" onClick={() => go(-1)} aria-label={T.prev[lang]}>
        <span className="diamond"></span>
        <span className="glyph" aria-hidden="true">‹</span>
      </button>

      <div className="ln-readout">
        <div className="ln-counter">
          <span className="ln-curr">{String(idx + 1).padStart(2, '0')}</span>
          <span className="ln-sep">/</span>
          <span className="ln-total">{String(n).padStart(2, '0')}</span>
        </div>
        <div className="ln-meta">
          <span className="ln-kind">{current ? current.kind[lang] : ''}</span>
          <span className="ln-dot"></span>
          <span className="ln-label">{current ? current.label[lang] : ''}</span>
        </div>
        <div className="ln-dots" role="tablist">
          {Array.from({ length: n }).map((_, i) => (
            <button
              key={i}
              role="tab"
              aria-selected={i === idx}
              aria-label={(lang === 'fr' ? 'Aperçu ' : 'Preview ') + (i + 1)}
              className={"ln-dot-btn" + (i === idx ? ' on' : '')}
              onClick={() => setIdx(i)}
            ></button>
          ))}
        </div>
      </div>

      <button type="button" className="ln-arrow" onClick={() => go(+1)} aria-label={T.next[lang]}>
        <span className="diamond"></span>
        <span className="glyph" aria-hidden="true">›</span>
      </button>
    </div>
  );
}

/* ============ TECHNICAL — animated circle diagram with hover descriptions ============ */
function Technical({ project, lang, scrollY }) {
  const ref = useRef(null);
  const [offset, setOffset] = useState(0);
  const [hover, setHover] = useState(null); // index of hovered satellite, or null
  const [visible, setVisible] = useState(false);

  useEffect(() => {
    if (!ref.current) return;
    const rect = ref.current.getBoundingClientRect();
    const center = rect.top + rect.height / 2 - window.innerHeight / 2;
    setOffset(Math.max(-50, Math.min(50, -center * 0.07)));
    if (rect.top < window.innerHeight * 0.7 && !visible) setVisible(true);
  }, [scrollY]);

  // clear hover when project changes
  useEffect(() => setHover(null), [project.id]);

  const nodes = project.techNodes;
  const active = hover !== null ? nodes[hover] : null;

  // Adaptive vars for the "Technical" section only (allows light section under dark hero etc.)
  const techVars = useMemo(() => {
    if (!project.techBg) return null;
    const t = project.techText || project.text;
    return {
      '--bg-alt': project.techBg,
      '--text': t,
      '--text-muted': hexToRgba(t, 0.62),
      '--text-faint': hexToRgba(t, 0.32),
      '--line': hexToRgba(t, 0.10),
      '--line-strong': hexToRgba(t, 0.22),
      '--accent': project.techAccent || project.accent,
    };
  }, [project.id]);

  return (
    <section className="block technical" ref={ref} data-screen-label={`03 Technical · ${project.name}`} style={techVars || undefined}>
      <div className="tech-grid">
        <div className="tech-text">
          <div className="section-tag">
            <span className="num">03 /</span>
            <span className="bar"></span>
            <span>{T.technique[lang]}</span>
          </div>
          <h2 className="section-title" style={{ whiteSpace: 'pre-line' }}>{T.techCoreTitle[lang]}</h2>
          <p className="section-lede">{T.techniqueLede[lang]}</p>
          <p className="section-body">{project.techIntro[lang]}</p>

          <div className="tech-detail">
            <div className="td-label">{T.techHint[lang]}</div>
            <div className={"td-card" + (active ? " on" : "")}>
              <div className="td-name">{active ? active.name : project.name}</div>
              <div className="td-desc">{active ? active.d[lang] : project.description[lang]}</div>
            </div>
          </div>
        </div>

        <div className={"circles-wrap" + (visible ? " in" : "")} style={{ transform: `translateY(${offset}px)` }}>
          <CirclesDiagram project={project} nodes={nodes} hover={hover} setHover={setHover} />
        </div>
      </div>
    </section>
  );
}

function CirclesDiagram({ project, nodes, hover, setHover }) {
  const count = nodes.length;
  return (
    <div className="circles-diagram">
      {/* faint rings */}
      <div className="ring r1" aria-hidden="true"></div>
      <div className="ring r2" aria-hidden="true"></div>
      <div className="ring r3" aria-hidden="true"></div>

      {/* connection lines */}
      <svg className="circles-lines" viewBox="0 0 400 400" preserveAspectRatio="xMidYMid meet" aria-hidden="true">
        {nodes.map((_, i) => {
          const a = (i / count) * Math.PI * 2 - Math.PI / 2;
          const r = 150;
          const x = 200 + Math.cos(a) * r;
          const y = 200 + Math.sin(a) * r;
          const isHover = hover === i;
          return (
            <line
              key={i}
              x1={200} y1={200} x2={x} y2={y}
              stroke={isHover ? "var(--accent)" : "var(--line-strong)"}
              strokeWidth={isHover ? 1.4 : 1}
              strokeDasharray={isHover ? "0" : "2 5"}
              style={{ transition: 'stroke 250ms, stroke-dasharray 250ms, stroke-width 250ms' }}
            />
          );
        })}
      </svg>

      {/* central node */}
      <div className="circle-center">
        <div className="cc-inner">
          <span className="cc-name">{project.name}</span>
          <span className="cc-sub">CORE</span>
        </div>
      </div>

      {/* satellites */}
      {nodes.map((n, i) => {
        const a = (i / count) * Math.PI * 2 - Math.PI / 2;
        const r = 38; // % of container
        const x = 50 + Math.cos(a) * r;
        const y = 50 + Math.sin(a) * r;
        const isHover = hover === i;
        return (
          <button
            key={n.name}
            type="button"
            className={"circle-node" + (isHover ? " on" : "")}
            style={{
              left: `${x}%`, top: `${y}%`,
              animationDelay: (i * 0.5) + 's',
            }}
            onMouseEnter={() => setHover(i)}
            onMouseLeave={() => setHover(null)}
            onFocus={() => setHover(i)}
            onBlur={() => setHover(null)}
            aria-label={n.name}
          >
            <span className="cn-label">{n.name}</span>
          </button>
        );
      })}
    </div>
  );
}

/* ============ FOOTER ============ */
function Footer({ project, lang }) {
  return (
    <footer data-screen-label="04 Footer">
      <div className="foot-grid">
        <div className="foot-brand">
          <div className="tag">{lang === 'fr'
            ? 'Donner à chacun les outils de ses ambitions.'
            : 'Giving everyone the tools for their ambitions.'}</div>
          <div className="who">Thibaut Filliat · {T.role[lang]}</div>
        </div>

        <div className="foot-col">
          <h4>{T.contact[lang]}</h4>
          <a className="foot-link" href="mailto:filliat.t@gmail.com">
            <span>filliat.t@gmail.com</span><span className="arr">→</span>
          </a>
          <a className="foot-link" href="https://linkedin.com/in/thibaut-filliat" target="_blank" rel="noreferrer">
            <span>LinkedIn</span><span className="arr">→</span>
          </a>
          <a className="foot-link" href="https://github.com/thibaut-filliat" target="_blank" rel="noreferrer">
            <span>GitHub</span><span className="arr">→</span>
          </a>
        </div>

        <div className="foot-col">
          <h4>{T.index[lang]}</h4>
          {PROJECTS.map((p,i) => (
            <a className="foot-link" key={p.id} href="#top">
              <span>{String(i+1).padStart(2,'0')} · {p.name}</span><span className="arr">↗</span>
            </a>
          ))}
        </div>
      </div>

      <div className="foot-bottom">
        <div className="ind">
          <span className="pulse-dot" aria-hidden="true"></span>
          <span>{T.available[lang]}</span>
        </div>
        <span>© 2026 Thibaut Filliat — {T.rights[lang]}</span>
        <span>{T.craftedIn[lang]}</span>
      </div>
    </footer>
  );
}

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