// ============================================================
// SHARED — Design tokens, hooks, logos, navbar, footer
// ============================================================
const { useState, useEffect, useRef, useCallback, Fragment } = React;
// Lazy accessors — the shim populates window.FramerMotion async after React loads,
// but components don't render until React mounts the tree, by which point it's ready.
const motion = new Proxy({}, { get: (_, p) => window.FramerMotion.motion[p] });
const useInView = (...a) => window.FramerMotion.useInView(...a);
const AnimatePresence = (props) => window.FramerMotion.AnimatePresence(props);

// Lucide icons (UMD exposes window.lucide)
const Lucide = window.lucide;
const toPascal = (s) => s.replace(/(^|-)([a-z0-9])/g, (_, __, c) => c.toUpperCase());
const Icon = ({ name, size = 18, color = 'currentColor', style = {}, ...rest }) => {
  const ref = useRef(null);
  useEffect(() => {
    if (!ref.current || !Lucide) return;
    ref.current.innerHTML = '';
    const key = toPascal(name);
    const def = Lucide.icons[key] || Lucide.icons[name];
    if (!def) return;
    const el = Lucide.createElement(def);
    el.setAttribute('width', size);
    el.setAttribute('height', size);
    el.setAttribute('stroke', color);
    el.setAttribute('stroke-width', 1.6);
    ref.current.appendChild(el);
  }, [name, size, color]);
  return <span ref={ref} style={{ display: 'inline-flex', ...style }} {...rest} />;
};

// LinkedIn brand glyph — not bundled in this lucide build, so we ship our own.
const LinkedinIcon = ({ size = 16, color = 'currentColor', style = {}, ...rest }) => (
  <svg
    width={size} height={size}
    viewBox="0 0 24 24" fill={color}
    style={{ display: 'inline-block', flexShrink: 0, ...style }}
    aria-hidden="true"
    {...rest}
  >
    <path d="M20.45 20.45h-3.55v-5.57c0-1.33-.02-3.04-1.85-3.04-1.85 0-2.14 1.45-2.14 2.94v5.67H9.36V9h3.41v1.56h.05c.48-.9 1.64-1.85 3.38-1.85 3.61 0 4.28 2.38 4.28 5.47v6.27zM5.34 7.43a2.06 2.06 0 1 1 0-4.13 2.06 2.06 0 0 1 0 4.13zM7.12 20.45H3.55V9h3.57v11.45zM22.22 0H1.77C.79 0 0 .77 0 1.72v20.56C0 23.23.79 24 1.77 24h20.45c.98 0 1.78-.77 1.78-1.72V1.72C24 .77 23.2 0 22.22 0z" />
  </svg>
);

// ============================================================
// DESIGN TOKENS
// ============================================================
const colors = {
  bgPrimary: '#0f0f23',
  bgSecondary: '#161630',
  bgTertiary: '#1B263B',
  brandGold: '#FFD700',
  brandGoldMuted: '#C9A84C',
  brandGreen: '#00E676',
  brandEmerald: '#2D6A4F',
  brandCyan: '#00B4D8',
  brandAmber: '#F4D03F',
  blackDeep: '#0A0A0A',
  textPrimary: '#e8e5dd',
  textGold: '#c9b037',
  textMuted: '#94a3b8',
  textDim: '#6b7387',
};

// ============================================================
// HOOKS
// ============================================================
function useScrollPosition() {
  const [scrollY, setScrollY] = useState(0);
  useEffect(() => {
    const handleScroll = () => setScrollY(window.scrollY);
    window.addEventListener('scroll', handleScroll, { passive: true });
    return () => window.removeEventListener('scroll', handleScroll);
  }, []);
  return scrollY;
}

function useCounterAnimation(end, duration = 2000, trigger = false) {
  const [count, setCount] = useState(0);
  const hasAnimated = useRef(false);
  useEffect(() => {
    if (!trigger || hasAnimated.current) return;
    hasAnimated.current = true;
    const startTime = performance.now();
    const animate = (currentTime) => {
      const elapsed = currentTime - startTime;
      const progress = Math.min(elapsed / duration, 1);
      const eased = 1 - Math.pow(1 - progress, 3);
      setCount(Math.round(eased * end));
      if (progress < 1) requestAnimationFrame(animate);
    };
    requestAnimationFrame(animate);
  }, [trigger, end, duration]);
  return count;
}

