// Shared tokens, primitives, nav and footer for all Hero variations

// Moneyshape brand kit
const TOKENS = {
  bordeaux: '#5C0D07',       // Deep Meridian (primary)
  bordeauxDeep: '#3D0A0A',
  graphite: '#1D1D1D',        // Noir graphite
  paper: '#F9F7F6',           // Blanc cassé
  paperWarm: '#F3EFE8',
  // secondaries
  green: '#C8FF2E',           // Financement · Green Insight (for bg/badge)
  greenDark: '#3E7A00',       // darker green for text/stroke on light bg
  blue: '#7098F8',            // Rentabilité · Analytical Blue
  coral: '#F04924',           // Advise · Action Coral
  // functional aliases (kept for compatibility with existing components)
  accent: '#7098F8',          // Analytical blue → accent
  accentSoft: 'oklch(0.94 0.05 255)',
  accentGlow: 'rgba(112,152,248,0.35)',
  success: '#3E7A00',         // use darker green for text/stroke
  ink: '#1D1D1D',
  ink80: 'rgba(29,29,29,0.8)',
  ink60: 'rgba(29,29,29,0.58)',
  ink40: 'rgba(29,29,29,0.38)',
  ink12: 'rgba(29,29,29,0.12)',
  ink06: 'rgba(29,29,29,0.06)',
  line: 'rgba(29,29,29,0.08)',
};

const FONTS = {
  display: `'Manrope', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif`,
  sans: `'Manrope', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif`,
  mono: `'Geist Mono', 'SF Mono', 'Menlo', monospace`,
};

// ────────────────────────── primitives ──────────────────────────

function MSLogo({ color = TOKENS.bordeaux, size = 22 }) {
  // 3 versions officielles ; on pick selon la couleur demandée (sémantique)
  const src =
    color === '#fff' || color === 'white' ? 'assets/logo-moneyshape-blanc.png' :
    color === TOKENS.ink || color === '#000' || color === 'black' || color === '#1D1D1D' ? 'assets/logo-moneyshape-noir.png' :
    'assets/logo-moneyshape-bordeaux.png';
  // PNG ratio natif 7016×1228 ≈ 5.71:1
  const height = size * 1.35; // visuellement calibré vs l'ancien mark
  const width = height * 5.71;
  return (
    <img src={src} alt="Moneyshape" style={{
      height, width, display: 'block', objectFit: 'contain',
    }}/>
  );
}

function Nav({ onDark = false, scrolled = false, compact = false }) {
  // Scrolled state overrides onDark — becomes light/condensed
  const isDark = onDark && !scrolled;

  const link = {
    color: isDark ? 'rgba(255,255,255,0.82)' : TOKENS.ink80,
    fontSize: 14, fontFamily: FONTS.sans, textDecoration: 'none',
    fontWeight: 500, cursor: 'pointer',
    transition: 'color .3s ease',
  };

  const smoothScroll = (e) => {
    const href = e.currentTarget.getAttribute('href');
    if (!href || !href.startsWith('#')) return;
    const target = document.getElementById(href.slice(1));
    if (target) {
      e.preventDefault();
      target.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }
  };

  const pad = scrolled || compact ? '14px 56px' : '24px 56px';
  const bg = scrolled
    ? 'rgba(249,247,246,0.82)'
    : 'transparent';
  const borderBottom = scrolled ? `1px solid ${TOKENS.line}` : '1px solid transparent';
  const boxShadow = scrolled ? '0 4px 20px -8px rgba(29,29,29,0.08)' : 'none';

  return (
    <nav style={{
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      padding: pad,
      background: bg,
      backdropFilter: scrolled ? 'blur(18px) saturate(1.4)' : 'none',
      WebkitBackdropFilter: scrolled ? 'blur(18px) saturate(1.4)' : 'none',
      borderBottom,
      boxShadow,
      transition: 'padding .3s ease, background .3s ease, box-shadow .3s ease, border-color .3s ease',
    }}>
      <MSLogo color={isDark ? '#fff' : TOKENS.bordeaux}/>
      <div style={{ display: 'flex', gap: 36 }}>
        <a href="#comment-ca-marche" style={link} onClick={smoothScroll}>Comment ça marche</a>
        <a href="#fonctionnalites" style={link} onClick={smoothScroll}>Fonctionnalités</a>
        <a href="#temoignages" style={link} onClick={smoothScroll}>Témoignages</a>
      </div>
      <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
        <button data-cta-source="lpi_nav" style={{
          background: TOKENS.bordeaux, color: '#fff', border: 'none',
          padding: scrolled ? '12px 20px' : '14px 22px',
          borderRadius: 12, fontSize: 14, fontWeight: 600,
          fontFamily: FONTS.sans, cursor: 'pointer',
          display: 'inline-flex', alignItems: 'center', gap: 10,
          boxShadow: '0 10px 30px -5px rgba(92,13,7,0.4)',
          transition: 'padding .3s ease',
        }}>
          <span style={{
            width: 7, height: 7, borderRadius: 99,
            background: TOKENS.green,
            boxShadow: `0 0 10px ${TOKENS.green}`,
            animation: 'v5pulseDot 1.8s ease-in-out infinite',
          }}/>
          Démarrer maintenant
        </button>
      </div>
    </nav>
  );
}

