// dib — section components (Hero rebuilt per §3 of design.md)
const { useEffect, useRef, useState } = React;

/* ─── Shared atoms ─────────────────────────────────────────────────────────── */

function Logo() {
  return (
    <img src="dib_solo.png" alt="dib" width="28" height="28"
         style={{ objectFit: 'contain', display: 'block' }} />
  );
}

function Arrow({ size = 16 }) {
  return (
    <svg className="arrow" width={size} height={size} viewBox="0 0 16 16" fill="none">
      <path d="M3 8h10M9 4l4 4-4 4" stroke="currentColor" strokeWidth="1.5"
            strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

/* ─── DIB Cube Lattice (canvas — ported from DIB Cube Lattice.html) ───────── */

function CubeLattice() {
  const canvasRef = useRef(null);

  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext('2d');
    let w = 0, h = 0, raf;
    const dpr = Math.min(window.devicePixelRatio || 1, 2);

    const resize = () => {
      const r = canvas.getBoundingClientRect();
      w = r.width;  h = r.height;
      canvas.width  = w * dpr;
      canvas.height = h * dpr;
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
    };
    resize();
    window.addEventListener('resize', resize);

    /* ── geometry ───────────────────────────────────────────────────── */
    const CUBE_HALF = 0.45;
    const cubeVerts = [
      [-1,-1,-1],[1,-1,-1],[1,1,-1],[-1,1,-1],
      [-1,-1, 1],[1,-1, 1],[1,1, 1],[-1,1, 1],
    ].map(v => v.map(c => c * CUBE_HALF));
    const cubeEdges = [
      [0,1],[1,2],[2,3],[3,0],
      [4,5],[5,6],[6,7],[7,4],
      [0,4],[1,5],[2,6],[3,7],
    ];

    const GRID = 3, STEP = 1.5;
    const cubes = [];
    for (let x = 0; x < GRID; x++)
      for (let y = 0; y < GRID; y++)
        for (let z = 0; z < GRID; z++)
          cubes.push({
            p: [
              (x - (GRID - 1) / 2) * STEP,
              (y - (GRID - 1) / 2) * STEP,
              (z - (GRID - 1) / 2) * STEP,
            ],
            active: Math.random() < 0.18,
            phase:  Math.random() * Math.PI * 2,
            speed:  0.4 + Math.random() * 0.6,
          });

    /* ── helpers ────────────────────────────────────────────────────── */
    const FOCAL = 5.5;
    const project = (x, y, z, cx, cy) => {
      const f = FOCAL / (FOCAL + z);
      return [cx + x * f * 94, cy + y * f * 94, f];
    };
    const rotate = ([x, y, z], rx, ry) => {
      const cy0 = Math.cos(rx), sy0 = Math.sin(rx);
      let ny = y * cy0 - z * sy0, nz = y * sy0 + z * cy0;
      y = ny; z = nz;
      const cx0 = Math.cos(ry), sx0 = Math.sin(ry);
      let nx = x * cx0 + z * sx0; nz = -x * sx0 + z * cx0;
      return [nx, y, nz];
    };

    const getAccent = () =>
      getComputedStyle(document.documentElement).getPropertyValue('--accent').trim() || '#22e3ff';
    const motionSpeed = () =>
      document.body.classList.contains('motion-low')  ? 0.35 :
      document.body.classList.contains('motion-high') ? 1.8  : 1;

    const start = performance.now();

    const tick = (now) => {
      const t  = (now - start) / 1000;
      const sp = motionSpeed();
      const cx = w / 2, cy = h / 2;
      const rx = Math.sin(t * 0.18 * sp) * 0.45 + 0.55;
      const ry = t * 0.18 * sp;

      ctx.clearRect(0, 0, w, h);

      const accent  = getAccent();
      const lineCol = '#a1a1aa';
      const glowMul = 0.65;

      const items = cubes
        .map(c => ({ c, rp: rotate(c.p, rx, ry) }))
        .sort((a, b) => b.rp[2] - a.rp[2]);

      for (const { c, rp } of items) {
        const pulse = c.active
          ? 0.6 + 0.4 * Math.sin(t * c.speed * 2 * sp + c.phase)
          : 0;
        ctx.lineWidth = c.active ? 1.2 : 0.7;

        for (const [a, b] of cubeEdges) {
          const va = rotate([c.p[0]+cubeVerts[a][0], c.p[1]+cubeVerts[a][1], c.p[2]+cubeVerts[a][2]], rx, ry);
          const vb = rotate([c.p[0]+cubeVerts[b][0], c.p[1]+cubeVerts[b][1], c.p[2]+cubeVerts[b][2]], rx, ry);
          const [ax, ay, af] = project(va[0], va[1], va[2], cx, cy);
          const [bx, by, bf] = project(vb[0], vb[1], vb[2], cx, cy);
          const depth     = (af + bf) / 2;
          const baseAlpha = Math.max(0.05, Math.min(1, (depth - 0.6) * 1.4));

          if (c.active) {
            ctx.strokeStyle  = accent;
            ctx.globalAlpha  = baseAlpha * (0.4 + pulse * 0.6);
            ctx.shadowColor  = accent;
            ctx.shadowBlur   = 14 * glowMul * pulse;
          } else {
            ctx.strokeStyle = lineCol;
            ctx.globalAlpha = baseAlpha * 0.35;
            ctx.shadowBlur  = 0;
          }
          ctx.beginPath();
          ctx.moveTo(ax, ay);
          ctx.lineTo(bx, by);
          ctx.stroke();
        }

        if (c.active) {
          const [cpx, cpy] = project(rp[0], rp[1], rp[2], cx, cy);
          ctx.globalAlpha = 0.6 + pulse * 0.4;
          ctx.fillStyle   = accent;
          ctx.shadowColor = accent;
          ctx.shadowBlur  = 20 * glowMul;
          ctx.beginPath();
          ctx.arc(cpx, cpy, 2 + pulse * 1.6, 0, Math.PI * 2);
          ctx.fill();
        }
      }

      ctx.globalAlpha = 1;
      ctx.shadowBlur  = 0;

      /* central reticle */
      const accent2 = getAccent();
      ctx.strokeStyle = accent2;
      ctx.globalAlpha = 0.5;
      ctx.lineWidth   = 1;
      ctx.beginPath();
      ctx.moveTo(cx - 14, cy); ctx.lineTo(cx - 4,  cy);
      ctx.moveTo(cx +  4, cy); ctx.lineTo(cx + 14, cy);
      ctx.moveTo(cx, cy - 14); ctx.lineTo(cx, cy -  4);
      ctx.moveTo(cx, cy +  4); ctx.lineTo(cx, cy + 14);
      ctx.stroke();
      ctx.globalAlpha = 1;

      raf = requestAnimationFrame(tick);
    };

    /* respect prefers-reduced-motion */
    if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
      tick(performance.now()); // single static frame
    } else {
      raf = requestAnimationFrame(tick);
    }

    return () => { cancelAnimationFrame(raf); window.removeEventListener('resize', resize); };
  }, []);

  return (
    <div className="cube-lattice" aria-hidden="true">
      <canvas ref={canvasRef} className="cube-lattice__canvas" />
      <div className="cube-lattice__vignette" />
    </div>
  );
}