// Section wrapper with reveal-on-scroll
const sectionVariants = {
  hidden: { opacity: 0, y: 40 },
  visible: { opacity: 1, y: 0, transition: { duration: 0.7, ease: 'easeOut' } },
};

function AnimatedSection({ children, id, style, ...props }) {
  const ref = useRef(null);
  const isInView = useInView(ref, { once: true, margin: '-80px' });
  return (
    <motion.section
      ref={ref}
      id={id}
      initial="hidden"
      animate={isInView ? 'visible' : 'hidden'}
      variants={sectionVariants}
      style={style}
      {...props}
    >
      {children}
    </motion.section>
  );
}

// ============================================================
// ORNAMENTAL SEPARATOR (Belle Époque diamond)
// ============================================================
function OrnamentalSeparator() {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      gap: 12, padding: '0 20px',
    }}>
      <div style={{
        flex: 1, maxWidth: 200, height: 1,
        background: `linear-gradient(90deg, transparent, ${colors.brandGold}, transparent)`,
      }} />
      <div style={{
        width: 8, height: 8, transform: 'rotate(45deg)',
        border: `1px solid ${colors.brandGold}`, background: 'transparent',
      }} />
      <div style={{
        flex: 1, maxWidth: 200, height: 1,
        background: `linear-gradient(90deg, transparent, ${colors.brandGreen}, transparent)`,
      }} />
    </div>
  );
}

// ============================================================
// LOGOS — pure CSS/SVG, animated
// ============================================================
function CompassLogo({ size = 80 }) {
  const s = size / 80;
  return (
    <div style={{ width: size, height: size, position: 'relative', flexShrink: 0 }} aria-hidden="true">
      <div style={{
        width: size, height: size, border: `${3 * s}px solid ${colors.brandGold}`,
        borderRadius: '50%', position: 'absolute',
        background: `radial-gradient(circle, rgba(255,215,0,0.1), transparent 70%)`,
        animation: 'rotate-slow 20s linear infinite',
      }} />
      <div style={{
        width: 54 * s, height: 54 * s,
        border: `${2 * s}px solid ${colors.brandGreen}`,
        borderRadius: '50%', position: 'absolute',
        top: 13 * s, left: 13 * s,
        background: `radial-gradient(circle, rgba(0,230,118,0.1), transparent 70%)`,
      }} />
      <div style={{
        position: 'absolute', top: '50%', left: '50%',
        transform: 'translate(-50%, -50%)',
        width: 40 * s, height: 2 * s,
        background: `linear-gradient(90deg, ${colors.brandGold}, ${colors.brandGreen})`,
        borderRadius: 2, animation: 'compass-point 8s ease-in-out infinite',
        transformOrigin: 'center',
      }}>
        <div style={{
          position: 'absolute', left: -6 * s, top: -3 * s,
          width: 0, height: 0,
          borderLeft: `${6 * s}px solid ${colors.brandGold}`,
          borderTop: `${4 * s}px solid transparent`,
          borderBottom: `${4 * s}px solid transparent`,
        }} />
      </div>
      {[
        { label: 'N', top: 4 * s, left: '50%', transform: 'translateX(-50%)' },
        { label: 'S', bottom: 4 * s, left: '50%', transform: 'translateX(-50%)' },
        { label: 'E', right: 4 * s, top: '50%', transform: 'translateY(-50%)' },
        { label: 'W', left: 4 * s, top: '50%', transform: 'translateY(-50%)' },
      ].map(({ label, ...pos }) => (
        <span key={label} style={{
          position: 'absolute', ...pos,
          fontFamily: "'Courier Prime', monospace",
          fontSize: 8 * s, color: colors.brandGreen, fontWeight: 'bold',
        }}>{label}</span>
      ))}
    </div>
  );
}

