// ============================================================
// PAGE — Tecnologia
// Hero + Filosofia + 4-layer architecture + stack tecnico + sicurezza + CTA
// ============================================================
const { useState: useStateTC, useRef: useRefTC, useEffect: useEffectTC } = React;
const motionTC = new Proxy({}, { get: (_, p) => window.FramerMotion.motion[p] });
const useInViewTC = (...a) => window.FramerMotion.useInView(...a);

// ============================================================
// TECH HUD — sfondo olografico stile sci-fi (sfera wireframe + reticoli)
// Originale, generico, low-impact 3D via canvas 2D
// ============================================================
function TechHUD() {
  const canvasRef = useRefTC(null);
  const wrapRef = useRefTC(null);
  const animRef = useRefTC(null);
  const mouseRef = useRefTC({ x: 0.5, y: 0.5, target: { x: 0.5, y: 0.5 } });
  const tRef = useRefTC(0);

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

    const resize = () => {
      const rect = wrap.getBoundingClientRect();
      w = rect.width; h = rect.height;
      canvas.width = w * dpr; canvas.height = h * dpr;
      canvas.style.width = w + 'px'; canvas.style.height = h + 'px';
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
    };

    // pre-build sphere geometry (parallels + meridians)
    const latSegs = 9, lonSegs = 16;
    const parallels = [];
    for (let i = 1; i < latSegs; i++) {
      const lat = -Math.PI / 2 + (Math.PI * i) / latSegs;
      const ring = [];
      for (let j = 0; j <= lonSegs; j++) {
        const lon = (Math.PI * 2 * j) / lonSegs;
        ring.push([
          Math.cos(lat) * Math.cos(lon),
          Math.sin(lat),
          Math.cos(lat) * Math.sin(lon),
        ]);
      }
      parallels.push(ring);
    }
    const meridians = [];
    for (let j = 0; j < lonSegs; j++) {
      const lon = (Math.PI * 2 * j) / lonSegs;
      const ring = [];
      for (let i = 0; i <= latSegs; i++) {
        const lat = -Math.PI / 2 + (Math.PI * i) / latSegs;
        ring.push([
          Math.cos(lat) * Math.cos(lon),
          Math.sin(lat),
          Math.cos(lat) * Math.sin(lon),
        ]);
      }
      meridians.push(ring);
    }

    const project = (p, cx, cy, R, rotY, rotX) => {
      let [x, y, z] = p;
      // rot X
      const cX = Math.cos(rotX), sX = Math.sin(rotX);
      const ny = y * cX - z * sX;
      const nz = y * sX + z * cX;
      y = ny; z = nz;
      // rot Y
      const cY = Math.cos(rotY), sY = Math.sin(rotY);
      const nx = x * cY + z * sY;
      const nz2 = -x * sY + z * cY;
      x = nx; z = nz2;
      // simple perspective
      const f = 2.6;
      const persp = f / (f - z * 0.55);
      return { sx: cx + x * R * persp, sy: cy + y * R * persp, z };
    };

    const onMouse = (e) => {
      const rect = wrap.getBoundingClientRect();
      mouseRef.current.target = {
        x: (e.clientX - rect.left) / rect.width,
        y: (e.clientY - rect.top) / rect.height,
      };
    };
    const onLeave = () => { mouseRef.current.target = { x: 0.5, y: 0.5 }; };

    const draw = () => {
      tRef.current += 0.0085;
      const t = tRef.current;

      // ease mouse
      mouseRef.current.x += (mouseRef.current.target.x - mouseRef.current.x) * 0.06;
      mouseRef.current.y += (mouseRef.current.target.y - mouseRef.current.y) * 0.06;

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

      // === perspective floor grid (subtle, bottom half) ===
      const horizonY = h * 0.62;
      const numH = 10;
      for (let i = 1; i <= numH; i++) {
        const k = i / numH;
        const yy = horizonY + Math.pow(k, 1.6) * (h - horizonY) * 1.1;
        ctx.beginPath();
        ctx.moveTo(-w * 0.1, yy);
        ctx.lineTo(w * 1.1, yy);
        ctx.strokeStyle = `rgba(0, 230, 118, ${0.03 + k * 0.07})`;
        ctx.lineWidth = 1;
        ctx.stroke();
      }
      const vpx = w * 0.5;
      const numV = 22;
      for (let i = -numV; i <= numV; i++) {
        const xOff = (i / numV) * w * 1.3;
        ctx.beginPath();
        ctx.moveTo(vpx + xOff, h);
        ctx.lineTo(vpx + xOff * 0.04, horizonY);
        ctx.strokeStyle = `rgba(0, 180, 216, ${0.025 + (Math.abs(i) / numV) * 0.05})`;
        ctx.lineWidth = 1;
        ctx.stroke();
      }

      // === central wireframe sphere ===
      const cx = w * (w > 980 ? 0.72 : 0.5);
      const cy = h * 0.5;
      const R = Math.min(w, h) * (w > 980 ? 0.22 : 0.28);
      const mx = mouseRef.current.x - 0.5;
      const my = mouseRef.current.y - 0.5;
      const rotY = t * 0.35 + mx * 0.7;
      const rotX = -0.25 + my * 0.5;

      // parallels
      ctx.lineWidth = 1;
      parallels.forEach((ring, ri) => {
        ctx.beginPath();
        let avgZ = 0;
        ring.forEach((p, i) => {
          const pr = project(p, cx, cy, R, rotY, rotX);
          if (i === 0) ctx.moveTo(pr.sx, pr.sy);
          else ctx.lineTo(pr.sx, pr.sy);
          avgZ += pr.z;
        });
        avgZ /= ring.length;
        const front = (avgZ + 1) / 2; // 0 back .. 1 front
        const a = 0.06 + front * 0.18;
        ctx.strokeStyle = `rgba(0, 230, 118, ${a})`;
        ctx.stroke();
      });
      // meridians (every 4th gold)
      meridians.forEach((ring, mi) => {
        const isAccent = mi % 4 === 0;
        ctx.beginPath();
        let avgZ = 0;
        ring.forEach((p, i) => {
          const pr = project(p, cx, cy, R, rotY, rotX);
          if (i === 0) ctx.moveTo(pr.sx, pr.sy);
          else ctx.lineTo(pr.sx, pr.sy);
          avgZ += pr.z;
        });
        avgZ /= ring.length;
        const front = (avgZ + 1) / 2;
        const a = 0.05 + front * 0.2;
        ctx.strokeStyle = isAccent
          ? `rgba(255, 215, 0, ${0.08 + front * 0.22})`
          : `rgba(0, 180, 216, ${a})`;
        ctx.lineWidth = isAccent ? 1.1 : 0.9;
        ctx.stroke();
      });

      // bright equator
      ctx.beginPath();
      const eqSegs = 80;
      for (let i = 0; i <= eqSegs; i++) {
        const a = (i / eqSegs) * Math.PI * 2;
        const pr = project([Math.cos(a), 0, Math.sin(a)], cx, cy, R, rotY, rotX);
        if (i === 0) ctx.moveTo(pr.sx, pr.sy);
        else ctx.lineTo(pr.sx, pr.sy);
      }
      ctx.strokeStyle = 'rgba(0, 230, 118, 0.55)';
      ctx.lineWidth = 1.3;
      ctx.stroke();

      // === outer reticle: static circle ===
      ctx.beginPath();
      ctx.arc(cx, cy, R * 1.35, 0, Math.PI * 2);
      ctx.strokeStyle = 'rgba(0, 180, 216, 0.35)';
      ctx.lineWidth = 1;
      ctx.stroke();

      // === tick ring (rotating) ===
      const tickR = R * 1.5;
      const ticks = 60;
      for (let i = 0; i < ticks; i++) {
        const a = (i / ticks) * Math.PI * 2 + t * 0.18;
        const major = i % 5 === 0;
        const len = major ? 10 : 4;
        const x1 = cx + Math.cos(a) * tickR;
        const y1 = cy + Math.sin(a) * tickR;
        const x2 = cx + Math.cos(a) * (tickR + len);
        const y2 = cy + Math.sin(a) * (tickR + len);
        ctx.beginPath();
        ctx.moveTo(x1, y1);
        ctx.lineTo(x2, y2);
        ctx.strokeStyle = major ? 'rgba(255, 215, 0, 0.55)' : 'rgba(0, 230, 118, 0.32)';
        ctx.lineWidth = major ? 1.2 : 0.7;
        ctx.stroke();
      }

      // four cardinal "lock" brackets just outside the disk
      const bR = R * 1.4;
      const bracketAngles = [-Math.PI / 4, Math.PI / 4, Math.PI * 3 / 4, -Math.PI * 3 / 4];
      bracketAngles.forEach(a0 => {
        const arm = 0.18;
        ctx.beginPath();
        ctx.arc(cx, cy, bR, a0 - arm, a0 + arm);
        ctx.strokeStyle = 'rgba(0, 180, 216, 0.65)';
        ctx.lineWidth = 1.5;
        ctx.stroke();
      });

      // === sweeping radar arc ===
      const sweepA = (t * 0.55) % (Math.PI * 2);
      const arcR = R * 1.18;
      const arcWidth = Math.PI * 0.22;
      const grad = ctx.createLinearGradient(
        cx + Math.cos(sweepA) * arcR,
        cy + Math.sin(sweepA) * arcR,
        cx + Math.cos(sweepA + arcWidth) * arcR,
        cy + Math.sin(sweepA + arcWidth) * arcR,
      );
      grad.addColorStop(0, 'rgba(0, 230, 118, 0)');
      grad.addColorStop(1, 'rgba(0, 230, 118, 0.85)');
      ctx.beginPath();
      ctx.arc(cx, cy, arcR, sweepA, sweepA + arcWidth);
      ctx.strokeStyle = grad;
      ctx.lineWidth = 2.2;
      ctx.stroke();

      // === aux reticle (top-left), only on wide screens ===
      if (w > 980) {
        const ax = w * 0.18, ay = h * 0.34, aR = 38;
        ctx.beginPath();
        ctx.arc(ax, ay, aR, 0, Math.PI * 2);
        ctx.strokeStyle = 'rgba(0, 180, 216, 0.45)';
        ctx.lineWidth = 1;
        ctx.stroke();
        ctx.beginPath();
        ctx.arc(ax, ay, aR - 7, t * 0.6, t * 0.6 + Math.PI * 1.25);
        ctx.strokeStyle = 'rgba(255, 215, 0, 0.6)';
        ctx.lineWidth = 1.4;
        ctx.stroke();
        // crosshair
        ctx.beginPath();
        ctx.moveTo(ax - aR - 8, ay); ctx.lineTo(ax - aR + 4, ay);
        ctx.moveTo(ax + aR - 4, ay); ctx.lineTo(ax + aR + 8, ay);
        ctx.moveTo(ax, ay - aR - 8); ctx.lineTo(ax, ay - aR + 4);
        ctx.moveTo(ax, ay + aR - 4); ctx.lineTo(ax, ay + aR + 8);
        ctx.strokeStyle = 'rgba(0, 230, 118, 0.55)';
        ctx.lineWidth = 1;
        ctx.stroke();
        // dot
        ctx.beginPath();
        ctx.arc(ax, ay, 2.5, 0, Math.PI * 2);
        ctx.fillStyle = 'rgba(0, 230, 118, 0.95)';
        ctx.fill();
      }

      animRef.current = requestAnimationFrame(draw);
    };

    resize();
    window.addEventListener('resize', resize);
    wrap.addEventListener('mousemove', onMouse);
    wrap.addEventListener('mouseleave', onLeave);
    animRef.current = requestAnimationFrame(draw);

    return () => {
      cancelAnimationFrame(animRef.current);
      window.removeEventListener('resize', resize);
      wrap.removeEventListener('mousemove', onMouse);
      wrap.removeEventListener('mouseleave', onLeave);
    };
  }, []);

  // monospaced HUD readouts (DOM, so they crisp)
  const labelStyle = {
    position: 'absolute',
    fontFamily: "'Courier Prime', monospace",
    fontSize: '0.62rem',
    color: 'rgba(0, 230, 118, 0.65)',
    letterSpacing: 1.2,
    textTransform: 'uppercase',
    fontWeight: 700,
    pointerEvents: 'none',
    whiteSpace: 'nowrap',
  };
  const bracket = (corner) => {
    const size = 22;
    const thick = 1.5;
    const c = 'rgba(0, 180, 216, 0.55)';
    const map = {
      tl: { top: 18, left: 18, borderTop: `${thick}px solid ${c}`, borderLeft: `${thick}px solid ${c}` },
      tr: { top: 18, right: 18, borderTop: `${thick}px solid ${c}`, borderRight: `${thick}px solid ${c}` },
      bl: { bottom: 18, left: 18, borderBottom: `${thick}px solid ${c}`, borderLeft: `${thick}px solid ${c}` },
      br: { bottom: 18, right: 18, borderBottom: `${thick}px solid ${c}`, borderRight: `${thick}px solid ${c}` },
    };
    return <div key={corner} style={{ position: 'absolute', width: size, height: size, ...map[corner] }} />;
  };

  return (
    <div ref={wrapRef} style={{ position: 'absolute', inset: 0, overflow: 'hidden', pointerEvents: 'none' }} aria-hidden="true">
      <canvas ref={canvasRef} style={{ position: 'absolute', inset: 0, opacity: 0.95 }} />
      {/* corner brackets */}
      {['tl', 'tr', 'bl', 'br'].map(bracket)}
      {/* top-left readout */}
      <div style={{ ...labelStyle, top: 22, left: 48 }}>
        SYS // LUMIKODE.HUD <span style={{ color: 'rgba(255,215,0,0.75)' }}>v4.2</span>
      </div>
      <div style={{ ...labelStyle, top: 38, left: 48, color: 'rgba(0,180,216,0.55)' }}>
        ARCH=4L · STATUS=OK · LATENCY&lt;50MS
      </div>
      {/* top-right readout */}
      <div style={{ ...labelStyle, top: 22, right: 48, color: 'rgba(255,215,0,0.7)' }}>
        IBM·i · DB2/400 · RPG·ILE · NODE·JS
      </div>
      {/* bottom-left readout */}
      <div style={{ ...labelStyle, bottom: 38, left: 48, color: 'rgba(0,180,216,0.55)' }}>
        FRAME 1080 · LOCK·ON · TLS 1.3
      </div>
      <div style={{ ...labelStyle, bottom: 22, left: 48 }}>
        <span style={{ color: 'rgba(255,215,0,0.7)' }}>◢</span>&nbsp; TARGETING — 4 LAYERS ACQUIRED
      </div>
      {/* bottom-right blinking dot */}
      <div style={{ ...labelStyle, bottom: 22, right: 48 }}>
        <span style={{
          display: 'inline-block', width: 6, height: 6, borderRadius: '50%',
          background: 'rgba(0,230,118,1)', marginRight: 8, verticalAlign: 'middle',
          boxShadow: '0 0 8px rgba(0,230,118,0.9)',
          animation: 'hud-blink 1.6s ease-in-out infinite',
        }} />
        REC · 00:{String(Math.floor((Date.now() / 1000) % 60)).padStart(2, '0')}
      </div>
      {/* vignette */}
      <div style={{
        position: 'absolute', inset: 0,
        background: 'radial-gradient(ellipse 75% 60% at 50% 50%, transparent 35%, rgba(15,15,35,0.55) 100%)',
      }} />
      <style>{`
        @keyframes hud-blink { 0%,100% { opacity: 1; } 50% { opacity: 0.25; } }
      `}</style>
    </div>
  );
}

