/* =========================================================
   AI Employees Overview — shared parts
   Hardened count-up + reveal hooks, buttons, nav, agent page map.
   Depends on globals from sg-parts.jsx (AGENTS, AGENT_BY, AgentAvatar).
   ========================================================= */
const { useState, useEffect, useRef } = React;

const DEMO_URL = "https://calendly.com/charles-cardealer/30min";

const prefersReducedMotion =
  typeof window !== "undefined" &&
  window.matchMedia &&
  window.matchMedia("(prefers-reduced-motion: reduce)").matches;

/* Map each agent id -> its product page + a one-line outcome for the roster. */
const AGENT_PAGES = {
  summer: { href: "Summer AI Sales Agent v2.html",        outcome: "Reactivates dormant sales leads and books appointments." },
  lily:   { href: "Lily AI Service-to-Sales Agent.html",   outcome: "Turns service visits into net-new sales appointments." },
  april:  { href: "April AI Service Agent.html",           outcome: "Brings lapsed service customers back into the bay." },
  taylor: { href: "Taylor AI Inbound Service Agent.html",  outcome: "Answers every inbound service call, 24/7." },
  riley:  { href: "Riley AI Recall Agent.html",            outcome: "Turns open recalls into booked service visits." },
  avery:  { href: "Avery AI Receptionist.html",            outcome: "Greets and routes every caller to the right person." },
};

/* ---------- Hooks ---------- */
function useCountUp(target, { duration = 1500, start = 0 } = {}) {
  const [val, setVal] = useState(prefersReducedMotion ? target : start);
  const ref = useRef(null);
  const done = useRef(false);
  useEffect(() => {
    if (prefersReducedMotion) { setVal(target); return; }
    const el = ref.current;
    if (!el) return;

    const run = () => {
      if (done.current) return;
      done.current = true;
      const t0 = performance.now();
      const tick = (now) => {
        const p = Math.min(1, (now - t0) / duration);
        const eased = 1 - Math.pow(1 - p, 3);
        setVal(start + (target - start) * eased);
        if (p < 1) requestAnimationFrame(tick);
        else setVal(target);
      };
      requestAnimationFrame(tick);
    };

    const r = el.getBoundingClientRect();
    if (r.top < window.innerHeight && r.bottom > 0) run();

    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => { if (e.isIntersecting) { run(); io.disconnect(); } });
    }, { threshold: 0.4 });
    io.observe(el);

    const t = setTimeout(() => { if (!done.current) { done.current = true; setVal(target); } }, 1200);
    return () => { io.disconnect(); clearTimeout(t); };
  }, [target]);
  return [val, ref];
}

function useReveal() {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    if (!el || prefersReducedMotion) return;

    let revealed = false;
    const show = () => {
      if (revealed) return;
      revealed = true;
      el.style.transition = "opacity 600ms cubic-bezier(0.2,0,0,1), transform 600ms cubic-bezier(0.2,0,0,1)";
      el.style.opacity = "1";
      el.style.transform = "translateY(0)";
    };

    el.style.opacity = "0";
    el.style.transform = "translateY(16px)";

    const r = el.getBoundingClientRect();
    if (r.top < window.innerHeight && r.bottom > 0) {
      requestAnimationFrame(() => requestAnimationFrame(show));
    }

    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => { if (e.isIntersecting) { show(); io.disconnect(); } });
    }, { threshold: 0.15 });
    io.observe(el);

    const t = setTimeout(show, 1200);
    return () => { io.disconnect(); clearTimeout(t); };
  }, []);
  return ref;
}

/* ---------- Buttons ---------- */
function OvBtn({ children, variant = "primary", href, onClick, icon, pulse }) {
  const base = {
    display: "inline-flex", alignItems: "center", gap: 10,
    padding: "16px 26px", borderRadius: 14, cursor: "pointer",
    fontFamily: "var(--font-body)", fontSize: 16, fontWeight: 700, letterSpacing: "-0.01em",
    border: "1.5px solid transparent", whiteSpace: "nowrap", position: "relative",
    transition: "transform 140ms ease, background 140ms ease, border-color 140ms ease",
  };
  const variants = {
    primary:   { background: "var(--cobalt-500)", color: "#fff" },
    secondary: { background: "transparent", color: "var(--ink)", borderColor: "var(--line)" },
    dark:      { background: "#fff", color: "var(--ink)" },
    "dark-ghost": { background: "rgba(255,255,255,0.06)", color: "#fff", borderColor: "rgba(255,255,255,0.22)" },
  };
  const [hover, setHover] = useState(false);
  const hoverBg = {
    primary: "var(--cobalt-600)", secondary: "var(--bg-alt)",
    dark: "#EEF0F3", "dark-ghost": "rgba(255,255,255,0.12)",
  };
  const style = {
    ...base, ...variants[variant],
    ...(hover ? { transform: "translateY(-1px)", background: hoverBg[variant] } : {}),
  };
  const inner = (
    <React.Fragment>
      {pulse && !prefersReducedMotion ? (
        <span aria-hidden style={{
          position: "absolute", inset: -2, borderRadius: 16,
          border: "2px solid var(--cobalt-400)", opacity: 0.55,
          animation: "ovPulse 2.2s ease-out infinite", pointerEvents: "none",
        }}></span>
      ) : null}
      {icon === "play" ? (
        <svg width="16" height="16" viewBox="0 0 14 14" fill="currentColor"><path d="M3 1.5v11l9-5.5z"/></svg>
      ) : null}
      {icon === "arrow" ? (
        <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h14M13 6l6 6-6 6"/></svg>
      ) : null}
      {children}
    </React.Fragment>
  );
  const handlers = { onMouseEnter: () => setHover(true), onMouseLeave: () => setHover(false) };
  if (href) return <a href={href} target={href.startsWith("http") ? "_blank" : undefined} rel="noopener" style={style} {...handlers}>{inner}</a>;
  return <button onClick={onClick} style={style} {...handlers}>{inner}</button>;
}

