/* ── KREDOO SHARED ────────────────────────────────────────────────────── */

const { useState, useEffect, useRef, useMemo, useCallback } = React;

/* ── LOGO ─────────────────────────────────────────────────────────────── */
function KredooLogo({ size = 32, tone = "dark", showByline = true }) {
  return (
    <a href="/" style={{ display: "inline-flex", alignItems: "center", position: "relative", textDecoration: "none" }}>
      <img
        src="/kredoo-logo-transparent.png"
        alt="Kredoo"
        style={{
          height: size,
          width: "auto",
          objectFit: "contain",
          display: "block",
          filter: tone === "light" ? "brightness(0) invert(1)" : "none",
        }}
      />
      {showByline && (
        <span style={{
          position: "absolute", left: 6, top: "100%",
          marginTop: -2,
          font: '800 8px/1 "Plus Jakarta Sans",sans-serif',
          letterSpacing: ".22em", textTransform: "uppercase",
          color: tone === "light" ? "rgba(255,255,255,.6)" : "var(--indigo)",
          whiteSpace: "nowrap"
        }}>
          By Elevaite Labs
        </span>
      )}
    </a>
  );
}

/* ── PARTICLE FIELD (full-bleed) ─────────────────────────────────────── */
function ParticleField({ density = 70, color = "#3b82f6", opacity = 0.45, accent = "#C9A227", connect = true, speed = 0.35 }) {
  const canvasRef = useRef(null);
  const rafRef = useRef(0);
  const stateRef = useRef({ pts: [], w: 0, h: 0, dpr: 1 });

  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext("2d");
    const s = stateRef.current;

    function resize() {
      const dpr = Math.min(window.devicePixelRatio || 1, 2);
      const rect = canvas.parentElement.getBoundingClientRect();
      s.w = rect.width; s.h = rect.height; s.dpr = dpr;
      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);
      s.pts = Array.from({ length: density }, () => ({
        x: Math.random() * s.w,
        y: Math.random() * s.h,
        vx: (Math.random() - 0.5) * speed,
        vy: (Math.random() - 0.5) * speed,
        r: Math.random() * 1.6 + 0.6,
        gold: Math.random() < 0.12,
      }));
    }

    function tick() {
      ctx.clearRect(0, 0, s.w, s.h);
      const pts = s.pts;
      // connections
      if (connect) {
        for (let i = 0; i < pts.length; i++) {
          for (let j = i + 1; j < pts.length; j++) {
            const a = pts[i], b = pts[j];
            const dx = a.x - b.x, dy = a.y - b.y;
            const d2 = dx * dx + dy * dy;
            if (d2 < 110 * 110) {
              const alpha = (1 - d2 / (110 * 110)) * 0.35 * opacity;
              ctx.strokeStyle = `rgba(59,130,246,${alpha})`;
              ctx.lineWidth = 0.7;
              ctx.beginPath();
              ctx.moveTo(a.x, a.y);
              ctx.lineTo(b.x, b.y);
              ctx.stroke();
            }
          }
        }
      }
      // points
      for (const p of pts) {
        p.x += p.vx; p.y += p.vy;
        if (p.x < 0 || p.x > s.w) p.vx *= -1;
        if (p.y < 0 || p.y > s.h) p.vy *= -1;
        ctx.beginPath();
        ctx.fillStyle = p.gold ? accent : color;
        ctx.globalAlpha = p.gold ? 0.9 : opacity;
        ctx.arc(p.x, p.y, p.r, 0, Math.PI * 2);
        ctx.fill();
      }
      ctx.globalAlpha = 1;
      rafRef.current = requestAnimationFrame(tick);
    }

    resize();
    tick();
    const ro = new ResizeObserver(resize);
    ro.observe(canvas.parentElement);
    return () => { cancelAnimationFrame(rafRef.current); ro.disconnect(); };
  }, [density, color, accent, opacity, connect, speed]);

  return <canvas ref={canvasRef} style={{ position: "absolute", inset: 0, pointerEvents: "none" }} />;
}

