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

/* ----------------------------------------------------------------------------
   Icon — inline Lucide-style paths (1.75 stroke, round).
   -------------------------------------------------------------------------- */
const ICONS = {
  arrowRight: <path d="M5 12h14M13 6l6 6-6 6" />,
  arrowUpRight: <path d="M7 17 17 7M7 7h10v10" />,
  chevronRight: <path d="m9 18 6-6-6-6" />,
  chevronDown: <path d="m6 9 6 6 6-6" />,
  activity: <path d="M22 12h-4l-3 9L9 3l-3 9H2" />,
  shieldCheck: <><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10" /><path d="m9 12 2 2 4-4" /></>,
  users: <><path d="M16 7a4 4 0 1 0-8 0" /><path d="M17 21v-2a5 5 0 0 0-10 0v2" /><circle cx="9" cy="7" r="4" /><path d="M22 11h-4" /></>,
  trendingUp: <><path d="M16 7h6v6" /><path d="m22 7-8.5 8.5-5-5L2 17" /></>,
  barChart: <><path d="M3 3v18h18" /><rect x="7" y="10" width="3" height="8" /><rect x="12" y="6" width="3" height="12" /><rect x="17" y="13" width="3" height="5" /></>,
  lineChart: <><path d="M3 3v18h18" /><path d="m19 9-5 5-4-4-3 3" /></>,
  mapPin: <><path d="M20 10c0 6-8 12-8 12s-8-6-8-12a8 8 0 0 1 16 0" /><circle cx="12" cy="10" r="3" /></>,
  target: <><circle cx="12" cy="12" r="10" /><circle cx="12" cy="12" r="6" /><circle cx="12" cy="12" r="2" /></>,
  handshake: <><path d="m11 17 2 2a1 1 0 1 0 3-3" /><path d="m14 14 2.5 2.5a1 1 0 1 0 3-3l-3.88-3.88a3 3 0 0 0-4.24 0l-.88.88a1 1 0 1 1-3-3l2.81-2.81a5.79 5.79 0 0 1 7.06-.87l.47.28a2 2 0 0 0 1.42.25L21 4" /><path d="m21 3 1 11h-2" /><path d="M3 3 2 14l6.5 6.5a1 1 0 1 0 3-3" /><path d="M3 4h8" /></>,
  building: <><path d="M6 22V4a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v18Z" /><path d="M6 12H4a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2h2" /><path d="M18 9h2a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-2" /><path d="M10 6h4M10 10h4M10 14h4M10 18h4" /></>,
  landmark: <><line x1="3" y1="22" x2="21" y2="22" /><line x1="6" y1="18" x2="6" y2="11" /><line x1="10" y1="18" x2="10" y2="11" /><line x1="14" y1="18" x2="14" y2="11" /><line x1="18" y1="18" x2="18" y2="11" /><polygon points="12 2 20 7 4 7" /></>,
  phone: <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-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.13.96.36 1.9.7 2.81a2 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-.45c.91.34 1.85.57 2.81.7A2 2 0 0 1 22 16.92" />,
  message: <path d="M7.9 20A9 9 0 1 0 4 16.1L2 22Z" />,
  check: <path d="M20 6 9 17l-5-5" />,
  menu: <><path d="M4 6h16M4 12h16M4 18h16" /></>,
  x: <><path d="M18 6 6 18M6 6l12 12" /></>,
  heartPulse: <><path d="M19 14c1.49-1.46 3-3.21 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.76 0-3 .5-4.5 2-1.5-1.5-2.74-2-4.5-2A5.5 5.5 0 0 0 2 8.5c0 2.3 1.5 4.05 3 5.5l7 7Z" /><path d="M3.22 12H9.5l.5-1 2 4.5 2-7 1.5 3.5h5.27" /></>,
  heart: <path d="M19 14c1.49-1.46 3-3.21 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.76 0-3 .5-4.5 2-1.5-1.5-2.74-2-4.5-2A5.5 5.5 0 0 0 2 8.5c0 2.3 1.5 4.05 3 5.5l7 7Z" />,
  clipboardCheck: <><rect x="8" y="2" width="8" height="4" rx="1" /><path d="M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2" /><path d="m9 14 2 2 4-4" /></>,
  fileText: <><path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z" /><path d="M14 2v5h5" /><path d="M9 13h6M9 17h4" /></>,
  globe: <><circle cx="12" cy="12" r="10" /><path d="M2 12h20" /><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z" /></>,
  award: <><circle cx="12" cy="8" r="6" /><path d="M15.477 12.89 17 22l-5-3-5 3 1.523-9.11" /></>,
  sparkles: <><path d="m12 3-1.9 5.8a2 2 0 0 1-1.3 1.3L3 12l5.8 1.9a2 2 0 0 1 1.3 1.3L12 21l1.9-5.8a2 2 0 0 1 1.3-1.3L21 12l-5.8-1.9a2 2 0 0 1-1.3-1.3Z" /></>,
  layers: <><path d="m12.83 2.18 8.27 4.13a1 1 0 0 1 0 1.79l-8.27 4.13a2 2 0 0 1-1.79 0L2.27 8.1a1 1 0 0 1 0-1.79l8.77-4.13a2 2 0 0 1 1.79 0Z" /><path d="m2 12.5 9.27 4.63a2 2 0 0 0 1.79 0L22 12.5" /><path d="m2 17 9.27 4.63a2 2 0 0 0 1.79 0L22 17" /></>,
  compass: <><circle cx="12" cy="12" r="10" /><path d="m16.24 7.76-2.12 6.36-6.36 2.12 2.12-6.36 6.36-2.12z" /></>,
  lock: <><rect x="3" y="11" width="18" height="11" rx="2" /><path d="M7 11V7a5 5 0 0 1 10 0v4" /></>,
  calendar: <><rect x="3" y="4" width="18" height="18" rx="2" /><path d="M16 2v4M8 2v4M3 10h18" /></>,
  linkedin: <><path d="M16 8a6 6 0 0 1 6 6v7h-4v-7a2 2 0 0 0-4 0v7h-4v-7a6 6 0 0 1 6-6z" /><rect x="2" y="9" width="4" height="12" /><circle cx="4" cy="4" r="2" /></>,
  twitter: <path d="M23 3a10.9 10.9 0 0 1-3.14 1.53 4.48 4.48 0 0 0-7.86 3v1A10.66 10.66 0 0 1 3 4s-4 9 5 13a11.64 11.64 0 0 1-7 2c9 5 20 0 20-11.5a4.5 4.5 0 0 0-.08-.83A7.72 7.72 0 0 0 23 3z" />,
  facebook: <path d="M18 2h-3a5 5 0 0 0-5 5v3H7v4h3v8h4v-8h3l1-4h-4V7a1 1 0 0 1 1-1h3z" />,
  youtube: <><rect x="2" y="6" width="20" height="12" rx="3" /><path d="m10 9 5 3-5 3z" /></>,
  mail: <><rect x="2" y="4" width="20" height="16" rx="2" /><path d="m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7" /></>,
  stethoscope: <><path d="M4.8 2.3A.3.3 0 1 0 5 2H4a2 2 0 0 0-2 2v5a6 6 0 0 0 6 6v0a6 6 0 0 0 6-6V4a2 2 0 0 0-2-2h-1a.2.2 0 1 0 .3.3" /><path d="M8 15v1a6 6 0 0 0 6 6v0a6 6 0 0 0 6-6v-4" /><circle cx="20" cy="10" r="2" /></>,
  database: <><ellipse cx="12" cy="5" rx="9" ry="3" /><path d="M3 5v14a9 3 0 0 0 18 0V5" /><path d="M3 12a9 3 0 0 0 18 0" /></>,
  image: <><rect x="3" y="3" width="18" height="18" rx="2" /><circle cx="9" cy="9" r="2" /><path d="m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21" /></>,
};