// Sticky wrapper — listens to window scroll and toggles Nav into "scrolled" state
function StickyNav({ onDark = false, threshold = 80 }) {
  const [scrolled, setScrolled] = React.useState(false);
  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > threshold);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, [threshold]);
  return (
    <div style={{
      position: 'sticky', top: 0, zIndex: 100,
      width: '100%',
    }}>
      <Nav onDark={onDark} scrolled={scrolled}/>
    </div>
  );
}

// Small sparkline svg — procedural cashflow-ish line
function Sparkline({ width = 120, height = 32, color = TOKENS.accent, seed = 1, fill = true, stroke = 1.6 }) {
  const n = 24;
  const pts = [];
  let v = 0.4;
  for (let i = 0; i < n; i++) {
    // deterministic pseudo-random walk
    const r = Math.sin(i * 1.3 + seed * 2.7) * 0.5 + Math.cos(i * 0.7 + seed) * 0.3;
    v = Math.max(0.08, Math.min(0.92, v + r * 0.08 + 0.015));
    pts.push([i / (n - 1) * width, height - v * height]);
  }
  const d = pts.map((p, i) => (i ? 'L' : 'M') + p[0].toFixed(1) + ' ' + p[1].toFixed(1)).join(' ');
  const area = `${d} L ${width} ${height} L 0 ${height} Z`;
  const gid = 'sg' + seed + '-' + width;
  return (
    <svg width={width} height={height} style={{ display: 'block' }}>
      <defs>
        <linearGradient id={gid} x1="0" x2="0" y1="0" y2="1">
          <stop offset="0" stopColor={color} stopOpacity="0.25"/>
          <stop offset="1" stopColor={color} stopOpacity="0"/>
        </linearGradient>
      </defs>
      {fill && <path d={area} fill={`url(#${gid})`}/>}
      <path d={d} fill="none" stroke={color} strokeWidth={stroke} strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  );
}

// Animated number ticker
function Ticker({ value, prefix = '', suffix = '', decimals = 0, duration = 1400, style }) {
  const [n, setN] = React.useState(0);
  React.useEffect(() => {
    let raf, start;
    const step = (t) => {
      if (!start) start = t;
      const k = Math.min(1, (t - start) / duration);
      const eased = 1 - Math.pow(1 - k, 3);
      setN(value * eased);
      if (k < 1) raf = requestAnimationFrame(step);
    };
    raf = requestAnimationFrame(step);
    return () => cancelAnimationFrame(raf);
  }, [value, duration]);
  const formatted = n.toLocaleString('fr-FR', {
    minimumFractionDigits: decimals, maximumFractionDigits: decimals,
  });
  return <span style={style}>{prefix}{formatted}{suffix}</span>;
}

// Fake avatar group
function AvatarStack({ count = 5, dark = false }) {
  const initials = ['AD', 'PL', 'JH', 'ML', 'SB'];
  const bgs = ['#8B2828', '#1E3A8A', '#B83A1D', '#1F3D2B', '#4C1D95'];
  return (
    <div style={{ display: 'flex' }}>
      {initials.slice(0, count).map((s, i) => (
        <div key={i} style={{
          width: 30, height: 30, borderRadius: 99, background: bgs[i],
          color: '#fff', fontSize: 10, fontWeight: 600, fontFamily: FONTS.sans,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          marginLeft: i ? -10 : 0, border: `2px solid ${dark ? '#0E0E0F' : TOKENS.paper}`,
          zIndex: 10 - i,
        }}>{s}</div>
      ))}
    </div>
  );
}

// "Press" media logos — wordmark placeholders (text only, no fake brands)
function PressRow({ dark = false, label = 'Recommandé par' }) {
  const c = dark ? 'rgba(255,255,255,0.5)' : TOKENS.ink40;
  const names = ['LES ÉCHOS', 'CAPITAL', 'BFM BUSINESS', 'LE FIGARO', 'CHALLENGES'];
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 32, flexWrap: 'wrap' }}>
      <div style={{
        fontFamily: FONTS.mono, fontSize: 10, color: c,
        textTransform: 'uppercase', letterSpacing: 1.5,
      }}>{label}</div>
      {names.map(n => (
        <div key={n} style={{
          fontFamily: FONTS.sans, fontSize: 13, fontWeight: 600,
          color: c, letterSpacing: 1, opacity: 0.85,
        }}>{n}</div>
      ))}
    </div>
  );
}