/* ── ORBIT VISUAL (used on login page) ────────────────────────────────── */
function OrbitVisual({ size = 520 }) {
  const moons = useMemo(() => ([
    { r: 110, dur: 14, offset: 0,   color: "#3b82f6", icon: "meta" },
    { r: 110, dur: 14, offset: 0.5, color: "#10b981", icon: "check" },
    { r: 170, dur: 22, offset: 0.15, color: "#8b5cf6", icon: "spark" },
    { r: 170, dur: 22, offset: 0.7,  color: "#C9A227", icon: "star" },
    { r: 230, dur: 32, offset: 0,    color: "#ef4444", icon: "phone" },
    { r: 230, dur: 32, offset: 0.4,  color: "#0ea5e9", icon: "mail" },
    { r: 230, dur: 32, offset: 0.8,  color: "#f59e0b", icon: "chat" },
  ]), []);

  function Glyph({ kind }) {
    const sw = { strokeWidth: 2.2, strokeLinecap: "round", strokeLinejoin: "round", fill: "none", stroke: "#fff" };
    if (kind === "meta") return <svg viewBox="0 0 24 24" width="18" height="18" {...sw}><path d="M2 12c0-4 2-7 5-7s5 3 8 7 5 7 7 7c2 0 2-3 2-7 0-4-1-7-3-7-3 0-5 3-9 7s-5 7-7 7" /></svg>;
    if (kind === "check") return <svg viewBox="0 0 24 24" width="18" height="18" {...sw}><polyline points="20 6 9 17 4 12" /></svg>;
    if (kind === "spark") return <svg viewBox="0 0 24 24" width="18" height="18" {...sw}><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2" fill="#fff" stroke="none" /></svg>;
    if (kind === "star") return <svg viewBox="0 0 24 24" width="18" height="18" {...sw}><polygon points="12 2 15 9 22 9 16.5 13.5 18.5 21 12 17 5.5 21 7.5 13.5 2 9 9 9 12 2" fill="#fff" stroke="none" /></svg>;
    if (kind === "phone") return <svg viewBox="0 0 24 24" width="18" height="18" {...sw}><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6A19.79 19.79 0 0 1 2.12 4.18 2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z" /></svg>;
    if (kind === "mail") return <svg viewBox="0 0 24 24" width="18" height="18" {...sw}><path d="M4 4h16v16H4z" /><polyline points="22 6 12 13 2 6" /></svg>;
    if (kind === "chat") return <svg viewBox="0 0 24 24" width="18" height="18" {...sw}><path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z" /></svg>;
    return null;
  }

  return (
    <div style={{ position: "relative", width: size, height: size }}>
      {/* outer glow */}
      <div style={{
        position: "absolute", inset: 0, borderRadius: "50%",
        background: "radial-gradient(closest-side, rgba(201,162,39,.15), rgba(59,130,246,.08) 45%, transparent 70%)",
        filter: "blur(4px)",
      }} />

      {/* concentric rings */}
      {[110, 170, 230].map((r, i) => (
        <div key={r} style={{
          position: "absolute", left: "50%", top: "50%",
          width: r * 2, height: r * 2, marginLeft: -r, marginTop: -r,
          borderRadius: "50%",
          border: `1px ${i === 1 ? "dashed" : "solid"} rgba(15,23,42,.10)`,
          animation: `${i % 2 ? "kr-orbit-rev" : "kr-orbit"} ${60 + i * 20}s linear infinite`,
        }}>
          {i === 0 && (
            <span style={{
              position: "absolute", left: "50%", top: -3, width: 6, height: 6,
              borderRadius: "50%", background: "var(--gold)", boxShadow: "0 0 0 4px rgba(201,162,39,.18)",
              transform: "translateX(-50%)",
            }} />
          )}
        </div>
      ))}

      {/* moons */}
      {moons.map((m, i) => (
        <div key={i} style={{
          position: "absolute", left: "50%", top: "50%",
          width: m.r * 2, height: m.r * 2, marginLeft: -m.r, marginTop: -m.r,
          animation: `kr-orbit ${m.dur}s linear infinite`,
          animationDelay: `${-m.dur * m.offset}s`,
        }}>
          <div style={{
            position: "absolute", left: "50%", top: 0, transform: "translate(-50%,-50%)",
            width: 40, height: 40, borderRadius: 14,
            background: `linear-gradient(135deg,${m.color},${m.color}99)`,
            display: "grid", placeItems: "center",
            boxShadow: `0 10px 28px -8px ${m.color}66, inset 0 1px 0 rgba(255,255,255,.25)`,
          }}>
            <Glyph kind={m.icon} />
          </div>
        </div>
      ))}

      {/* core */}
      <div style={{
        position: "absolute", left: "50%", top: "50%", transform: "translate(-50%,-50%)",
        width: 124, height: 124, borderRadius: "50%",
        background: "radial-gradient(circle at 30% 30%, #1a2540, #0a0e1a 70%)",
        boxShadow: "0 30px 60px -16px rgba(10,14,26,.6), inset 0 2px 0 rgba(201,162,39,.32), 0 0 0 1px rgba(201,162,39,.18)",
        display: "grid", placeItems: "center",
      }}>
        <div style={{
          position: "absolute", inset: -12, borderRadius: "50%",
          background: "conic-gradient(from 0deg, transparent 0%, rgba(201,162,39,.45) 25%, transparent 50%, rgba(59,130,246,.4) 75%, transparent 100%)",
          animation: "kr-spin-slow 8s linear infinite",
          filter: "blur(8px)", opacity: .65,
        }} />
        {/* Kredoo monogram */}
        <svg width="56" height="56" viewBox="0 0 56 56" style={{ position: "relative" }}>
          <defs>
            <linearGradient id="kg" x1="0" x2="1" y1="0" y2="1">
              <stop offset="0" stopColor="#E0B842" />
              <stop offset="1" stopColor="#C9A227" />
            </linearGradient>
          </defs>
          <path d="M14 30 C8 30 5 25 5 20 C5 15 8 10 14 10 C18 10 21 12 23 15 L25 15 C27 12 30 10 34 10 C40 10 43 15 43 20 C43 25 40 30 34 30 C30 30 27 28 25 25 L23 25 C21 28 18 30 14 30 Z M14 16 C11 16 9 18 9 20 C9 22 11 24 14 24 C17 24 19 22 19 20 C19 18 17 16 14 16 Z M34 16 C31 16 29 18 29 20 C29 22 31 24 34 24 C37 24 39 22 39 20 C39 18 37 16 34 16 Z"
            fill="url(#kg)" transform="translate(2 8)" />
        </svg>
      </div>

      {/* faint perimeter dots */}
      {Array.from({ length: 24 }).map((_, i) => {
        const angle = (i / 24) * Math.PI * 2;
        const x = Math.cos(angle) * (size / 2 - 6);
        const y = Math.sin(angle) * (size / 2 - 6);
        return <span key={i} style={{
          position: "absolute", left: "50%", top: "50%",
          width: 3, height: 3, borderRadius: "50%",
          background: i % 6 === 0 ? "rgba(201,162,39,.7)" : "rgba(15,23,42,.18)",
          transform: `translate(${x - 1.5}px,${y - 1.5}px)`,
        }} />;
      })}
    </div>
  );
}