/* ─── Drift Constellation (behind cube) ────────────────────────────────────── */

function DriftConstellation() {
  const canvasRef  = useRef(null);
  const instanceRef = useRef(null);

  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas || !window.SubtleFX) return;

    const getAccent = () =>
      getComputedStyle(document.documentElement).getPropertyValue('--accent').trim() || '#22e3ff';

    const motionSpeed = () =>
      document.body.classList.contains('motion-low')  ? 0.35 :
      document.body.classList.contains('motion-high') ? 1.8  : 1;

    const start = (accent) => {
      if (instanceRef.current) { instanceRef.current.stop(); instanceRef.current = null; }
      instanceRef.current = window.SubtleFX.driftConstellation(canvas, {
        accent,
        muted:    '#3a3a4a',
        count:    160,
        linkDist: 110,
        seed:     0.73,
      });
    };

    /* prefers-reduced-motion: render one static frame, no loop */
    if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;

    start(getAccent());

    /* restart when --accent CSS variable changes (set by applyTweaks in dib-app.jsx) */
    const mo = new MutationObserver(() => start(getAccent()));
    mo.observe(document.documentElement, { attributes: true, attributeFilter: ['style'] });

    return () => {
      if (instanceRef.current) { instanceRef.current.stop(); instanceRef.current = null; }
      mo.disconnect();
    };
  }, []);

  return (
    <canvas ref={canvasRef} className="hero__drift" aria-hidden="true" />
  );
}