function Icon({ name, size = 22, stroke = 1.75, className = "", style = {} }) {
  return (
    <svg xmlns="http://www.w3.org/2000/svg" width={size} height={size} viewBox="0 0 24 24"
      fill="none" stroke="currentColor" strokeWidth={stroke} strokeLinecap="round"
      strokeLinejoin="round" className={className} style={style} aria-hidden="true">
      {ICONS[name] || null}
    </svg>
  );
}

/* ---- Button ------------------------------------------------------------- */
function Button({ children, variant = "primary", size = "md", icon = "arrowRight", showIcon = false, onClick, href, type, className = "" }) {
  const cls = `hb hb-${variant} hb-${size} ${className}`;
  const inner = <>{children}{showIcon && icon && <Icon name={icon} size={size === "lg" ? 18 : 16} stroke={2} className="hb-ic" />}</>;
  if (href) return <a className={cls} href={href} onClick={onClick}>{inner}</a>;
  return <button className={cls} onClick={onClick} type={type || "button"}>{inner}</button>;
}

function Eyebrow({ children, color }) {
  return <span className="eyebrow" style={color ? { color } : null}>{children}</span>;
}

function SectionHead({ eyebrow, title, lead, align = "left", eyebrowColor, max }) {
  return (
    <Reveal className={`sec-head ${align === "center" ? "sec-center" : ""}`} style={max ? { maxWidth: max } : null}>
      <div className="rule-dove" />
      {eyebrow && <Eyebrow color={eyebrowColor}>{eyebrow}</Eyebrow>}
      {title && <h2>{title}</h2>}
      {lead && <p className="lead">{lead}</p>}
    </Reveal>
  );
}