/* ── ANIMATED COUNTER ─────────────────────────────────────────────────── */
function Counter({ to, duration = 1600, suffix = "", prefix = "", className, style }) {
  const [val, setVal] = useState(0);
  const startRef = useRef(0);
  const rafRef = useRef(0);
  useEffect(() => {
    const start = performance.now();
    startRef.current = start;
    const ease = (t) => 1 - Math.pow(1 - t, 3);
    const step = (now) => {
      const t = Math.min(1, (now - start) / duration);
      setVal(Math.round(to * ease(t)));
      if (t < 1) rafRef.current = requestAnimationFrame(step);
    };
    rafRef.current = requestAnimationFrame(step);
    return () => cancelAnimationFrame(rafRef.current);
  }, [to, duration]);
  return <span className={className} style={style}>{prefix}{val.toLocaleString()}{suffix}</span>;
}

/* ── LIVE TICKER (rolling list of lead events) ───────────────────────── */
const TICKER_EVENTS = [
  { who: "Priya S.", action: "captured a new lead from", source: "Meta Ads",     color: "#1877F2", t: "just now" },
  { who: "Auto-flow", action: "sent WhatsApp follow-up to", source: "Rahul M.",  color: "#10b981", t: "2s ago" },
  { who: "Arjun K.",  action: "moved deal to",                 source: "Closed Won", color: "#059669", t: "8s ago" },
  { who: "Pipeline",  action: "scored new lead from",          source: "Google Ads", color: "#EA4335", t: "14s ago" },
  { who: "Sara R.",   action: "booked demo via",               source: "Booking Link", color: "#8b5cf6", t: "22s ago" },
  { who: "Auto-flow", action: "fired n8n workflow",            source: "Welcome Email", color: "#FF6D5A", t: "31s ago" },
  { who: "Vivek T.",  action: "added a note to",               source: "Acme Realty", color: "#C9A227", t: "48s ago" },
  { who: "Pipeline",  action: "tagged hot lead from",          source: "LinkedIn", color: "#0A66C2", t: "1m ago" },
];