// HERO
function TecnologiaHero() {
  const ref = useRefTC(null);
  const isInView = useInViewTC(ref, { once: true });
  return (
    <section ref={ref} style={{
      position: 'relative', overflow: 'hidden',
      padding: '160px 5% 80px',
      background: colors.bgPrimary,
    }}>
      <TechHUD />
      <div style={{
        position: 'absolute', inset: 0,
        background: `radial-gradient(ellipse 60% 40% at 30% 30%, rgba(45,106,79,0.1), transparent 70%)`,
        pointerEvents: 'none',
      }} />
      <div style={{
        maxWidth: 920, margin: '0 auto', position: 'relative', zIndex: 1,
        textAlign: 'center',
      }}>
        <motionTC.div
          initial={{ opacity: 0, y: -10 }}
          animate={isInView ? { opacity: 1, y: 0 } : {}}
          transition={{ duration: 0.6 }}
          style={{
            display: 'inline-flex', alignItems: 'center', gap: 10,
            padding: '6px 14px', marginBottom: 28,
            border: `1px solid rgba(45,106,79,0.4)`,
            borderRadius: 999, background: 'rgba(15,15,35,0.6)',
            fontFamily: "'Courier Prime', monospace",
            fontSize: '0.7rem', color: colors.brandGreen,
            letterSpacing: 2, textTransform: 'uppercase', fontWeight: 600,
          }}
        >
          <span style={{ width: 6, height: 6, borderRadius: '50%', background: colors.brandGreen, boxShadow: `0 0 8px ${colors.brandGreen}` }} />
          Architettura Tecnica
        </motionTC.div>
        <motionTC.h1
          initial={{ opacity: 0, y: 20 }}
          animate={isInView ? { opacity: 1, y: 0 } : {}}
          transition={{ duration: 0.7, delay: 0.1 }}
          style={{
            fontFamily: "'Cinzel', serif",
            fontSize: 'clamp(2.6rem, 5.5vw, 4rem)',
            fontWeight: 500, color: colors.textPrimary,
            lineHeight: 1.1, marginBottom: 22, letterSpacing: -0.5,
          }}
        >
          Quattro layer.<br />
          <span style={{ color: colors.brandGreen, fontStyle: 'italic' }}>Zero vendor lock-in.</span>
        </motionTC.h1>
        <motionTC.p
          initial={{ opacity: 0 }}
          animate={isInView ? { opacity: 1 } : {}}
          transition={{ duration: 0.7, delay: 0.3 }}
          style={{
            fontSize: '1.15rem', color: colors.textMuted,
            lineHeight: 1.7, fontWeight: 300, maxWidth: 720, margin: '0 auto',
          }}
        >
          Calcolo, dati e frontend coesistono sullo stesso server IBM i.
          Separazione chiara, sicurezza nativa, tecnologie standard.
          Niente magia. Solo ingegneria.
        </motionTC.p>
      </div>
    </section>
  );
}

