/* global React, ReactDOM */
const { useState, useEffect, useRef, useMemo } = React;

// =============== Tokens for inline JS use ===============
const T = {
  ink: '#080D1A',
  ink2: '#071228',
  ink3: '#0F1629',
  card: '#0c1a35',
  glass: 'rgba(8,18,40,0.55)',
  grid: 'rgba(26,32,56,0.4)',
  blue: '#1746f5',
  blueVivid: '#1B1EFF',
  blueMid: '#1a52ff',
  electric: '#4B6BFB',
  blueLight: '#6B8AFF',
  bluePale: '#eef2ff',
  blueMedium: '#1A2860',
  off: '#f4f6ff',
  light: '#eef1ff',
  ice: '#F0F2F8',
  white: '#FFFFFF',
  body: '#444444',
  muted: 'rgba(8,16,31,0.46)',
  whiteMuted: 'rgba(255,255,255,0.5)',
  whiteBody: 'rgba(255,255,255,0.6)',
  whiteSub: 'rgba(255,255,255,0.7)',
  ember: '#E8793A',
  green: '#2EE5A1',
  greenDark: '#10B981',
  violet: '#B69BFF',
  violetDeep: '#7C5BFF',
  fuchsia: '#FF3DA6',
  fuchsiaDeep: '#E5408C',
  borderDark: '0.5px solid rgba(255,255,255,0.07)',
  borderLight: '0.5px solid rgba(0,0,0,0.06)',
  borderPremium: '1.5px solid #4B6BFB',
  glowMd: '0 0 20px rgba(23,70,245,0.35)',
  glowLg: '0 0 28px rgba(23,70,245,0.35)',
  glowCta: '0 0 48px rgba(23,70,245,0.35), 0 8px 32px rgba(23,70,245,0.4)',
  serif: "'Archivo', 'Inter', 'DM Sans', system-ui, sans-serif",
  sans: "'Inter', 'DM Sans', system-ui, sans-serif",
  mono: "'DM Mono', ui-monospace, SFMono-Regular, Menlo, monospace",
};

// =============== Countdown to event ===============
// Event start: 16 Oct 2026, 09:00 CET
const EVENT_DATE = new Date('2026-10-16T09:00:00+02:00').getTime();

function useCountdown(target = EVENT_DATE) {
  const [now, setNow] = useState(Date.now());
  useEffect(() => {
    const i = setInterval(() => setNow(Date.now()), 1000);
    return () => clearInterval(i);
  }, []);
  const diff = Math.max(0, target - now);
  return {
    d: Math.floor(diff / 86400000),
    h: Math.floor((diff % 86400000) / 3600000),
    m: Math.floor((diff % 3600000) / 60000),
    s: Math.floor((diff % 60000) / 1000),
  };
}

// =============== Section header (eyebrow + h2 with italic accent) ===============
function Eyebrow({ children, accent = T.blueLight, dot = true, line = true, style }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 10,
      fontFamily: T.mono, fontSize: 11, fontWeight: 500,
      letterSpacing: '0.18em', textTransform: 'uppercase', color: accent,
      marginBottom: 18, ...style
    }}>
      {dot && <span style={{ width: 6, height: 6, borderRadius: '50%', background: accent }}/>}
      {children}
      {line && <span style={{ flex: 1, height: 1, background: 'rgba(107,138,255,0.2)' }}/>}
    </div>
  );
}

function H2({ children, dark = true, max = 800, style }) {
  return (
    <h2 style={{
      fontFamily: T.serif, fontWeight: 900,
      fontSize: 'clamp(34px, 4.2vw, 60px)',
      color: dark ? '#fff' : T.ink,
      lineHeight: 1.0, margin: '0 0 32px',
      letterSpacing: '-0.035em',
      maxWidth: max, textWrap: 'balance',
      ...style
    }}>{children}</h2>
  );
}

const Italic = ({ children, color = T.blueLight }) => (
  <em style={{ fontStyle: 'italic', color, fontWeight: 900, letterSpacing: '-0.02em' }}>{children}</em>
);