/* ─── Hero ─────────────────────────────────────────────────────────────────── */

function Hero({ t }) {
  return (
    <section className="hero">
      <div className="hero__bg-glow" aria-hidden="true" />
      <DriftConstellation />
      <CubeLattice />
      <div className="container hero__inner">
        <div className="reveal in"><span className="eyebrow">{t.hero.eyebrow}</span></div>
        <h1 className="display hero__h1">
          <span className="hero__h1-l1 reveal in delay-1">{t.hero.title_1}</span>
          <span className="hero__h1-l2 reveal in delay-2">
            {t.hero.title_2} <em className="hero__h1-l3">{t.hero.title_accent}</em>
          </span>
        </h1>
        <p className="hero__sub reveal in delay-2">{t.hero.sub}</p>
        <div className="hero__cta-row reveal in delay-3">
          <a href="#products" className="btn btn--primary">{t.hero.cta_primary} <Arrow /></a>
        </div>
        <div className="hero__meta reveal in delay-4">
          {[
            { label: 'Expertise',  value: 'XR · 3D · Web · AI'     },
            { label: 'Core Stack', value: 'Unity · Unreal · Python' },
            { label: 'Use Cases',  value: 'Training · Art · Sim'    },
            { label: 'Focus',      value: 'Shaping the Future'      },
          ].map(({ label, value }) => (
            <div key={label} className="hero__meta-item">
              <div className="hero__meta-label">{label}</div>
              <div className="hero__meta-value">{value}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ─── Products ─────────────────────────────────────────────────────────────── */

/** Maps product names to product page URL parameter IDs */
const PRODUCT_NAME_TO_ID = {
  'Medisync VR':       'medisyncvr',
  'ParticleMotion':    'particlemotion',
  'ARchitect':         'architect',
  'SkyPilot Simulator':'skypilot',
};

function ProductCard({ p, idx }) {
  const idxStr   = String(idx + 1).padStart(2, '0');
  const cap      = `// ${p.name.toUpperCase().replace(/\s+/g, '.')}`;
  const projectId = PRODUCT_NAME_TO_ID[p.name];

  return (
    <article className="product reveal">
      <div className="product__top">
        <span className="product__index mono">{idxStr} / 04</span>
        <span className="product__tag">{p.tag}</span>
      </div>
      <div className="product__visual" data-caption={cap}>
        <div className="product__visual-glow"></div>
      </div>
      <h3>{p.name}<br /><span className="grad">{p.grad}</span></h3>
      <p>{p.body}</p>
      <div className="product__feat">{p.feat.map(f => <span key={f}>{f}</span>)}</div>
      <div className="product__actions">
        {projectId && (
          <a
            href={`product.html?project=${projectId}`}
            className="btn btn--show-more"
            aria-label={`View ${p.name} product page`}
          >
            Show More <Arrow size={16} />
          </a>
        )}
      </div>
    </article>
  );
}

function Products({ t }) {
  return (
    <section id="products">
      <div className="container">
        <div className="sec-head">
          <div className="reveal">
            <span className="eyebrow">{t.products.eyebrow}</span>
            <h2>{t.products.title}</h2>
          </div>
          <p className="reveal delay-1">{t.products.lede}</p>
        </div>
        <div className="products">
          {t.products.items.map((p, i) => <ProductCard key={p.name} p={p} idx={i} />)}
        </div>
      </div>
    </section>
  );
}

/* ─── About ────────────────────────────────────────────────────────────────── */

function About({ t }) {
  return (
    <section id="about">
      <div className="container">
        <div className="sec-head">
          <div className="reveal">
            <span className="eyebrow">{t.about.eyebrow}</span>
            <h2>{t.about.title}</h2>
          </div>
          <p className="reveal delay-1">{t.about.lede}</p>
        </div>
      </div>
      <div className="about-grid">
        {t.about.items.map((a, i) => (
          <div key={i} className={`about-block reveal delay-${i + 1}`}>
            <span className="about-block__num">{String(i + 1).padStart(2, '0')}</span>
            <h3>{a.title}</h3>
            <p>{a.body}</p>
          </div>
        ))}
      </div>
    </section>
  );
}

/* ─── Process ──────────────────────────────────────────────────────────────── */

function Process({ t }) {
  return (
    <section id="process" className="process">
      <div className="container">
        <div className="sec-head">
          <div className="reveal">
            <span className="eyebrow">{t.process.eyebrow}</span>
            <h2>{t.process.title}</h2>
          </div>
          <p className="reveal delay-1">{t.process.lede}</p>
        </div>
        <div className="process__list">
          {t.process.items.map((p, i) => (
            <div key={i} className={`process__row reveal delay-${i + 1}`}>
              <span className="num">{String(i + 1).padStart(2, '0')}</span>
              <h4>{p.t}</h4>
              <p>{p.d}</p>
              <span className="dur">{p.dur}</span>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ─── Tech Stack ───────────────────────────────────────────────────────────── */

const TILE_LAYOUT = [
  { size: 'lg',   shape: 'ring'     },
  { size: 'wide', shape: 'bars'     },
  { size: 'wide', shape: 'wave'     },
  { size: 'sm',   shape: 'dots'     },
  { size: 'sm',   shape: 'triangle' },
  { size: 'sm',   shape: 'grid'     },
  { size: 'md',   shape: 'cube'     },
  { size: 'md',   shape: 'hex'      },
  { size: 'md',   shape: 'stack'    },
];

function TechStack({ t }) {
  return (
    <section id="tech">
      <div className="container">
        <div className="sec-head">
          <div className="reveal">
            <span className="eyebrow">{t.tech.eyebrow}</span>
            <h2>{t.tech.title}</h2>
          </div>
          <p className="reveal delay-1">{t.tech.lede}</p>
        </div>
        <div className="bento">
          {t.tech.items.map((it, i) => {
            const layout = TILE_LAYOUT[i] || TILE_LAYOUT[0];
            return (
              <div key={it.name} className={`tile tile--${layout.size} reveal delay-${(i % 4) + 1}`}>
                <div>
                  <div className="kind">{it.kind}</div>
                  <h4 style={{ marginTop: 8 }}>{it.name}</h4>
                  <p>{it.body}</p>
                </div>
                <div className={`tile__shape tile__shape--${layout.shape}`}></div>
              </div>
            );
          })}
        </div>
      </div>
    </section>
  );
}

/* ─── FAQ ──────────────────────────────────────────────────────────────────── */

function FAQ({ t }) {
  const [open, setOpen] = useState(0);
  return (
    <section id="faq">
      <div className="container">
        <div className="sec-head">
          <div className="reveal">
            <span className="eyebrow">{t.faq.eyebrow}</span>
            <h2>{t.faq.title}</h2>
          </div>
          <p className="reveal delay-1">{t.faq.lede}</p>
        </div>
        <div className="faq reveal">
          {t.faq.items.map((f, i) => (
            <div key={i} className={`faq__item ${open === i ? 'open' : ''}`}>
              <button className="faq__q" onClick={() => setOpen(open === i ? -1 : i)}>
                <span className="faq__q-text">{f.q}</span>
                <span className="faq__icon">
                  <svg width="12" height="12" viewBox="0 0 12 12" fill="none">
                    <path d="M6 2v8M2 6h8" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
                  </svg>
                </span>
              </button>
              <div className="faq__a">{f.a}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ─── Footer ───────────────────────────────────────────────────────────────── */

function Footer({ t }) {
  return (
    <footer id="footer">
      <div className="container">
        <div className="footer__grid">
          <div className="footer__brand">
            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <Logo /> Digital Immersive Box
            </div>
            <p>{t.footer.tagline}</p>
          </div>
          <div className="footer__col">
            <h5>{t.footer.studio}</h5>
            <a href="#about"   >{t.nav.about   }</a>
            <a href="#process" >{t.nav.process  }</a>
            <a href="#products">{t.nav.products }</a>
            <a href="#faq"     >{t.nav.faq      }</a>
          </div>
          <div className="footer__col">
            <h5>{t.footer.contact}</h5>
            <a href="mailto:hello@digitalimmersivebox.com">hello@digitalimmersivebox.com</a>
            <span>+40 752 931 873</span>
            <span>Cluj-Napoca · RO</span>
          </div>
          <div className="footer__col">
            <h5>{t.footer.elsewhere}</h5>
            <a href="#">Twitter / X</a>
            <a href="#">LinkedIn</a>
            <a href="#">Instagram</a>
            <a href="#">YouTube</a>
          </div>
        </div>
        <div className="footer__bottom">
          <span>{t.footer.copy}</span>
          <span>{t.footer.motto}</span>
        </div>
      </div>
    </footer>
  );
}

/* ─── Nav ──────────────────────────────────────────────────────────────────── */

function Nav({ t, tweaks, setTweak, langs, presets }) {
  const [langOpen,   setLangOpen]   = useState(false);
  const [appearOpen, setAppearOpen] = useState(false);
  const langRef   = useRef(null);
  const appearRef = useRef(null);

  useEffect(() => {
    const onDoc = e => {
      if (langRef.current   && !langRef.current.contains(e.target))   setLangOpen(false);
      if (appearRef.current && !appearRef.current.contains(e.target)) setAppearOpen(false);
    };
    document.addEventListener('mousedown', onDoc);
    return () => document.removeEventListener('mousedown', onDoc);
  }, []);

  const currentLang  = langs.find(l => l.value === tweaks.language) || langs[0];
  const currentColor = tweaks.accent === 'custom'
    ? tweaks.customColor
    : (presets[tweaks.accent] || presets.cyan);
  const isLight = tweaks.theme === 'light';
  const toggleTheme = () => setTweak('theme', isLight ? 'dark' : 'light');

  return (
    <nav className="nav">
      <a href="#" className="nav__logo">
        <span className="nav__mark"><Logo /></span>
        Digital Immersive Box
      </a>
      <div className="nav__links">
        <a href="#products">{t.nav.products}</a>
        <a href="#about"   >{t.nav.about   }</a>
        <a href="#process" >{t.nav.process  }</a>
        <a href="#tech"    >{t.nav.tech     }</a>
        <a href="#faq"     >{t.nav.faq      }</a>
        <a href="Articles.html">{t.nav.journal  }</a>
      </div>

      <div className="nav__right">
        {/* Appearance — theme + accent consolidated */}
        <div className="nav__pop" ref={appearRef}>
          <button
            className="nav__icon-btn nav__icon-btn--appear"
            onClick={() => { setAppearOpen(o => !o); setLangOpen(false); }}
            aria-label="Appearance" aria-expanded={appearOpen}
          >
            <span className={`nav__theme-icon ${isLight ? 'is-light' : 'is-dark'}`}>
              {isLight ? (
                <svg width="14" height="14" viewBox="0 0 16 16" fill="none">
                  <path d="M13 9.5A5.5 5.5 0 0 1 6.5 3a5.5 5.5 0 1 0 6.5 6.5z" fill="currentColor"/>
                </svg>
              ) : (
                <svg width="14" height="14" viewBox="0 0 16 16" fill="none">
                  <circle cx="8" cy="8" r="3" fill="currentColor"/>
                  <g stroke="currentColor" strokeWidth="1.4" strokeLinecap="round">
                    <line x1="8" y1="1" x2="8" y2="3"/>
                    <line x1="8" y1="13" x2="8" y2="15"/>
                    <line x1="1" y1="8" x2="3" y2="8"/>
                    <line x1="13" y1="8" x2="15" y2="8"/>
                    <line x1="3" y1="3" x2="4.4" y2="4.4"/>
                    <line x1="11.6" y1="11.6" x2="13" y2="13"/>
                    <line x1="3" y1="13" x2="4.4" y2="11.6"/>
                    <line x1="11.6" y1="4.4" x2="13" y2="3"/>
                  </g>
                </svg>
              )}
            </span>
            <span className="nav__color-dot" style={{ background: currentColor }}></span>
          </button>
          {appearOpen && (
            <div className="nav__menu nav__menu--appear">
              <div className="nav__theme-row">
                <span className="nav__appear-label">Theme</span>
                <div className="nav__theme-btns">
                  <button
                    className={`nav__theme-opt ${!isLight ? 'on' : ''}`}
                    onClick={() => setTweak('theme', 'dark')}
                  >Dark</button>
                  <button
                    className={`nav__theme-opt ${isLight ? 'on' : ''}`}
                    onClick={() => setTweak('theme', 'light')}
                  >Light</button>
                </div>
              </div>
              <div className="nav__swatches">
                {Object.entries(presets).map(([key, color]) => (
                  <button
                    key={key}
                    className={`nav__swatch ${tweaks.accent === key ? 'on' : ''}`}
                    style={{
                      background: color,
                      boxShadow: tweaks.accent === key
                        ? `0 0 0 2px var(--bg-2), 0 0 0 4px ${color}` : undefined,
                    }}
                    onClick={() => setTweak('accent', key)}
                    aria-label={key} title={key}
                  />
                ))}
              </div>
              <label className="nav__custom">
                <span>{t.tweaks.custom}</span>
                <input
                  type="color"
                  value={tweaks.customColor}
                  onChange={e => setTweak({ accent: 'custom', customColor: e.target.value })}
                />
                <span className="nav__custom-hex">{tweaks.customColor}</span>
              </label>
              <div className="nav__glow-row">
                <span>{t.tweaks.glow}</span>
                <input
                  type="range"
                  className="nav__glow-slider"
                  min="0" max="100" step="1"
                  value={tweaks.glowIntensity ?? 35}
                  onChange={e => setTweak('glowIntensity', Number(e.target.value))}
                />
                <span className="nav__glow-val">{tweaks.glowIntensity ?? 35}%</span>
              </div>
            </div>
          )}
        </div>

        {/* Language */}
        <div className="nav__pop" ref={langRef}>
          <button
            className="nav__icon-btn"
            onClick={() => { setLangOpen(o => !o); setAppearOpen(false); }}
            aria-label="Language" aria-expanded={langOpen}
          >
            <span className="nav__flag">{currentLang.flag}</span>
            <span className="nav__code">{currentLang.value.toUpperCase()}</span>
            <svg width="10" height="10" viewBox="0 0 10 10">
              <path d="M2 4l3 3 3-3" stroke="currentColor" strokeWidth="1.4" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </button>
          {langOpen && (
            <div className="nav__menu">
              {langs.map(l => (
                <button
                  key={l.value}
                  className={`nav__menu-item ${tweaks.language === l.value ? 'on' : ''}`}
                  onClick={() => { setTweak('language', l.value); setLangOpen(false); }}
                >
                  <span className="nav__flag">{l.flag}</span>
                  <span>{l.label}</span>
                  <span className="nav__menu-code">{l.value.toUpperCase()}</span>
                </button>
              ))}
            </div>
          )}
        </div>

        <a href="contact.html" className="nav__cta">{t.nav.cta}</a>
      </div>
    </nav>
  );
}

Object.assign(window, { Nav, Hero, Products, About, Process, TechStack, FAQ, Footer });