// FILOSOFIA — 3 principi
function TechPrinciples() {
  const principles = [
    {
      icon: 'layers', title: 'Separation of Concerns',
      desc: 'Ogni layer ha una responsabilità sola e ben definita. Si può sostituire qualsiasi pezzo senza toccare gli altri.',
    },
    {
      icon: 'lock', title: 'Sicurezza Nativa IBM i',
      desc: 'Sfruttiamo l\'audit journal, gli user profile, le autorizzazioni native del sistema. Non reinventiamo la sicurezza: la potenziamo.',
    },
    {
      icon: 'unlink', title: 'Zero Vendor Lock-in',
      desc: 'Tecnologie standard (React, Node.js, RPG ILE, DB2). Nessun runtime proprietario. Il cliente è padrone del proprio codice.',
    },
  ];

  return (
    <AnimatedSection style={{ padding: '90px 5%', background: colors.bgSecondary }}>
      <div style={{ maxWidth: 1080, margin: '0 auto' }}>
        <SectionHeading
          eyebrow="// Principi"
          title="Tre regole, sempre"
          sub="Ogni scelta tecnica passa attraverso questi tre filtri. Se non li rispetta, non entra nello stack."
        />

        <div style={{
          display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)',
          gap: 24, marginTop: 60,
        }} className="princ-grid">
          {principles.map((p, i) => (
            <motionTC.div
              key={i}
              initial={{ opacity: 0, y: 20 }}
              whileInView={{ opacity: 1, y: 0 }}
              viewport={{ once: true }}
              transition={{ duration: 0.5, delay: i * 0.1 }}
              style={{
                padding: 32,
                background: 'rgba(255,255,255,0.02)',
                border: '1px solid rgba(255,255,255,0.06)',
                borderRadius: 10,
                transition: 'all 0.3s',
              }}
              onMouseEnter={e => {
                e.currentTarget.style.borderColor = colors.brandGreen + '40';
                e.currentTarget.style.boxShadow = `0 0 30px ${colors.brandGreen}10`;
              }}
              onMouseLeave={e => {
                e.currentTarget.style.borderColor = 'rgba(255,255,255,0.06)';
                e.currentTarget.style.boxShadow = 'none';
              }}
            >
              <Icon name={p.icon} size={32} color={colors.brandGreen} style={{ marginBottom: 18 }} />
              <h3 style={{
                fontFamily: "'DM Sans', sans-serif",
                fontSize: '1.15rem', fontWeight: 600,
                color: colors.textPrimary, marginBottom: 12,
                lineHeight: 1.3,
              }}>{p.title}</h3>
              <p style={{
                fontSize: '0.9rem', color: colors.textMuted,
                lineHeight: 1.7, fontWeight: 300,
              }}>{p.desc}</p>
            </motionTC.div>
          ))}
        </div>
      </div>
      <style>{`
        @media (max-width: 820px) { .princ-grid { grid-template-columns: 1fr !important; } }
      `}</style>
    </AnimatedSection>
  );
}