// =============== Buttons ===============
function PrimaryBtn({ children, href = '#ctalista', style, ember = false, green = false, onClick }) {
  const bg = ember ? T.ember : (green ? T.green : T.blue);
  const fg = green ? T.ink : '#fff';
  const glow = green ? '0 0 28px rgba(46,229,161,0.4)' : T.glowLg;
  const hoverGlow = green ? '0 0 48px rgba(46,229,161,0.5)' : T.glowCta;
  return (
    <a href={href} onClick={onClick} style={{
      display: 'inline-flex', alignItems: 'center', gap: 10,
      background: bg, color: fg,
      padding: '14px 26px', borderRadius: 8,
      fontSize: 14, fontWeight: 600, fontFamily: T.sans,
      letterSpacing: '0.01em',
      border: ember ? 'none' : (green ? '1px solid rgba(46,229,161,0.45)' : '1px solid rgba(79,128,255,0.4)'),
      boxShadow: ember ? 'none' : glow,
      textDecoration: 'none', transition: 'transform 0.3s, box-shadow 0.3s',
      ...style
    }}
      onMouseEnter={e => { e.currentTarget.style.transform = 'translateY(-2px)'; if (!ember) e.currentTarget.style.boxShadow = hoverGlow; }}
      onMouseLeave={e => { e.currentTarget.style.transform = 'translateY(0)'; if (!ember) e.currentTarget.style.boxShadow = glow; }}
    >
      {children}<span style={{ display: 'inline-block', transition: 'transform 0.3s' }}>→</span>
    </a>
  );
}

// =============== Handwritten arrow callout (signature MW touch) ===============
function ScribbleArrow({ children, rotation = -8, color = '#2EE5A1', style }) {
  return (
    <div style={{
      display: 'inline-flex', flexDirection: 'column', alignItems: 'center',
      transform: `rotate(${rotation}deg)`,
      fontFamily: '"Caveat", "Kalam", "Comic Sans MS", cursive',
      color, fontSize: 22, fontWeight: 600, letterSpacing: '0.01em',
      ...style,
    }}>
      <span style={{ whiteSpace: 'nowrap' }}>{children}</span>
      <svg width="80" height="50" viewBox="0 0 80 50" style={{ marginTop: 4 }}>
        <path d="M5,5 Q 30,15 45,35 Q 55,45 70,40" stroke={color} strokeWidth="2.5" fill="none" strokeLinecap="round"/>
        <path d="M62,32 L 72,40 L 64,46" stroke={color} strokeWidth="2.5" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
      </svg>
    </div>
  );
}

function GhostBtn({ children, href = '#', style, dark = true, onClick }) {
  return (
    <a href={href} onClick={onClick} style={{
      display: 'inline-flex', alignItems: 'center', gap: 10,
      background: 'transparent',
      color: dark ? T.whiteSub : T.ink,
      padding: '14px 26px', borderRadius: 8,
      fontSize: 14, fontWeight: 500, fontFamily: T.sans,
      border: dark ? '0.5px solid rgba(255,255,255,0.2)' : '0.5px solid rgba(0,0,0,0.12)',
      textDecoration: 'none', transition: 'border-color 0.3s, color 0.3s',
      ...style
    }}
      onMouseEnter={e => {
        e.currentTarget.style.borderColor = dark ? 'rgba(255,255,255,0.4)' : 'rgba(0,0,0,0.3)';
        e.currentTarget.style.color = dark ? '#fff' : T.ink;
      }}
      onMouseLeave={e => {
        e.currentTarget.style.borderColor = dark ? 'rgba(255,255,255,0.2)' : 'rgba(0,0,0,0.12)';
        e.currentTarget.style.color = dark ? T.whiteSub : T.ink;
      }}
    >
      {children}
    </a>
  );
}