/* ---- Reveal: scroll-in animation (respects reduced motion) -------------- */
function Reveal({ children, className = "", style = {}, as = "div", delay = 0, y = 22 }) {
  const ref = useRef(null);
  const [seen, setSeen] = useState(false);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    if (window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches) { setSeen(true); return; }
    // Already in view on mount? Reveal immediately (covers above-the-fold + no-IO contexts).
    const r = el.getBoundingClientRect();
    if (r.top < window.innerHeight * 0.95 && r.bottom > 0) { setSeen(true); return; }
    let fallback = 0;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => { if (e.isIntersecting) { setSeen(true); io.disconnect(); clearTimeout(fallback); } });
    }, { threshold: 0.12, rootMargin: "0px 0px -8% 0px" });
    io.observe(el);
    // Safety net: content must never stay hidden if IO never fires.
    fallback = setTimeout(() => { setSeen(true); io.disconnect(); }, 1200);
    return () => { io.disconnect(); clearTimeout(fallback); };
  }, []);
  const Tag = as;
  return (
    <Tag ref={ref} className={`reveal ${seen ? "in" : ""} ${className}`}
      style={{ "--rv-y": `${y}px`, transitionDelay: `${delay}ms`, ...style }}>
      {children}
    </Tag>
  );
}

/* ---- Parallax: subtle scroll translate for decorative / media ----------- */
function useParallax(factor = 0.12) {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    if (window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
    let raf = 0;
    const onScroll = () => {
      if (raf) return;
      raf = requestAnimationFrame(() => {
        raf = 0;
        const r = el.getBoundingClientRect();
        const center = r.top + r.height / 2 - window.innerHeight / 2;
        el.style.transform = `translate3d(0, ${(-center * factor).toFixed(1)}px, 0)`;
      });
    };
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, [factor]);
  return ref;
}