// 4-LAYER ARCHITECTURE
function FourLayer() {
  const layers = [
    {
      n: 'L4', name: 'Frontend Layer', brand: 'Lumiere · React',
      icon: 'monitor', color: colors.brandGold,
      desc: 'Microfrontend federati con Webpack Module Federation. Design system condiviso, deploy indipendenti.',
      tech: ['React', 'Material UI', 'Module Federation', '@lumiere/sdk', '@lumiere/datagrid'],
      role: 'Esposizione',
    },
    {
      n: 'L3', name: 'API Gateway', brand: 'kd-api-gateway · Node.js',
      icon: 'server', color: colors.brandGreen,
      desc: 'Autenticazione, autorizzazione, rate limiting, logging. Connessione ODBC verso IBM i, gestita con PM2 in cluster mode.',
      tech: ['Express.js', 'JWT + MFA', 'Refresh Tokens', 'ODBC IBM i', 'PM2 cluster'],
      role: 'Orchestrazione',
    },
    {
      n: 'L2', name: 'Bridge Layer', brand: 'Kodari Bridge',
      icon: 'shield', color: colors.brandCyan,
      desc: 'RPG ILE moderno (SQLRPGLE Free-Format). WebServices nativi con serializzazione JSON, esposti come stored procedure callable.',
      tech: ['RPG ILE', 'SQLRPGLE Free-Format', 'WebServices', 'Activation Groups'],
      role: 'Business Logic',
    },
    {
      n: 'L1', name: 'Data Layer', brand: 'IBM i · DB2/400',
      icon: 'database', color: colors.brandGoldMuted,
      desc: 'Database DB2 for i nativo. Audit journal di sistema, autorizzazioni a livello oggetto, user profile, libraries.',
      tech: ['DB2/400', 'IBM i', 'User Profiles', 'Object Authorities'],
      role: 'Persistenza',
    },
  ];

  const [active, setActive] = useStateTC(0);
  const l = layers[active];

  return (
    <AnimatedSection style={{ padding: '100px 5%', background: colors.bgPrimary }}>
      <div style={{ maxWidth: 1180, margin: '0 auto' }}>
        <SectionHeading
          eyebrow="// 03 — Architettura tecnica"
          title="Quattro layer, una sinfonia"
          sub="Esplora i quattro strati indipendenti che garantiscono separazione, sicurezza e zero vendor lock-in. Passa il mouse o tocca per ispezionare."
        />

        <div style={{
          display: 'grid', gridTemplateColumns: '1fr 1fr',
          gap: 40, alignItems: 'center',
          marginTop: 60,
        }} className="fourlayer-grid">

          {/* LEFT — 3D stack */}
          <div>
            <Layer3DStack layers={layers} active={active} onSelect={setActive} compact />
          </div>

          {/* RIGHT — inspector + selector */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
            {/* Inspector card */}
            <motionTC.div
              key={active}
              initial={{ opacity: 0, y: 8 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.35 }}
              style={{
                position: 'relative',
                padding: '24px 26px',
                background: `linear-gradient(180deg, rgba(255,255,255,0.03), rgba(255,255,255,0.01))`,
                border: `1px solid ${l.color}55`,
                borderLeft: `3px solid ${l.color}`,
                borderRadius: 10,
                boxShadow: `0 0 40px ${l.color}10`,
              }}
            >
              <div style={{ display: 'flex', alignItems: 'flex-start', gap: 16, marginBottom: 14 }}>
                <div style={{
                  width: 52, height: 52, flexShrink: 0,
                  borderRadius: 8,
                  background: `${l.color}15`,
                  border: `1px solid ${l.color}50`,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                }}>
                  <Icon name={l.icon} size={24} color={l.color} />
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <h3 style={{
                    fontFamily: "'DM Sans', sans-serif",
                    fontSize: '1.25rem', fontWeight: 600,
                    color: colors.textPrimary, margin: '2px 0 6px',
                    lineHeight: 1.2,
                  }}>{l.name}</h3>
                  <div style={{
                    fontFamily: "'Courier Prime', monospace",
                    fontSize: '0.78rem', color: l.color,
                    fontWeight: 700, letterSpacing: 1,
                  }}>{l.brand}</div>
                </div>
                <span style={{
                  fontSize: '0.6rem', padding: '3px 9px',
                  background: `${l.color}15`, border: `1px solid ${l.color}40`,
                  borderRadius: 12, color: l.color, fontWeight: 700,
                  letterSpacing: 1.2, textTransform: 'uppercase',
                  fontFamily: "'Courier Prime', monospace",
                  flexShrink: 0,
                }}>{l.role}</span>
              </div>
              <p style={{
                fontSize: '0.92rem', color: colors.textMuted,
                lineHeight: 1.65, fontWeight: 300,
                margin: '0 0 16px',
              }}>{l.desc}</p>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                {l.tech.map((t, ti) => (
                  <span key={ti} style={{
                    padding: '4px 10px',
                    fontSize: '0.7rem',
                    fontFamily: "'Courier Prime', monospace",
                    color: l.color, opacity: 0.9,
                    background: `${l.color}10`,
                    border: `1px solid ${l.color}40`,
                    borderRadius: 4, letterSpacing: 0.4,
                  }}>{t}</span>
                ))}
              </div>
            </motionTC.div>

            {/* Selector — 4 row buttons */}
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {layers.map((row, i) => {
                const isActive = i === active;
                return (
                  <button
                    key={i}
                    onClick={() => setActive(i)}
                    onMouseEnter={() => setActive(i)}
                    style={{
                      all: 'unset',
                      cursor: 'pointer',
                      display: 'flex', alignItems: 'center', gap: 12,
                      padding: '11px 16px',
                      background: isActive ? `${row.color}10` : 'rgba(255,255,255,0.015)',
                      border: `1px solid ${isActive ? row.color + '70' : 'rgba(255,255,255,0.08)'}`,
                      borderRadius: 6,
                      transition: 'all 0.25s',
                      fontFamily: "'Courier Prime', monospace",
                      fontSize: '0.85rem',
                      color: isActive ? row.color : colors.textMuted,
                      letterSpacing: 0.5,
                    }}
                  >
                    <span style={{
                      width: 8, height: 8, borderRadius: '50%',
                      background: row.color,
                      boxShadow: isActive ? `0 0 10px ${row.color}` : 'none',
                      flexShrink: 0,
                      transition: 'box-shadow 0.25s',
                    }} />
                    <span style={{ flex: 1 }}>{row.name}</span>
                    <span style={{
                      fontSize: '0.65rem',
                      color: isActive ? row.color : colors.textDim,
                      opacity: isActive ? 0.9 : 0.5,
                      letterSpacing: 1,
                    }}>{row.n}</span>
                  </button>
                );
              })}
            </div>
          </div>
        </div>

        {/* Footer note */}
        <div style={{
          marginTop: 40, padding: '20px 28px',
          background: 'rgba(45,106,79,0.04)',
          border: `1px dashed ${colors.brandGreen}30`,
          borderRadius: 8,
          display: 'flex', alignItems: 'flex-start', gap: 14,
        }}>
          <Icon name="info" size={18} color={colors.brandGreen} style={{ flexShrink: 0, marginTop: 2 }} />
          <div>
            <div style={{
              fontFamily: "'Courier Prime', monospace",
              fontSize: '0.7rem', color: colors.brandGreen,
              letterSpacing: 1.5, textTransform: 'uppercase',
              fontWeight: 700, marginBottom: 6,
            }}>Nota architetturale</div>
            <p style={{
              fontSize: '0.88rem', color: colors.textMuted,
              lineHeight: 1.6, margin: 0, fontWeight: 300,
            }}>
              I layer L1, L2 risiedono sulla stessa LPAR IBM i.
              L3 e L4 possono essere ovunque: stesso server, container Docker,
              edge CDN.
            </p>
          </div>
        </div>
      </div>

      <style>{`
        @media (max-width: 980px) {
          .fourlayer-grid { grid-template-columns: 1fr !important; gap: 24px !important; }
        }
      `}</style>
    </AnimatedSection>
  );
}

// SECURITY DEEP-DIVE
function SecuritySection() {
  const items = [
    { icon: 'key', title: 'JWT + MFA', desc: 'Token a vita breve (15 min) con refresh rotativo. MFA opzionale per ruoli sensibili.' },
    { icon: 'fingerprint', title: 'User Profile IBM i', desc: 'Ogni request è eseguita con il profile dell\'utente. Le autorizzazioni native si applicano sempre.' },
    { icon: 'history', title: 'Audit Journal nativo', desc: 'Ogni operazione è tracciata dall\'audit journal di sistema.' }, // TODO ripristinare: Compliance ready: SOX, GDPR, ISO 27001.
    { icon: 'lock', title: 'TLS End-to-End', desc: 'Certificate pinning sul Gateway. Solo cipher suite moderne.' }, // TODO ripristinare: HSTS forced.
    { icon: 'shield-check', title: 'Rate Limit + WAF', desc: 'Throttling per IP/utente, blocco pattern noti, alerting in tempo reale.' },
    { icon: 'eye-off', title: 'Secrets Vault', desc: 'Credenziali e chiavi mai in chiaro. Rotazione automatica programmabile.' },
  ];

  return (
    <AnimatedSection style={{ padding: '100px 5%', background: colors.bgSecondary }}>
      <div style={{ maxWidth: 1080, margin: '0 auto' }}>
        <SectionHeading
          eyebrow="// Sicurezza"
          title="Difesa in profondità"
          sub="Sei livelli di sicurezza, ognuno indipendente. Anche se uno cade, gli altri tengono."
        />

        <div style={{
          display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)',
          gap: 18, marginTop: 60,
        }} className="sec-grid">
          {items.map((it, i) => (
            <motionTC.div
              key={i}
              initial={{ opacity: 0, y: 20 }}
              whileInView={{ opacity: 1, y: 0 }}
              viewport={{ once: true }}
              transition={{ duration: 0.4, delay: i * 0.05 }}
              style={{
                padding: '24px 22px',
                background: 'rgba(255,255,255,0.02)',
                border: '1px solid rgba(255,255,255,0.06)',
                borderRadius: 8,
                transition: 'all 0.3s',
              }}
              onMouseEnter={e => {
                e.currentTarget.style.borderColor = colors.brandCyan + '40';
                e.currentTarget.style.transform = 'translateY(-2px)';
              }}
              onMouseLeave={e => {
                e.currentTarget.style.borderColor = 'rgba(255,255,255,0.06)';
                e.currentTarget.style.transform = 'translateY(0)';
              }}
            >
              <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 10 }}>
                <div style={{
                  width: 36, height: 36, borderRadius: 6,
                  background: `${colors.brandCyan}10`,
                  border: `1px solid ${colors.brandCyan}30`,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  flexShrink: 0,
                }}>
                  <Icon name={it.icon} size={16} color={colors.brandCyan} />
                </div>
                <h4 style={{
                  fontFamily: "'DM Sans', sans-serif",
                  fontSize: '0.98rem', fontWeight: 600,
                  color: colors.textPrimary, margin: 0,
                }}>{it.title}</h4>
              </div>
              <p style={{
                fontSize: '0.85rem', color: colors.textMuted,
                lineHeight: 1.6, fontWeight: 300, margin: 0,
              }}>{it.desc}</p>
            </motionTC.div>
          ))}
        </div>
      </div>
      <style>{`
        @media (max-width: 900px) { .sec-grid { grid-template-columns: 1fr 1fr !important; } }
        @media (max-width: 600px) { .sec-grid { grid-template-columns: 1fr !important; } }
      `}</style>
    </AnimatedSection>
  );
}