// =============== Section wrapper ===============
function Section({ id, children, className = '', dark = true, grid = true, style, containerStyle, maxW = 1240, pad = '120px 56px' }) {
  const baseCls = dark && grid ? 'grid-bg' : '';
  const cls = [baseCls, className].filter(Boolean).join(' ');
  return (
    <section id={id} className={cls} style={{
      position: 'relative',
      padding: pad,
      background: dark ? T.ink : T.off,
      color: dark ? '#fff' : T.ink,
      overflow: 'hidden',
      ...style
    }}>
      <div style={{ position: 'relative', maxWidth: maxW, margin: '0 auto', ...containerStyle }}>
        {children}
      </div>
    </section>
  );
}

// =============== Tech-style placeholder image (striped with mono caption) ===============
function StripeImg({ label, ratio = '4/5', radius = 12, color = T.blueLight }) {
  return (
    <div style={{
      width: '100%', aspectRatio: ratio, borderRadius: radius,
      background: `repeating-linear-gradient(135deg, rgba(75,107,251,0.06) 0 8px, rgba(255,255,255,0.015) 8px 16px), ${T.card}`,
      border: T.borderDark, position: 'relative', overflow: 'hidden',
    }}>
      <div style={{
        position: 'absolute', inset: 0, display: 'flex',
        alignItems: 'center', justifyContent: 'center',
        fontFamily: T.mono, fontSize: 10, letterSpacing: '0.18em',
        textTransform: 'uppercase', color: 'rgba(255,255,255,0.35)',
      }}>{label}</div>
      <div style={{ position: 'absolute', top: 8, left: 8, fontFamily: T.mono, fontSize: 9, color, opacity: 0.6 }}>┌</div>
      <div style={{ position: 'absolute', top: 8, right: 8, fontFamily: T.mono, fontSize: 9, color, opacity: 0.6 }}>┐</div>
      <div style={{ position: 'absolute', bottom: 8, left: 8, fontFamily: T.mono, fontSize: 9, color, opacity: 0.6 }}>└</div>
      <div style={{ position: 'absolute', bottom: 8, right: 8, fontFamily: T.mono, fontSize: 9, color, opacity: 0.6 }}>┘</div>
    </div>
  );
}

// =============== Photo with overlay frame (used for speaker portraits) ===============
function Photo({ src, alt, ratio = '1/1', radius = 12, dim = false }) {
  return (
    <div style={{
      width: '100%', aspectRatio: ratio, borderRadius: radius,
      overflow: 'hidden', position: 'relative',
      background: T.card, border: T.borderDark,
    }}>
      {src ? (
        <img src={src} alt={alt} loading="lazy"
          style={{
            width: '100%', height: '100%', objectFit: 'cover',
            display: 'block', filter: dim ? 'grayscale(0.2) brightness(0.92)' : 'none'
          }}
        />
      ) : (
        <div style={{
          position: 'absolute', inset: 0,
          background: `repeating-linear-gradient(135deg, rgba(75,107,251,0.08) 0 8px, transparent 8px 16px)`
        }}/>
      )}
    </div>
  );
}

// =============== Reveal on scroll ===============
function Reveal({ children, delay = 0, as = 'div', style }) {
  const ref = useRef(null);
  const [visible, setVisible] = useState(false);
  useEffect(() => {
    if (!ref.current) return;
    // Fire immediately on mount, then re-trigger only if scrolled in via observer
    const fire = () => setVisible(true);
    const t = setTimeout(fire, 50 + delay);
    const o = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) { fire(); o.disconnect(); }
    }, { threshold: 0.05, rootMargin: '0px 0px -10% 0px' });
    o.observe(ref.current);
    return () => { clearTimeout(t); o.disconnect(); };
  }, [delay]);
  const El = as;
  return (
    <El ref={ref} style={{
      opacity: visible ? 1 : 0,
      transform: visible ? 'translateY(0)' : 'translateY(22px)',
      transition: `opacity 0.7s ease ${delay}ms, transform 0.7s ease ${delay}ms`,
      ...style
    }}>{children}</El>
  );
}