/* ---- Img: real photo in a rounded frame with rollover zoom -------------- */
function Img({ src, alt = "", ratio, className = "", parallax = 0, imgClass = "", style = {}, eager = false }) {
  const pref = useParallax(parallax);
  return (
    <div className={`imgframe ${className}`} style={{ ...(ratio ? { aspectRatio: ratio } : {}), ...style }}>
      <img ref={parallax ? pref : null} src={src} alt={alt}
        className={`imgframe-img ${imgClass} ${parallax ? "is-parallax" : ""}`} loading={eager ? "eager" : "lazy"} />
    </div>
  );
}

/* Photo placeholder kept for back-compat */
function Photo({ label, ratio = "4 / 3", className = "", style = {} }) {
  return (
    <div className={`photo ${className}`} style={{ aspectRatio: ratio, ...style }}>
      <Icon name="users" size={26} /><span>{label}</span>
    </div>
  );
}

/* ---- CountUp: animate a number to its target when scrolled into view ----- */
function CountUp({ to, prefix = "", suffix = "", decimals = 0, format = false, dur = 1500 }) {
  const ref = useRef(null);
  const [val, setVal] = useState(0);
  const started = useRef(false);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const run = () => {
      if (started.current) return;
      started.current = true;
      const start = performance.now();
      const tick = (now) => {
        const p = Math.min(1, (now - start) / dur);
        const eased = 1 - Math.pow(1 - p, 3);
        setVal(to * eased);
        if (p < 1) requestAnimationFrame(tick); else setVal(to);
      };
      requestAnimationFrame(tick);
    };
    if (window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches) { setVal(to); return; }
    const r = el.getBoundingClientRect();
    if (r.top < window.innerHeight * 0.92 && r.bottom > 0) { run(); return; }
    const io = new IntersectionObserver((es) => es.forEach((e) => { if (e.isIntersecting) { run(); io.disconnect(); } }), { threshold: 0.3 });
    io.observe(el);
    const fb = setTimeout(run, 1600);
    return () => { io.disconnect(); clearTimeout(fb); };
  }, [to]);
  const num = format ? Math.round(val).toLocaleString() : (decimals ? val.toFixed(decimals) : Math.round(val).toString());
  return <span ref={ref}>{prefix}{num}{suffix}</span>;
}

/* ---- ImpactBand: capabilities section, reused on every page ------------- */
const IMPACT_CAPS = [
  { ic: "users", t: "Population health management" },
  { ic: "award", t: "HEDIS and Star Ratings support" },
  { ic: "trendingUp", t: "Quality improvement" },
  { ic: "target", t: "Care gap closure" },
  { ic: "heart", t: "Member engagement and retention" },
  { ic: "barChart", t: "Risk adjustment support" },
  { ic: "compass", t: "Health equity strategy" },
  { ic: "lineChart", t: "Value-based care performance" },
  { ic: "mapPin", t: "Community-based outreach" },
  { ic: "database", t: "Data-informed reporting and measurement" },
];

function ImpactBand({ video = "assets/video/middle-2.mp4" }) {
  return (
    <section className="band" id="impact">
      <video className="band-video" autoPlay muted loop playsInline>
        <source src={video} type="video/mp4" />
      </video>
      <div className="wrap">
        <div className="band-cap">
          <Reveal className="band-intro">
            <div className="rule-dove" style={{ marginBottom: 16 }} />
            <span className="eyebrow">What we do</span>
            <h2>Intelligence-driven. Human-centered. Built to close gaps.</h2>
            <p>HCDI helps clients identify priority populations, understand barriers to care,
              and activate outreach strategies that move people toward better health.</p>
          </Reveal>
          <div className="band-caps">
            <span className="is-label">Our work supports</span>
            <div className="caps-grid">
              {IMPACT_CAPS.map((c, i) => (
                <Reveal className="cap-chip" key={c.t} delay={i * 45}>
                  <span className="cc-ic"><Icon name={c.ic} size={20} /></span>
                  <span className="cc-t">{c.t}</span>
                </Reveal>
              ))}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Icon, Button, Eyebrow, SectionHead, Reveal, useParallax, Img, Photo, CountUp, ImpactBand, useState, useEffect, useRef });