// METRICS
function TechMetrics() {
  const metrics = [
    { val: '4', label: 'Layer indipendenti', sub: 'separation of concerns' },
    { val: '0', label: 'Vendor lock-in', sub: 'tech standard' },
    { val: '99.9%', label: 'Uptime garantito', sub: 'PM2 cluster + IBM i' },
    { val: '<50ms', label: 'Latenza Gateway', sub: 'P95 in produzione' },
  ];

  return (
    <AnimatedSection style={{ padding: '80px 5%', background: colors.bgPrimary }}>
      <div style={{ maxWidth: 980, margin: '0 auto' }}>
        <div style={{
          display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)',
          gap: 16, padding: '36px 28px',
          background: 'rgba(255,255,255,0.02)',
          border: '1px solid rgba(255,255,255,0.06)',
          borderRadius: 12,
        }} className="metrics-grid">
          {metrics.map((m, i) => (
            <div key={i} style={{
              textAlign: 'center',
              padding: '0 16px',
              borderRight: i < metrics.length - 1 ? '1px solid rgba(255,255,255,0.06)' : 'none',
            }} className="metric-cell">
              <div style={{
                fontFamily: "'Orbitron', sans-serif",
                fontSize: 'clamp(1.6rem, 3vw, 2.2rem)',
                fontWeight: 700, color: colors.brandGold,
                marginBottom: 6,
              }}>{m.val}</div>
              <div style={{
                fontSize: '0.85rem', color: colors.textPrimary,
                fontWeight: 500, marginBottom: 4,
              }}>{m.label}</div>
              <div style={{
                fontSize: '0.7rem', color: colors.textDim,
                fontFamily: "'Courier Prime', monospace",
                letterSpacing: 0.8,
              }}>{m.sub}</div>
            </div>
          ))}
        </div>
      </div>
      <style>{`
        @media (max-width: 720px) {
          .metrics-grid { grid-template-columns: 1fr 1fr !important; }
          .metric-cell { border-right: none !important; padding: 14px 0 !important; }
        }
      `}</style>
    </AnimatedSection>
  );
}