function AiKoLogo({ size = 80 }) {
  const s = size / 80;
  const nodes = [
    { top: 10, left: 15, color: colors.brandGold, delay: '0s' },
    { top: 10, right: 15, color: colors.brandGreen, delay: '0.3s' },
    { top: 35, left: 5, color: colors.brandGold, delay: '0.6s' },
    { top: 35, right: 5, color: colors.brandGreen, delay: '0.9s' },
    { bottom: 10, left: 15, color: colors.brandGreen, delay: '1.2s' },
    { bottom: 10, right: 15, color: colors.brandGold, delay: '1.5s' },
    { top: 25, left: 35, color: colors.brandGreen, delay: '1.8s' },
    { bottom: 25, right: 35, color: colors.brandGold, delay: '2.1s' },
  ];
  return (
    <div style={{ width: size, height: size, position: 'relative', flexShrink: 0 }} aria-hidden="true">
      <div style={{
        position: 'absolute', width: 75 * s, height: 75 * s,
        border: `2px solid rgba(255,215,0,0.4)`, borderRadius: '50%',
        top: '50%', left: '50%', marginTop: -37.5 * s, marginLeft: -37.5 * s,
        animation: 'rotate-ring 15s linear infinite',
      }} />
      <div style={{
        position: 'absolute', width: 65 * s, height: 65 * s,
        border: `2px solid rgba(0,230,118,0.4)`, borderRadius: '50%',
        top: '50%', left: '50%', marginTop: -32.5 * s, marginLeft: -32.5 * s,
        animation: 'rotate-ring 12s linear infinite reverse',
      }} />
      <div style={{
        width: 26 * s, height: 26 * s,
        background: `radial-gradient(circle, rgba(255,215,0,0.85), rgba(0,230,118,0.7))`,
        borderRadius: '50%', position: 'absolute', top: '50%', left: '50%',
        marginTop: -13 * s, marginLeft: -13 * s,
        boxShadow: `0 0 ${20 * s}px rgba(255,215,0,0.6), 0 0 ${40 * s}px rgba(0,230,118,0.4)`,
        animation: 'pulse-brain 2s ease-in-out infinite',
      }} />
      {nodes.map((n, i) => {
        const pos = {};
        if (n.top !== undefined) pos.top = n.top * s;
        if (n.bottom !== undefined) pos.bottom = n.bottom * s;
        if (n.left !== undefined) pos.left = n.left * s;
        if (n.right !== undefined) pos.right = n.right * s;
        return (
          <div key={i} style={{
            position: 'absolute', ...pos,
            width: 6 * s, height: 6 * s,
            background: n.color, borderRadius: '50%',
            boxShadow: `0 0 ${8 * s}px ${n.color}`,
            animation: `node-pulse 3s ease-in-out infinite`,
            animationDelay: n.delay,
          }} />
        );
      })}
    </div>
  );
}

function KodariLogo({ size = 80 }) {
  const s = size / 80;
  return (
    <div style={{ width: size, height: size, position: 'relative', flexShrink: 0 }} aria-hidden="true">
      <div style={{
        width: size * 0.85, height: size * 0.85,
        border: `${2.5 * s}px solid ${colors.brandGreen}`,
        borderRadius: 8 * s, position: 'absolute',
        top: size * 0.075, left: size * 0.075,
        background: `radial-gradient(circle, rgba(0,230,118,0.12), transparent 70%)`,
        transform: 'rotate(45deg)',
      }}>
        {[
          { top: 8 * s, left: 8 * s, delay: '0s' },
          { top: 8 * s, right: 8 * s, delay: '0.5s' },
          { bottom: 8 * s, left: 8 * s, delay: '1s' },
          { bottom: 8 * s, right: 8 * s, delay: '1.5s' },
        ].map((d, i) => {
          const pos = {};
          if (d.top !== undefined) pos.top = d.top;
          if (d.bottom !== undefined) pos.bottom = d.bottom;
          if (d.left !== undefined) pos.left = d.left;
          if (d.right !== undefined) pos.right = d.right;
          return (
            <div key={i} style={{
              position: 'absolute', ...pos,
              width: 4 * s, height: 4 * s,
              background: colors.brandGreen, borderRadius: '50%',
              boxShadow: `0 0 ${8 * s}px ${colors.brandGreen}`,
              animation: `blink 2s ease-in-out infinite`,
              animationDelay: d.delay,
            }} />
          );
        })}
      </div>
      <div style={{
        position: 'absolute', top: '50%', left: '50%',
        transform: 'translate(-50%, -50%)',
        fontFamily: "'Courier Prime', monospace",
        fontSize: 18 * s, color: colors.brandGreen,
        fontWeight: 'bold', letterSpacing: -1,
        textShadow: `0 0 10px rgba(0,230,118,0.5)`,
        animation: 'pulse-code 2s ease-in-out infinite',
      }}>{'</>'}</div>
    </div>
  );
}

