// ============================================================
// NOMERUS · MARKETING SITE (public-facing)
// Shares QT design tokens with the dashboard
// ============================================================

const W = {
  bg: "#06080F",
  bgAlt: "#0B0F1C",
  panel: "#0B0F1C",
  panel2: "#10162A",
  border: "rgba(124, 158, 255, 0.12)",
  borderStrong: "rgba(124, 158, 255, 0.22)",
  text: "#E5EAFF",
  textDim: "#8A93B8",
  textMute: "#5A6388",
  indigo: "#7C9EFF",
  indigoSoft: "rgba(124, 158, 255, 0.12)",
  violet: "#A78BFA",
  green: "#5BD99A",
  red: "#FF6B7A",
  amber: "#FFB454",
  mono: "'JetBrains Mono', ui-monospace, monospace",
  sans: "'Inter', system-ui, sans-serif",
};

// ──────────────────────────────────────────────────────────────
// MOTION PRIMITIVES — scroll reveals (shared across all pages)
// ──────────────────────────────────────────────────────────────
const nmReduced = () => {
  try { return !!(window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches); }
  catch (e) { return false; }
};

// Returns [ref, seen] — `seen` flips true once the element enters the
// viewport (and stays true). Falls back to visible if IO is unavailable
// or the user prefers reduced motion.
const useInView = (opts) => {
  const ref = React.useRef(null);
  const [seen, setSeen] = React.useState(false);
  React.useEffect(() => {
    if (nmReduced()) { setSeen(true); return; }
    const el = ref.current;
    if (!el || typeof IntersectionObserver === "undefined") { setSeen(true); return; }
    const obs = new IntersectionObserver((entries) => {
      for (const e of entries) {
        if (e.isIntersecting) { setSeen(true); obs.disconnect(); break; }
      }
    }, Object.assign({ threshold: 0.12, rootMargin: "0px 0px -6% 0px" }, opts || {}));
    obs.observe(el);
    return () => obs.disconnect();
  }, []);
  return [ref, seen];
};

// Single block that fades + rises into view. `delay`/`y`/`dur` tune it.
const Reveal = ({ children, delay = 0, y = 20, dur = 700, style, className, ...rest }) => {
  const [ref, seen] = useInView();
  const reduced = nmReduced();
  return (
    <div ref={ref} className={className} style={{
      opacity: seen ? 1 : 0,
      transform: seen ? "none" : `translateY(${y}px)`,
      transition: reduced ? "none" : `opacity ${dur}ms var(--ease-out-expo) ${delay}ms, transform ${dur}ms var(--ease-out-expo) ${delay}ms`,
      willChange: "opacity, transform",
      ...(style || {}),
    }} {...rest}>
      {children}
    </div>
  );
};

// Grid/row container — children with className "reveal-item" + style
// {"--ri": index} stagger in once the group is visible.
const RevealGroup = ({ children, style, className = "", ...rest }) => {
  const [ref, seen] = useInView();
  return (
    <div ref={ref} className={`reveal-group${seen ? " in" : ""}${className ? " " + className : ""}`} style={style} {...rest}>
      {children}
    </div>
  );
};