/* ---------- Roster agent card ---------- */
function RosterCard({ id }) {
  const a = AGENT_BY[id];
  const page = AGENT_PAGES[id];
  const [hover, setHover] = useState(false);
  return (
    <a href={page.href}
      onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      style={{
        display: "flex", flexDirection: "column",
        background: "var(--bg)", border: "1px solid var(--line)", borderRadius: 20,
        overflow: "hidden", boxShadow: hover ? "var(--e-3)" : "var(--e-1)",
        transform: hover ? "translateY(-4px)" : "translateY(0)",
        transition: "transform 240ms ease, box-shadow 240ms ease",
      }}>
      <div style={{ position: "relative", aspectRatio: "1 / 1", overflow: "hidden", background: "var(--bg-alt)" }}>
        <video src={a.video} poster={a.src} autoPlay loop muted playsInline
          style={{ width: "100%", height: "100%", objectFit: "cover", display: "block" }} />
        <div style={{
          position: "absolute", left: 14, right: 14, bottom: 14,
          background: "rgba(11,18,22,0.78)", color: "#fff", borderRadius: 12, padding: "9px 13px",
          backdropFilter: "blur(8px)", WebkitBackdropFilter: "blur(8px)",
        }}>
          <div style={{ fontSize: 19, fontWeight: 800, letterSpacing: "-0.02em", lineHeight: 1 }}>{a.name}</div>
          <div style={{ fontSize: 12, color: "rgba(255,255,255,0.74)", marginTop: 3 }}>{a.role}</div>
        </div>
      </div>
      <div style={{ padding: "18px 20px 20px", display: "flex", flexDirection: "column", gap: 14, flex: 1 }}>
        <div style={{ fontSize: 15.5, lineHeight: 1.5, color: "var(--ink-soft)", fontWeight: 500, flex: 1 }}>{page.outcome}</div>
        <div style={{
          display: "inline-flex", alignItems: "center", gap: 7,
          fontSize: 14, fontWeight: 700, color: "var(--cobalt-600)",
        }}>
          Learn more
          <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round" style={{ transform: hover ? "translateX(3px)" : "none", transition: "transform 200ms ease" }}><path d="M5 12h14M13 6l6 6-6 6"/></svg>
        </div>
      </div>
    </a>
  );
}

/* ---------- Minimal top nav ---------- */
function OvNav() {
  return (
    <header style={{
      position: "sticky", top: 0, zIndex: 50,
      background: "rgba(255,255,255,0.82)", backdropFilter: "saturate(180%) blur(12px)",
      WebkitBackdropFilter: "saturate(180%) blur(12px)", borderBottom: "1px solid var(--line)",
    }}>
      <div className="page" style={{ display: "flex", alignItems: "center", height: 68, gap: 20 }}>
        <a href="Home.html" style={{ display: "flex", alignItems: "center" }}>
          <img src="logo-exports/horizontal/horizontal-full-color.png" alt="CarDealer.ai" style={{ height: 26 }} />
        </a>
        <div style={{ flex: 1 }}></div>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <span style={{ display: "inline-flex", alignItems: "center", gap: 8, fontSize: 13, fontWeight: 600, color: "var(--body)" }}>
            <span style={{ width: 7, height: 7, borderRadius: 999, background: "var(--positive)", animation: prefersReducedMotion ? "none" : "ovDot 2s ease-in-out infinite" }}></span>
            6 AI employees
          </span>
          <OvBtn variant="primary" href={DEMO_URL}>Book a Demo</OvBtn>
        </div>
      </div>
    </header>
  );
}

Object.assign(window, {
  DEMO_URL, prefersReducedMotion, AGENT_PAGES,
  useCountUp, useReveal, OvBtn, RosterCard, OvNav,
});