function LumiereLogo({ size = 80 }) {
  const s = size / 80;
  return (
    <div style={{ width: size, height: size, position: 'relative', flexShrink: 0 }} aria-hidden="true">
      <div style={{ position: 'absolute', top: 12 * s, left: 18 * s, width: 44 * s, height: 56 * s }}>
        <div style={{
          width: 44 * s, height: 8 * s,
          background: `linear-gradient(135deg, ${colors.brandGold}, ${colors.brandAmber})`,
          borderRadius: `${4 * s}px ${4 * s}px 0 0`,
          position: 'absolute', top: 0,
        }} />
        <div style={{
          width: 36 * s, height: 32 * s,
          background: `linear-gradient(135deg, rgba(255,215,0,0.3), rgba(244,208,63,0.18))`,
          border: `${2.5 * s}px solid ${colors.brandGold}`,
          borderRadius: 6 * s,
          position: 'absolute', top: 8 * s, left: 4 * s,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <div style={{
            width: 16 * s, height: 16 * s,
            background: `radial-gradient(circle, ${colors.brandGold}, transparent 70%)`,
            borderRadius: '50%',
            boxShadow: `0 0 ${16 * s}px ${colors.brandGold}, 0 0 ${30 * s}px rgba(255,215,0,0.5)`,
            animation: 'glow 2s ease-in-out infinite',
          }} />
        </div>
        <div style={{
          width: 44 * s, height: 6 * s,
          background: `linear-gradient(135deg, ${colors.brandGold}, ${colors.brandAmber})`,
          borderRadius: `0 0 ${4 * s}px ${4 * s}px`,
          position: 'absolute', bottom: 5 * s,
        }} />
      </div>
      <div style={{ position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%, -50%)' }}>
        {[0, 60, 120, 180, 240, 300].map((deg, i) => (
          <div key={i} style={{
            position: 'absolute', width: 50 * s, height: 1.5 * s,
            background: `linear-gradient(90deg, transparent, ${colors.brandGold}, transparent)`,
            transformOrigin: 'left center',
            transform: `rotate(${deg}deg)`,
            opacity: 0.55,
            animation: `shine 3s ease-in-out infinite`,
            animationDelay: `${i * 0.5}s`,
          }} />
        ))}
      </div>
    </div>
  );
}

function LestageLogo({ size = 80 }) {
  return (
    <div style={{ width: size, height: size, position: 'relative', flexShrink: 0 }} aria-hidden="true">
      <svg width={size} height={size} viewBox="0 0 80 80" fill="none">
        <circle cx="40" cy="22" r="9" stroke={colors.brandGoldMuted} strokeWidth="2.5" fill="none" opacity="0.85">
          <animate attributeName="r" values="9;10;9" dur="2s" repeatCount="indefinite" />
        </circle>
        <line x1="40" y1="31" x2="40" y2="62" stroke={colors.brandGoldMuted} strokeWidth="2.5" opacity="0.7" />
        <line x1="26" y1="48" x2="40" y2="62" stroke={colors.brandGoldMuted} strokeWidth="2" opacity="0.6" />
        <line x1="54" y1="48" x2="40" y2="62" stroke={colors.brandGoldMuted} strokeWidth="2" opacity="0.6" />
        <path d="M14 36 L28 36" stroke={colors.brandGreen} strokeWidth="1.6" opacity="0.6">
          <animate attributeName="opacity" values="0.3;0.8;0.3" dur="2s" repeatCount="indefinite" />
        </path>
        <path d="M52 36 L66 36" stroke={colors.brandGreen} strokeWidth="1.6" opacity="0.6">
          <animate attributeName="opacity" values="0.3;0.8;0.3" dur="2s" repeatCount="indefinite" begin="0.5s" />
        </path>
        <path d="M10 46 L24 46" stroke={colors.brandGold} strokeWidth="1.4" opacity="0.45">
          <animate attributeName="opacity" values="0.2;0.6;0.2" dur="2.5s" repeatCount="indefinite" />
        </path>
        <path d="M56 46 L70 46" stroke={colors.brandGold} strokeWidth="1.4" opacity="0.45">
          <animate attributeName="opacity" values="0.2;0.6;0.2" dur="2.5s" repeatCount="indefinite" begin="0.7s" />
        </path>
      </svg>
    </div>
  );
}

// ============================================================
// CIRCUIT BOARD background (hero)
// ============================================================
function CircuitBoard() {
  const canvasRef = useRef(null);
  const mouseRef = useRef({ x: -1000, y: -1000 });
  const animRef = useRef(null);
  const gridRef = useRef({ nodes: [], traces: [], signals: [] });
  const timeRef = useRef(0);

  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext('2d');
    const dpr = window.devicePixelRatio || 1;

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

      const sp = 55;
      const cols = Math.ceil(rect.width / sp) + 1;
      const rows = Math.ceil(rect.height / sp) + 1;
      const nodes = [];
      const traces = [];

      for (let r = 0; r < rows; r++) {
        for (let c = 0; c < cols; c++) {
          nodes.push({
            x: c * sp, y: r * sp,
            isGold: (r + c) % 3 === 0,
            pulseOffset: Math.random() * Math.PI * 2,
            pulseSpeed: 1.2 + Math.random() * 2.5,
            isJunction: Math.random() < 0.12,
          });
        }
      }
      for (let r = 0; r < rows; r++) {
        for (let c = 0; c < cols; c++) {
          const idx = r * cols + c;
          if (c < cols - 1 && Math.random() < 0.65) {
            traces.push({ from: idx, to: idx + 1, dir: 'h',
              isGold: nodes[idx].isGold || nodes[idx + 1].isGold,
              pulseOffset: Math.random() * Math.PI * 2 });
          }
          if (r < rows - 1 && Math.random() < 0.65) {
            traces.push({ from: idx, to: idx + cols, dir: 'v',
              isGold: nodes[idx].isGold || nodes[idx + cols].isGold,
              pulseOffset: Math.random() * Math.PI * 2 });
          }
        }
      }
      const signals = [];
      for (let i = 0; i < 35; i++) {
        signals.push({
          traceIdx: Math.floor(Math.random() * traces.length),
          pos: Math.random(),
          speed: 0.25 + Math.random() * 0.7,
          isGold: Math.random() < 0.45,
          size: 1.8 + Math.random() * 1.6,
        });
      }
      gridRef.current = { nodes, traces, signals };
    };

    const onMouse = (e) => {
      const rect = canvas.getBoundingClientRect();
      mouseRef.current = { x: e.clientX - rect.left, y: e.clientY - rect.top };
    };
    const onLeave = () => { mouseRef.current = { x: -1000, y: -1000 }; };

    const draw = () => {
      timeRef.current += 0.016;
      const t = timeRef.current;
      const w = canvas.width / dpr;
      const h = canvas.height / dpr;
      ctx.clearRect(0, 0, w, h);
      const mx = mouseRef.current.x;
      const my = mouseRef.current.y;
      const mouseRadius = 200;
      const { nodes, traces, signals } = gridRef.current;

      traces.forEach(trace => {
        const a = nodes[trace.from];
        const b = nodes[trace.to];
        if (!a || !b) return;
        const midX = (a.x + b.x) / 2, midY = (a.y + b.y) / 2;
        const distMouse = Math.sqrt((mx - midX) ** 2 + (my - midY) ** 2);
        const pulse = Math.sin(t * 1.8 + trace.pulseOffset) * 0.5 + 0.5;
        let alpha = 0.06 + pulse * 0.1;
        if (distMouse < mouseRadius) alpha += (1 - distMouse / mouseRadius) * 0.3;
        ctx.beginPath();
        ctx.moveTo(a.x, a.y);
        ctx.lineTo(b.x, b.y);
        ctx.strokeStyle = trace.isGold ? `rgba(255,215,0,${alpha})` : `rgba(0,230,118,${alpha})`;
        ctx.lineWidth = 0.7;
        ctx.stroke();
      });

      nodes.forEach(node => {
        const pulse = Math.sin(t * node.pulseSpeed + node.pulseOffset) * 0.5 + 0.5;
        const distFromMouse = Math.sqrt((mx - node.x) ** 2 + (my - node.y) ** 2);
        let brightness = 0.2 + pulse * 0.3;
        let size = node.isJunction ? (2.2 + pulse * 1.3) : (1.3 + pulse * 0.8);
        if (distFromMouse < mouseRadius) {
          const proximity = 1 - distFromMouse / mouseRadius;
          brightness += proximity * 0.45;
          size += proximity * 2;
        }
        ctx.beginPath();
        ctx.arc(node.x, node.y, size, 0, Math.PI * 2);
        ctx.fillStyle = node.isGold ? `rgba(255,215,0,${brightness})` : `rgba(0,230,118,${brightness})`;
        ctx.fill();
      });

      signals.forEach(sig => {
        sig.pos += sig.speed * 0.016;
        if (sig.pos > 1) {
          sig.pos = 0;
          sig.traceIdx = Math.floor(Math.random() * traces.length);
        }
        const trace = traces[sig.traceIdx];
        if (!trace) return;
        const a = nodes[trace.from];
        const b = nodes[trace.to];
        if (!a || !b) return;
        const sx = a.x + (b.x - a.x) * sig.pos;
        const sy = a.y + (b.y - a.y) * sig.pos;
        const distMouse = Math.sqrt((mx - sx) ** 2 + (my - sy) ** 2);
        let sigAlpha = 0.45;
        let sigSize = sig.size;
        if (distMouse < mouseRadius) {
          sigAlpha += (1 - distMouse / mouseRadius) * 0.4;
          sigSize += 1.2;
        }
        ctx.beginPath();
        ctx.arc(sx, sy, sigSize + 2.5, 0, Math.PI * 2);
        ctx.fillStyle = sig.isGold ? `rgba(255,215,0,${sigAlpha * 0.2})` : `rgba(0,230,118,${sigAlpha * 0.2})`;
        ctx.fill();
        ctx.beginPath();
        ctx.arc(sx, sy, sigSize, 0, Math.PI * 2);
        ctx.fillStyle = sig.isGold ? `rgba(255,215,0,${sigAlpha})` : `rgba(0,230,118,${sigAlpha})`;
        ctx.fill();
      });

      animRef.current = requestAnimationFrame(draw);
    };

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

  return <canvas ref={canvasRef} style={{ position: 'absolute', inset: 0, zIndex: 0 }} aria-hidden="true" />;
}

// ============================================================
// NAVBAR
// ============================================================
const navItems = [
  { id: 'chi-siamo', label: 'Chi Siamo' },
  { id: 'ecosistema', label: 'Ecosistema' },
  { id: 'servizi', label: 'Servizi' },
  { id: 'aiko', label: 'AiKo Engine' },
  { id: 'tecnologia', label: 'Tecnologia' },
  { id: 'contatti', label: 'Contatti' },
];

function Navbar() {
  const [isMenuOpen, setIsMenuOpen] = useState(false);
  const [lang, setLang] = useState('IT');
  const scrollY = useScrollPosition();
  const isScrolled = scrollY > 50;

  const handleNavClick = (id) => {
    setIsMenuOpen(false);
    const el = document.getElementById(id);
    if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
  };

  return (
    <header style={{
      position: 'fixed', top: 0, left: 0, right: 0, zIndex: 1000,
      background: isScrolled ? 'rgba(15,15,35,0.92)' : 'rgba(15,15,35,0.5)',
      backdropFilter: 'blur(16px)',
      WebkitBackdropFilter: 'blur(16px)',
      borderBottom: `1px solid rgba(255,215,0,${isScrolled ? '0.15' : '0.08'})`,
      transition: 'all 0.3s ease',
    }}>
      <nav style={{
        maxWidth: 1280, margin: '0 auto',
        padding: '14px 5%',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      }}>
        <a href="#top" onClick={(e) => { e.preventDefault(); window.scrollTo({ top: 0, behavior: 'smooth' }); }}
          style={{ display: 'flex', alignItems: 'center', gap: 12, textDecoration: 'none' }}
          aria-label="Lumikode home"
        >
          <CompassLogo size={38} />
          <span style={{ fontSize: '1.5rem', letterSpacing: 2 }}>
            <span style={{ fontFamily: "'Cinzel', serif", color: colors.brandGold, fontWeight: 500 }}>Lumi</span>
            <span style={{ fontFamily: "'Courier Prime', monospace", color: colors.brandGreen, fontWeight: 700 }}>Kode</span>
          </span>
        </a>

        <div style={{ display: 'flex', alignItems: 'center', gap: 28 }}>
          <ul style={{ display: 'flex', gap: 26, listStyle: 'none', alignItems: 'center', margin: 0, padding: 0 }} className="nav-desktop">
            {navItems.map(item => (
              <li key={item.id}>
                <button
                  onClick={() => handleNavClick(item.id)}
                  style={{
                    background: 'none', border: 'none', cursor: 'pointer',
                    fontFamily: "'DM Sans', sans-serif",
                    fontSize: '0.85rem', letterSpacing: 0.5,
                    color: colors.textMuted, fontWeight: 400,
                    transition: 'color 0.3s', padding: '4px 0',
                  }}
                  onMouseEnter={e => e.target.style.color = colors.brandGold}
                  onMouseLeave={e => e.target.style.color = colors.textMuted}
                >
                  {item.label}
                </button>
              </li>
            ))}
          </ul>

          <button
            onClick={() => setLang(l => l === 'IT' ? 'EN' : 'IT')}
            style={{
              background: 'none', border: `1px solid rgba(255,215,0,0.25)`,
              borderRadius: 4, padding: '4px 10px',
              fontFamily: "'Courier Prime', monospace",
              fontSize: '0.7rem', color: colors.textGold,
              cursor: 'pointer', letterSpacing: 1, fontWeight: 600,
            }}
            aria-label="Cambia lingua"
            title="Cambia lingua"
          >{lang}</button>

          <button
            onClick={() => setIsMenuOpen(o => !o)}
            style={{
              display: 'none', background: 'none',
              border: 'none', color: colors.textPrimary,
              cursor: 'pointer', padding: 4,
            }}
            className="hamburger-btn"
            aria-label={isMenuOpen ? 'Chiudi menu' : 'Apri menu'}
          >
            <Icon name={isMenuOpen ? 'x' : 'menu'} size={24} />
          </button>
        </div>
      </nav>

      <AnimatePresence>
        {isMenuOpen && (
          <motion.div
            initial={{ opacity: 0, y: -20 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -20 }}
            style={{
              position: 'fixed', top: 68, left: 0, right: 0, bottom: 0,
              background: 'rgba(15,15,35,0.98)', backdropFilter: 'blur(20px)',
              display: 'flex', flexDirection: 'column',
              alignItems: 'center', justifyContent: 'center', gap: 24,
              zIndex: 999,
            }}
          >
            {navItems.map((item, i) => (
              <motion.button
                key={item.id}
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: i * 0.08 }}
                onClick={() => handleNavClick(item.id)}
                style={{
                  background: 'none', border: 'none', cursor: 'pointer',
                  fontFamily: "'Cinzel', serif",
                  fontSize: '1.4rem', color: colors.textPrimary,
                  letterSpacing: 2,
                }}
              >{item.label}</motion.button>
            ))}
          </motion.div>
        )}
      </AnimatePresence>

      <style>{`
        .nav-desktop { display: flex !important; }
        .hamburger-btn { display: none !important; }
        @media (max-width: 900px) {
          .nav-desktop { display: none !important; }
          .hamburger-btn { display: flex !important; }
        }
      `}</style>
    </header>
  );
}