// ──────────────────────────────────────────────────────────────
// PUBLIC TOP NAV
// ──────────────────────────────────────────────────────────────
const WNav = ({ route, go }) => {
  const [scrolled, setScrolled] = React.useState(false);
  const [menuOpen, setMenuOpen] = React.useState(false);
  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 8);
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  // Referme le menu mobile à chaque changement de route.
  React.useEffect(() => { setMenuOpen(false); }, [route]);
  const items = [
    { id: "features", label: "Fonctionnalités" },
    { id: "pricing",  label: "Tarifs" },
    { id: "brokers",  label: "Brokers" },
  ];
  const goAndClose = (r) => { setMenuOpen(false); go(r); };
  return (
    <header className={scrolled ? "w-nav-scrolled" : ""} style={{
      position: "sticky", top: 0, zIndex: 50,
      backdropFilter: "blur(12px)", background: scrolled ? "rgba(6, 8, 15, 0.9)" : "rgba(6, 8, 15, 0.72)",
      borderBottom: `1px solid ${scrolled ? W.borderStrong : W.border}`,
      transition: "background 0.3s ease, border-color 0.3s ease, box-shadow 0.3s ease",
    }}>
      <div style={{
        maxWidth: 1280, margin: "0 auto",
        padding: "14px 28px",
        display: "flex", alignItems: "center", gap: 28,
      }}>
        {/* Logo */}
        <button onClick={() => go("landing")} style={{
          display: "flex", alignItems: "center", gap: 10,
          background: "transparent", border: "none", cursor: "pointer", padding: 0,
        }}>
          <img src="/assets/nomerus-logo.png" alt="Nomerus" width="28" height="28"
            style={{ width: 28, height: 28, borderRadius: 6, display: "block" }}/>
          <div style={{ textAlign: "left" }}>
            <div style={{ fontFamily: W.sans, fontSize: 14, fontWeight: 700, color: W.text, letterSpacing: 0.5, lineHeight: 1 }}>NOMERUS</div>
            <div style={{ fontFamily: W.mono, fontSize: 8.5, color: W.textMute, letterSpacing: 1.4, marginTop: 2 }}>QUANT TERMINAL</div>
          </div>
        </button>

        {/* Nav links (desktop) */}
        <nav className="w-nav-desktop" style={{ display: "flex", alignItems: "center", gap: 4, marginLeft: 12 }}>
          {items.map(it => (
            <button key={it.id} onClick={() => go(it.id)}
              className="w-nav-link"
              style={{
                background: "transparent", border: "none", cursor: "pointer",
                color: route === it.id ? W.text : W.textDim,
                fontFamily: W.sans, fontSize: 13, fontWeight: 500,
                padding: "6px 12px", borderRadius: 4,
              }}>
              {it.label}
            </button>
          ))}
        </nav>

        <div style={{ flex: 1 }}/>

        {/* Status pill (desktop) */}
        <span className="w-nav-status" style={{
          display: "inline-flex", alignItems: "center", gap: 6,
          fontFamily: W.mono, fontSize: 10, color: W.textDim, letterSpacing: 1,
        }}>
          <span className="nm-dot" style={{ width: 6, height: 6, borderRadius: "50%", background: W.green, boxShadow: `0 0 8px ${W.green}` }}/>
          PLAN GRATUIT · SANS CARTE
        </span>

        <button onClick={() => go("login")} className="w-nav-link w-nav-desktop" style={{
          background: "transparent", border: "none", cursor: "pointer",
          color: W.text, fontFamily: W.sans, fontSize: 13, fontWeight: 500,
          padding: "6px 12px",
        }}>
          Se connecter
        </button>
        <button onClick={() => go("signup")} className="w-btn-primary w-cta w-nav-desktop" style={{
          background: W.indigo, color: W.bg, border: "none", cursor: "pointer",
          padding: "8px 14px", borderRadius: 4,
          fontFamily: W.mono, fontSize: 11, fontWeight: 700, letterSpacing: 1.5,
        }}>
          COMMENCER →
        </button>

        {/* Burger (mobile) */}
        <button
          className="w-nav-burger"
          aria-label={menuOpen ? "Fermer le menu" : "Ouvrir le menu"}
          aria-expanded={menuOpen}
          onClick={() => setMenuOpen(o => !o)}
          style={{
            width: 38, height: 38, alignItems: "center", justifyContent: "center",
            background: "transparent", border: `1px solid ${W.border}`, borderRadius: 6,
            color: W.text, cursor: "pointer", flexDirection: "column", gap: 4,
          }}>
          {menuOpen ? (
            <span style={{ fontFamily: W.sans, fontSize: 18, lineHeight: 1 }}>✕</span>
          ) : (
            <>
              <span style={{ display: "block", width: 16, height: 1.5, background: W.text }}/>
              <span style={{ display: "block", width: 16, height: 1.5, background: W.text }}/>
              <span style={{ display: "block", width: 16, height: 1.5, background: W.text }}/>
            </>
          )}
        </button>
      </div>

      {/* Menu déroulant mobile */}
      {menuOpen && (
        <nav style={{
          borderTop: `1px solid ${W.border}`,
          background: "rgba(6, 8, 15, 0.97)",
          padding: "10px 20px 18px",
          display: "flex", flexDirection: "column", gap: 2,
        }}>
          {items.map(it => (
            <button key={it.id} onClick={() => goAndClose(it.id)}
              className="w-nav-link"
              style={{
                background: "transparent", border: "none", cursor: "pointer",
                color: route === it.id ? W.text : W.textDim, textAlign: "left",
                fontFamily: W.sans, fontSize: 15, fontWeight: 500,
                padding: "12px 8px", borderRadius: 4,
              }}>
              {it.label}
            </button>
          ))}
          <button onClick={() => goAndClose("login")} className="w-nav-link" style={{
            background: "transparent", border: "none", cursor: "pointer",
            color: W.text, textAlign: "left", fontFamily: W.sans, fontSize: 15, fontWeight: 500,
            padding: "12px 8px", borderRadius: 4,
          }}>
            Se connecter
          </button>
          <button onClick={() => goAndClose("signup")} className="w-btn-primary w-cta" style={{
            background: W.indigo, color: W.bg, border: "none", cursor: "pointer",
            padding: "13px 14px", borderRadius: 4, marginTop: 8,
            fontFamily: W.mono, fontSize: 12, fontWeight: 700, letterSpacing: 1.5,
          }}>
            COMMENCER →
          </button>
        </nav>
      )}
    </header>
  );
};