// =============== Exports ===============
Object.assign(window, {
  T, useCountdown, Eyebrow, H2, Italic, PrimaryBtn, GhostBtn,
  Section, StripeImg, Photo, Reveal, ScribbleArrow, EVENT_DATE,
  CountUp, LightEyebrow, LightH2, LightPrimary, LightGhost, useInView,
});

// =============== useInView hook (for in-viewport triggers) ===============
function useInView(threshold = 0.2, once = true) {
  const ref = useRef(null);
  const [seen, setSeen] = useState(false);
  useEffect(() => {
    if (!ref.current) return;
    const o = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) {
        setSeen(true);
        if (once) o.disconnect();
      } else if (!once) {
        setSeen(false);
      }
    }, { threshold });
    o.observe(ref.current);
    return () => o.disconnect();
  }, [threshold, once]);
  return [ref, seen];
}

// =============== CountUp animation ===============
function CountUp({ to, duration = 1600, prefix = '', suffix = '', decimals = 0, format = false, style }) {
  const [ref, seen] = useInView(0.4, true);
  const [val, setVal] = useState(0);
  useEffect(() => {
    if (!seen) return;
    const start = performance.now();
    const from = 0;
    let raf;
    const step = (t) => {
      const k = Math.min(1, (t - start) / duration);
      const eased = 1 - Math.pow(1 - k, 3);
      setVal(from + (to - from) * eased);
      if (k < 1) raf = requestAnimationFrame(step);
    };
    raf = requestAnimationFrame(step);
    return () => cancelAnimationFrame(raf);
  }, [seen, to, duration]);
  const display = decimals === 0 ? Math.round(val) : val.toFixed(decimals);
  const formatted = format ? Number(display).toLocaleString('it-IT') : display;
  return (
    <span ref={ref} style={style}>
      {prefix}{formatted}{suffix}
    </span>
  );
}

// =============== Light theme helpers ===============
function LightEyebrow({ children, accent = '#1746f5', style }) {
  return (
    <div style={{
      display: 'inline-flex', alignItems: 'center', gap: 10,
      padding: '6px 14px',
      borderRadius: 40, background: 'rgba(23,70,245,0.06)',
      border: '1px solid rgba(23,70,245,0.16)',
      fontFamily: T.mono, fontSize: 10, fontWeight: 500,
      letterSpacing: '0.18em', textTransform: 'uppercase', color: accent,
      ...style,
    }}>
      <span style={{ width: 6, height: 6, borderRadius: '50%', background: accent }}/>
      {children}
    </div>
  );
}

function LightH2({ children, max = 800, style, centered = false }) {
  return (
    <h2 style={{
      fontFamily: T.serif, fontWeight: 900,
      fontSize: 'clamp(38px, 4.6vw, 68px)',
      color: T.ink,
      lineHeight: 1.0, margin: '20px 0 24px',
      letterSpacing: '-0.035em',
      maxWidth: max, textWrap: 'balance',
      ...(centered ? { textAlign: 'center', margin: '20px auto 24px' } : null),
      ...style,
    }}>{children}</h2>
  );
}