// ============================================================
// FOOTER
// ============================================================
function Footer() {
  return (
    <footer style={{
      padding: '60px 5% 30px',
      background: colors.blackDeep,
      borderTop: `1px solid rgba(255,215,0,0.1)`,
    }}>
      <div style={{ maxWidth: 1080, margin: '0 auto' }}>
        <div style={{
          display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start',
          flexWrap: 'wrap', gap: 40, marginBottom: 40,
        }}>
          <div style={{ maxWidth: 320 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 14 }}>
              <CompassLogo size={32} />
              <span style={{ fontSize: '1.25rem', letterSpacing: 2 }}>
                <span style={{ fontFamily: "'Cinzel', serif", color: colors.brandGold, fontWeight: 500 }}>Lumi</span>
                <span style={{ fontFamily: "'Courier Prime', monospace", color: colors.brandGreen, fontWeight: 700 }}>Kode</span>
              </span>
            </div>
            <p style={{
              fontFamily: "'Cinzel', serif",
              fontSize: '0.85rem', color: colors.textGold,
              fontStyle: 'italic', marginBottom: 14, lineHeight: 1.5,
            }}>
              Dove l'esperienza incontra l'innovazione
            </p>
            <p style={{ fontSize: '0.75rem', color: colors.textDim, lineHeight: 1.6 }}>
              Modernizzazione IBM i enterprise<br />assistita da intelligenza artificiale multi-agente.
            </p>
          </div>

          <div>
            <h4 style={{
              fontSize: '0.7rem', color: colors.textMuted,
              textTransform: 'uppercase', letterSpacing: 2,
              marginBottom: 14, fontWeight: 600,
            }}>Navigazione</h4>
            <ul style={{ listStyle: 'none', display: 'flex', flexDirection: 'column', gap: 8, padding: 0, margin: 0 }}>
              {navItems.map(item => (
                <li key={item.id}>
                  <a href={`#${item.id}`}
                    style={{
                      color: colors.textMuted, fontSize: '0.82rem',
                      fontWeight: 300, transition: 'color 0.3s',
                      textDecoration: 'none',
                    }}
                    onMouseEnter={e => e.target.style.color = colors.brandGold}
                    onMouseLeave={e => e.target.style.color = colors.textMuted}
                  >{item.label}</a>
                </li>
              ))}
            </ul>
          </div>

          <div>
            <h4 style={{
              fontSize: '0.7rem', color: colors.textMuted,
              textTransform: 'uppercase', letterSpacing: 2,
              marginBottom: 14, fontWeight: 600,
            }}>Sede</h4>
            <p style={{ fontSize: '0.82rem', color: colors.textMuted, fontWeight: 300, lineHeight: 1.7 }}>
              Lumikode SRL<br />Modena, Italia<br />
              <span style={{ color: colors.textDim }}>lumikode.io · lumikode.it</span>
            </p>
          </div>

          <div>
            <h4 style={{
              fontSize: '0.7rem', color: colors.textMuted,
              textTransform: 'uppercase', letterSpacing: 2,
              marginBottom: 14, fontWeight: 600,
            }}>Social</h4>
            <a
              href="#"
              onClick={(e) => e.preventDefault()}
              style={{
                display: 'inline-flex', alignItems: 'center', gap: 8,
                color: colors.textMuted, fontSize: '0.82rem',
                transition: 'color 0.3s', textDecoration: 'none',
              }}
              onMouseEnter={e => e.currentTarget.style.color = colors.brandGold}
              onMouseLeave={e => e.currentTarget.style.color = colors.textMuted}
            >
              <Icon name="linkedin" size={16} />LinkedIn
            </a>
          </div>
        </div>

        <OrnamentalSeparator />
        <div style={{
          textAlign: 'center', paddingTop: 24,
          fontSize: '0.78rem', color: colors.textDim, fontWeight: 300,
        }}>
          © 2026 Lumikode SRL — Modena, Italia · Tutti i diritti riservati
        </div>
      </div>
    </footer>
  );
}