// ──────────────────────────────────────────────────────────────
// FOOTER
// ──────────────────────────────────────────────────────────────
const WFooter = ({ go }) => {
  // Each link is { label, route } (SPA router), { label, mailto } (email),
  // or { label } (placeholder href="#" until the page is actually built).
  const cols = [
    { title: "PRODUIT", links: [
      { label: "Fonctionnalités", route: "features" },
      { label: "Tarifs",          route: "pricing" },
      { label: "Brokers",         route: "brokers" },
    ] },
    { title: "ENTREPRISE", links: [
      { label: "À propos", route: "about" },
      { label: "Contact",  route: "contact" },
    ] },
    { title: "LÉGAL", links: [
      { label: "Mentions légales",         route: "legal" },
      { label: "Conditions d'utilisation", route: "terms" },
      { label: "Confidentialité",          route: "privacy" },
      { label: "Avertissement risque",     route: "risk" },
      { label: "Gérer les cookies",        action: () => { if (window.NomerusAnalytics && window.NomerusAnalytics.openConsent) window.NomerusAnalytics.openConsent(); } },
    ] },
  ];
  return (
    <footer style={{ borderTop: `1px solid ${W.border}`, background: W.panel, marginTop: 80 }}>
      <div style={{ maxWidth: 1280, margin: "0 auto", padding: "56px 28px 24px" }}>
        <window.RevealGroup className="w-stack" style={{ display: "grid", gridTemplateColumns: "1.6fr 1fr 1fr 1fr", gap: 40 }}>
          <div className="reveal-item" style={{ "--ri": 0 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 12 }}>
              <img src="/assets/nomerus-logo.png" alt="Nomerus" width="28" height="28"
                style={{ width: 28, height: 28, borderRadius: 6, display: "block" }}/>
              <div style={{ fontFamily: W.sans, fontSize: 14, fontWeight: 700, color: W.text, letterSpacing: 0.5 }}>NOMERUS</div>
            </div>
            <p style={{ fontFamily: W.sans, fontSize: 12, color: W.textDim, lineHeight: 1.6, maxWidth: 240, margin: 0 }}>
              Le journal de trading qui te débrieffe comme un coach. Import CSV, vraies stats, debrief IA sur tes propres trades — et Le Brief, le journal des marchés.
            </p>
            <div style={{ marginTop: 18, fontFamily: W.mono, fontSize: 10, color: W.textMute, letterSpacing: 1.5 }}>
              © 2026 NOMERUS · PROJET INDIE
            </div>
          </div>
          {cols.map((c, ci) => (
            <div key={c.title} className="reveal-item" style={{ "--ri": ci + 1 }}>
              <div style={{ fontFamily: W.mono, fontSize: 10, color: W.textMute, letterSpacing: 1.8, marginBottom: 14 }}>{c.title}</div>
              <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
                {c.links.map(l => (l.route || l.action) ? (
                  <button key={l.label} onClick={() => l.action ? l.action() : go(l.route)} className="w-nav-link" style={{
                    background: "transparent", border: "none", padding: 0, cursor: "pointer",
                    textAlign: "left", fontFamily: W.sans, fontSize: 13, color: W.textDim,
                  }}>{l.label}</button>
                ) : l.mailto ? (
                  <a key={l.label} href={`mailto:${l.mailto}`} style={{ fontFamily: W.sans, fontSize: 13, color: W.textDim, textDecoration: "none" }}>{l.label}</a>
                ) : (
                  <a key={l.label} href="#" style={{ fontFamily: W.sans, fontSize: 13, color: W.textDim, textDecoration: "none" }}>{l.label}</a>
                ))}
              </div>
            </div>
          ))}
        </window.RevealGroup>

        <div style={{
          marginTop: 48, paddingTop: 20, borderTop: `1px solid ${W.border}`,
          display: "flex", flexWrap: "wrap", gap: 14, justifyContent: "space-between",
          fontFamily: W.mono, fontSize: 10, color: W.textMute, letterSpacing: 1.4,
        }}>
          <div>NOMERUS v1.0.0 · CONSTRUIT EN INDIE · MADE IN 🇨🇭</div>
          <div style={{ color: W.amber }}>
            ⚠ Le trading comporte des risques. Les performances passées ≠ futures.
          </div>
        </div>
      </div>
    </footer>
  );
};

window.W = W;
window.WNav = WNav;
window.WFooter = WFooter;
window.useInView = useInView;
window.Reveal = Reveal;
window.RevealGroup = RevealGroup;
window.nmReduced = nmReduced;