function LightPrimary({ children, href = '#prenota-call', style, onClick, big = false, green = false }) {
  const bg = green ? T.green : T.blue;
  const fg = green ? T.ink : '#fff';
  return (
    <a href={href} onClick={onClick} style={{
      display: 'inline-flex', alignItems: 'center', gap: 10,
      background: bg, color: fg,
      padding: big ? '18px 32px' : '14px 26px', borderRadius: 999,
      fontSize: big ? 16 : 14, fontWeight: 600, fontFamily: T.sans,
      letterSpacing: '0.005em',
      border: green ? '1px solid rgba(46,229,161,0.45)' : '1px solid rgba(23,70,245,0.4)',
      boxShadow: green ? '0 10px 30px rgba(46,229,161,0.25)' : '0 10px 30px rgba(23,70,245,0.28)',
      textDecoration: 'none',
      transition: 'transform 0.3s, box-shadow 0.3s, background 0.3s',
      ...style,
    }}
      onMouseEnter={e => {
        e.currentTarget.style.transform = 'translateY(-2px)';
        e.currentTarget.style.boxShadow = green
          ? '0 16px 40px rgba(46,229,161,0.40)'
          : '0 16px 40px rgba(23,70,245,0.40)';
      }}
      onMouseLeave={e => {
        e.currentTarget.style.transform = 'translateY(0)';
        e.currentTarget.style.boxShadow = green
          ? '0 10px 30px rgba(46,229,161,0.25)'
          : '0 10px 30px rgba(23,70,245,0.28)';
      }}
    >
      {children}<span style={{ display: 'inline-block' }}>→</span>
    </a>
  );
}

function LightGhost({ children, href = '#', style, onClick, big = false }) {
  return (
    <a href={href} onClick={onClick} style={{
      display: 'inline-flex', alignItems: 'center', gap: 10,
      background: 'transparent', color: T.ink,
      padding: big ? '18px 32px' : '14px 26px', borderRadius: 999,
      fontSize: big ? 16 : 14, fontWeight: 600, fontFamily: T.sans,
      border: '1px solid rgba(8,16,31,0.18)',
      textDecoration: 'none', transition: 'all 0.25s',
      ...style,
    }}
      onMouseEnter={e => {
        e.currentTarget.style.borderColor = T.ink;
        e.currentTarget.style.background = T.ink;
        e.currentTarget.style.color = '#fff';
      }}
      onMouseLeave={e => {
        e.currentTarget.style.borderColor = 'rgba(8,16,31,0.18)';
        e.currentTarget.style.background = 'transparent';
        e.currentTarget.style.color = T.ink;
      }}
    >
      {children}
    </a>
  );
}

// =============== VideoModal — fullscreen video popup via Portal ===============
// Renderizzato dentro document.body via createPortal per non essere intrappolato
// dagli stacking context dei parent (transform, backdrop-filter, ecc).
// type: 'video' (MP4 src) o 'youtube' (videoId).
function VideoModal({ open, onClose, type, src }) {
  useEffect(() => {
    if (!open) return;
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => {
      document.body.style.overflow = prev;
      window.removeEventListener('keydown', onKey);
    };
  }, [open, onClose]);

  if (!open) return null;

  const inner = (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.92)',
      display: 'grid', placeItems: 'center', zIndex: 999, padding: 16,
    }}>
      <button
        onClick={(e) => { e.stopPropagation(); onClose(); }}
        aria-label="Chiudi video"
        style={{
          position: 'fixed', top: 16, right: 16,
          width: 44, height: 44, borderRadius: '50%',
          background: 'rgba(255,255,255,0.1)', border: '1px solid rgba(255,255,255,0.25)',
          color: '#fff', fontSize: 22, lineHeight: 1, cursor: 'pointer',
          display: 'grid', placeItems: 'center', zIndex: 1000,
        }}>
        ×
      </button>
      <div onClick={(e) => e.stopPropagation()} style={{
        width: 'min(96vw, 1200px)', aspectRatio: '16/9',
        background: '#000', borderRadius: 12, overflow: 'hidden',
      }}>
        {type === 'youtube' ? (
          <iframe
            src={`https://www.youtube-nocookie.com/embed/${src}?autoplay=1&rel=0&modestbranding=1&playsinline=1`}
            title="Video"
            allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
            allowFullScreen
            style={{ width: '100%', height: '100%', border: 0, display: 'block' }}
          />
        ) : (
          <video
            src={src}
            controls
            autoPlay
            playsInline
            controlsList="nodownload"
            style={{ width: '100%', height: '100%', display: 'block', background: '#000' }}
          >
            Il tuo browser non supporta il tag video.
          </video>
        )}
      </div>
    </div>
  );

  return ReactDOM.createPortal(inner, document.body);
}