// Section heading (extracted from sections-1)
function SectionHeading({ eyebrow, title, sub, align = 'center' }) {
  return (
    <div style={{ textAlign: align }}>
      {eyebrow && (
        <div style={{
          fontFamily: "'Courier Prime', monospace",
          fontSize: '0.72rem', color: colors.textGold,
          letterSpacing: 3, textTransform: 'uppercase',
          marginBottom: 16, fontWeight: 600,
        }}>{eyebrow}</div>
      )}
      <h2 style={{
        fontFamily: "'Cinzel', serif",
        fontSize: 'clamp(1.9rem, 3.8vw, 3rem)',
        fontWeight: 500, color: colors.textPrimary,
        marginBottom: 16, letterSpacing: 0.5,
        textWrap: 'balance',
      }}>{title}</h2>
      {align === 'center' && <OrnamentalSeparator />}
      {sub && (
        <p style={{
          textAlign: align, color: colors.textMuted,
          maxWidth: align === 'center' ? 650 : '100%',
          margin: align === 'center' ? '28px auto 0' : '20px 0 0',
          fontSize: '1rem', lineHeight: 1.7, fontWeight: 300,
          textWrap: 'pretty',
        }}>{sub}</p>
      )}
    </div>
  );
}

// Export to window
Object.assign(window, {
  colors, useScrollPosition, useCounterAnimation,
  AnimatedSection, OrnamentalSeparator, Icon, LinkedinIcon, SectionHeading,
  CompassLogo, AiKoLogo, KodariLogo, LumiereLogo, LestageLogo,
  CircuitBoard, navItems,
});