// CTA
function TechCta() {
  return (
    <AnimatedSection style={{
      padding: '100px 5%',
      background: `linear-gradient(135deg, ${colors.bgSecondary}, #0a1a14)`,
      borderTop: `1px solid rgba(45,106,79,0.2)`,
      textAlign: 'center',
    }}>
      <div style={{ maxWidth: 720, margin: '0 auto' }}>
        <h2 style={{
          fontFamily: "'Cinzel', serif",
          fontSize: 'clamp(2rem, 4vw, 2.8rem)',
          fontWeight: 500, color: colors.textPrimary,
          marginBottom: 18, lineHeight: 1.2,
        }}>Vuoi vedere lo stack al lavoro?</h2>
        <p style={{
          fontSize: '1.05rem', color: colors.textMuted,
          lineHeight: 1.7, fontWeight: 300,
          maxWidth: 560, margin: '0 auto 36px',
        }}>
          Possiamo organizzare un walkthrough tecnico con il vostro team IT.
          Codice reale, architettura reale, scelte motivate.
        </p>
        <div style={{ display: 'inline-flex', gap: 14, flexWrap: 'wrap', justifyContent: 'center' }}>
          <a href="contatti.html" style={{
            fontFamily: "'DM Sans', sans-serif",
            fontSize: '0.95rem', fontWeight: 600,
            padding: '15px 32px',
            background: `linear-gradient(135deg, ${colors.brandGreen}, ${colors.brandEmerald})`,
            color: colors.bgPrimary, borderRadius: 6, textDecoration: 'none',
            letterSpacing: 0.5,
            boxShadow: `0 0 30px ${colors.brandGreen}30`,
            display: 'inline-flex', alignItems: 'center', gap: 10,
            transition: 'all 0.3s',
          }}
            onMouseEnter={e => { e.currentTarget.style.transform = 'translateY(-2px)'; }}
            onMouseLeave={e => { e.currentTarget.style.transform = 'translateY(0)'; }}
          >Richiedi un walkthrough <Icon name="arrow-right" size={16} color={colors.bgPrimary} /></a>
          <a href="prodotti/kodari.html" style={{
            fontFamily: "'DM Sans', sans-serif",
            fontSize: '0.95rem', fontWeight: 500,
            padding: '15px 28px',
            background: 'transparent',
            color: colors.textPrimary, borderRadius: 6, textDecoration: 'none',
            border: `1px solid rgba(255,255,255,0.15)`,
            letterSpacing: 0.5,
            display: 'inline-flex', alignItems: 'center', gap: 8,
            transition: 'all 0.3s',
          }}
            onMouseEnter={e => { e.currentTarget.style.borderColor = colors.brandGreen; e.currentTarget.style.color = colors.brandGreen; }}
            onMouseLeave={e => { e.currentTarget.style.borderColor = 'rgba(255,255,255,0.15)'; e.currentTarget.style.color = colors.textPrimary; }}
          >Approfondisci Kodari</a>
        </div>
      </div>
    </AnimatedSection>
  );
}

// APP
function TecnologiaApp() {
  return (
    <React.Fragment>
      <SiteNav depth={0} current="tecnologia" />
      <main>
        <TecnologiaHero />
        <TechPrinciples />
        <FourLayer />
        <SecuritySection />
        <TechMetrics />
        <TechCta />
      </main>
      <SiteFooter depth={0} />
    </React.Fragment>
  );
}

function mountTecnologia() {
  const ready =
    typeof colors !== 'undefined' &&
    typeof CompassLogo !== 'undefined' &&
    typeof SiteNav !== 'undefined' &&
    window.FramerMotion &&
    window.lucide;
  if (!ready) return setTimeout(mountTecnologia, 50);

  const root = ReactDOM.createRoot(document.getElementById('app'));
  root.render(<TecnologiaApp />);

  if (window.lucide) {
    const observer = new MutationObserver(() => window.lucide.createIcons());
    observer.observe(document.body, { childList: true, subtree: true });
    window.lucide.createIcons();
  }
}
mountTecnologia();