// Placeholder image (striped) — for when we don't have real imagery
function PlaceholderImg({ label, w = '100%', h = '100%', radius = 12, dark = false }) {
  const base = dark ? '#1a1a1c' : '#e8e4dc';
  const stripe = dark ? '#222225' : '#dcd6cb';
  return (
    <div style={{
      width: w, height: h, borderRadius: radius, position: 'relative', overflow: 'hidden',
      background: `repeating-linear-gradient(135deg, ${base} 0 12px, ${stripe} 12px 24px)`,
    }}>
      <div style={{
        position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontFamily: FONTS.mono, fontSize: 10, color: dark ? 'rgba(255,255,255,0.4)' : TOKENS.ink40,
        textTransform: 'uppercase', letterSpacing: 2,
      }}>{label}</div>
    </div>
  );
}

// Badge with dot
function Tag({ children, color = TOKENS.accent, dark = false }) {
  return (
    <div style={{
      display: 'inline-flex', alignItems: 'center', gap: 8,
      padding: '6px 12px 6px 10px', borderRadius: 999,
      background: dark ? 'rgba(255,255,255,0.06)' : 'rgba(14,14,15,0.04)',
      border: `1px solid ${dark ? 'rgba(255,255,255,0.1)' : TOKENS.line}`,
      fontFamily: FONTS.mono, fontSize: 11, fontWeight: 500,
      color: dark ? 'rgba(255,255,255,0.85)' : TOKENS.ink80,
      letterSpacing: 0.3, whiteSpace: 'nowrap',
    }}>
      <span style={{
        width: 6, height: 6, borderRadius: 99, background: color,
        boxShadow: `0 0 10px ${color}`,
      }}/>
      {children}
    </div>
  );
}

// FixedNav — renders over hero with scroll-state detection via window.scrollY.
// Use at the top of a landing page; the hero below reserves ~76px via padding.
function FixedNav({ onDark = true, threshold = 120 }) {
  const [scrolled, setScrolled] = React.useState(false);
  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > threshold);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, [threshold]);
  return (
    <div style={{
      position: 'fixed', top: 0, left: 0, right: 0, zIndex: 100,
    }}>
      <Nav onDark={onDark} scrolled={scrolled}/>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Mobile Nav — logo + CTA only (no menu, no burger)
// 2 states, same pattern as desktop Nav
// ─────────────────────────────────────────────────────────────
function NavMobile({ onDark = false, scrolled = false }) {
  const isDark = onDark && !scrolled;

  const pad = scrolled ? '10px 16px' : '14px 20px';
  const bg = scrolled ? 'rgba(249,247,246,0.85)' : 'transparent';
  const borderBottom = scrolled ? `1px solid ${TOKENS.line}` : '1px solid transparent';
  const boxShadow = scrolled ? '0 4px 16px -8px rgba(29,29,29,0.1)' : 'none';

  return (
    <nav style={{
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      padding: pad,
      background: bg,
      backdropFilter: scrolled ? 'blur(16px) saturate(1.35)' : 'none',
      WebkitBackdropFilter: scrolled ? 'blur(16px) saturate(1.35)' : 'none',
      borderBottom,
      boxShadow,
      transition: 'padding .3s ease, background .3s ease, box-shadow .3s ease, border-color .3s ease',
    }}>
      <MSLogo size={20} color={isDark ? '#fff' : TOKENS.bordeaux}/>
      <button data-cta-source="lpi_nav-mobile" style={{
        background: TOKENS.bordeaux, color: '#fff', border: 'none',
        padding: scrolled ? '9px 14px' : '10px 16px',
        borderRadius: 10, fontSize: 13, fontWeight: 600,
        fontFamily: FONTS.sans, cursor: 'pointer',
        display: 'inline-flex', alignItems: 'center', gap: 8,
        boxShadow: '0 8px 24px -6px rgba(92,13,7,0.4)',
        transition: 'padding .3s ease',
      }}>
        <span style={{
          width: 6, height: 6, borderRadius: 99,
          background: TOKENS.green,
          boxShadow: `0 0 8px ${TOKENS.green}`,
          animation: 'v5pulseDot 1.8s ease-in-out infinite',
        }}/>
        Démarrer maintenant
      </button>
    </nav>
  );
}

// FixedNavMobile — sticky mobile nav with scroll-state detection
function FixedNavMobile({ onDark = true, threshold = 80 }) {
  const [scrolled, setScrolled] = React.useState(false);
  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > threshold);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, [threshold]);
  return (
    <div style={{
      position: 'fixed', top: 0, left: 0, right: 0, zIndex: 100,
      width: 390, margin: '0 auto',
    }}>
      <NavMobile onDark={onDark} scrolled={scrolled}/>
    </div>
  );
}

Object.assign(window, { StickyNav, FixedNav, NavMobile, FixedNavMobile });