function LiveTicker({ height = 56 }) {
  const [idx, setIdx] = useState(0);
  useEffect(() => {
    const t = setInterval(() => setIdx(i => (i + 1) % TICKER_EVENTS.length), 2200);
    return () => clearInterval(t);
  }, []);
  const ev = TICKER_EVENTS[idx];
  return (
    <div style={{
      height, padding: "0 14px",
      display: "flex", alignItems: "center", gap: 12,
      background: "#fff", border: "1px solid var(--line)", borderRadius: 16,
      boxShadow: "0 12px 32px -16px rgba(15,23,42,.18)",
      overflow: "hidden", position: "relative",
    }}>
      <span style={{
        flexShrink: 0, width: 8, height: 8, borderRadius: "50%",
        background: "#ef4444", boxShadow: "0 0 0 4px rgba(239,68,68,.18)",
        animation: "kr-pulse-dot 1.4s ease-in-out infinite",
      }} />
      <span className="mono" style={{ fontSize: 10, fontWeight: 600, letterSpacing: ".12em", color: "var(--muted-2)", textTransform: "uppercase" }}>LIVE</span>
      <div key={idx} style={{ animation: "kr-rise .4s var(--ease)", display: "flex", alignItems: "center", gap: 8, minWidth: 0, flex: 1 }}>
        <span style={{ fontSize: 12, fontWeight: 800, color: "var(--ink)", whiteSpace: "nowrap" }}>{ev.who}</span>
        <span style={{ fontSize: 12, fontWeight: 500, color: "var(--muted)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
          {ev.action} <span style={{ color: ev.color, fontWeight: 700 }}>{ev.source}</span>
        </span>
      </div>
      <span className="mono" style={{ fontSize: 10, color: "var(--muted-2)", whiteSpace: "nowrap" }}>{ev.t}</span>
    </div>
  );
}

/* ── CHECK ICON ──────────────────────────────────────────────────────── */
function Check({ size = 16, color = "var(--emerald)" }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
      <polyline points="20 6 9 17 4 12" />
    </svg>
  );
}

/* ── ARROW ───────────────────────────────────────────────────────────── */
function Arrow({ size = 16 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
      <line x1="5" y1="12" x2="19" y2="12" />
      <polyline points="12 5 19 12 12 19" />
    </svg>
  );
}

/* ── NAVBAR ──────────────────────────────────────────────────────────── */
function Navbar({ route }) {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const on = () => setScrolled(window.scrollY > 24);
    on();
    window.addEventListener("scroll", on, { passive: true });
    return () => window.removeEventListener("scroll", on);
  }, []);
  const isLanding = route === "" || route === "/";

  const scrollToSection = (id) => (e) => {
    e.preventDefault();
    const doScroll = () => {
      const el = document.getElementById(id);
      if (el) el.scrollIntoView({ behavior: "smooth", block: "start" });
    };
    if (isLanding) {
      doScroll();
    } else {
      window.location.hash = "/";
      setTimeout(doScroll, 120);
    }
  };
  return (
    <div style={{
      position: "fixed", top: 16, left: 0, right: 0, zIndex: 50,
      display: "flex", justifyContent: "center", padding: "0 16px",
      pointerEvents: "none",
    }}>
      <header style={{
        pointerEvents: "auto", width: "100%", maxWidth: 1040,
        borderRadius: 999,
        background: scrolled ? "rgba(255,255,255,.92)" : "rgba(255,255,255,.7)",
        backdropFilter: "blur(20px)", WebkitBackdropFilter: "blur(20px)",
        border: scrolled ? "1px solid rgba(255,255,255,.65)" : "1px solid rgba(255,255,255,.45)",
        boxShadow: scrolled ? "0 12px 40px rgba(0,0,0,.11)" : "0 8px 30px rgba(0,0,0,.06)",
        transition: "all .3s var(--ease)",
      }}>
        <div style={{ height: 60, padding: "0 8px 0 18px", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
          <KredooLogo size={28} />
          <nav style={{ display: "flex", alignItems: "center", gap: 4, fontSize: 13, fontWeight: 700, color: "var(--muted)" }} className="kr-navlinks">
            <a href="/" onClick={scrollToSection("how-it-works")} style={{ height: 36, padding: "0 14px", borderRadius: 999, display: "inline-flex", alignItems: "center", cursor: "pointer" }}>Product</a>
            <a href="/" onClick={scrollToSection("integrations")} style={{ height: 36, padding: "0 14px", borderRadius: 999, display: "inline-flex", alignItems: "center", cursor: "pointer" }}>Integrations</a>
            {/* TEMPORARILY HIDDEN — pricing TBD. Restore by uncommenting:
            <a href="/pricing" style={{ height: 36, padding: "0 14px", borderRadius: 999, display: "inline-flex", alignItems: "center" }}>Pricing</a>
            */}
            <a href="/get-started" style={{ height: 36, padding: "0 14px", borderRadius: 999, display: "inline-flex", alignItems: "center" }}>Contact</a>
          </nav>
          <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
            <a href="/login" className="kr-nav-signin" style={{ height: 36, padding: "0 12px", borderRadius: 999, display: "inline-flex", alignItems: "center", fontSize: 13, fontWeight: 700, color: "var(--muted)" }}>Sign in</a>
            <a href="/get-started" className="kr-cta-primary" style={{ height: 36, padding: "0 14px", borderRadius: 999, fontSize: 13, whiteSpace: "nowrap" }}>
              <span className="kr-nav-cta-text">Get Started </span><span className="kr-arrow">→</span>
            </a>
          </div>
        </div>
      </header>
    </div>
  );
}

/* ── FOOTER (slim) ───────────────────────────────────────────────────── */
function Footnote({ tone = "light" }) {
  const color = tone === "light" ? "var(--muted-2)" : "rgba(255,255,255,.5)";
  return (
    <p style={{ fontSize: 11, fontWeight: 600, color, letterSpacing: ".02em" }}>
      © 2026 ElevAIte Labs · All rights reserved
    </p>
  );
}

/* ── Export to window ───────────────────────────────────────────────── */
Object.assign(window, {
  KredooLogo, ParticleField, OrbitVisual, Counter, LiveTicker,
  Check, Arrow, Navbar, Footnote, TICKER_EVENTS,
});
