// Shared UI primitives + helpers for America First Defense.AI prototype

// Reveal-on-scroll wrapper using IntersectionObserver
function Reveal({ children, delay = 0, as: Tag = "div", className = "" }) {
  const ref = React.useRef(null);
  const [shown, setShown] = React.useState(false);
  React.useEffect(() => {
    const el = ref.current;
    if (!el) return;
    // If element is already in (or above) viewport on mount, show immediately.
    const rect = el.getBoundingClientRect();
    if (rect.top < window.innerHeight + 100) {
      setTimeout(() => setShown(true), delay);
      return;
    }
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) {
            setTimeout(() => setShown(true), delay);
            io.unobserve(el);
          }
        });
      },
      { threshold: 0.05, rootMargin: "0px 0px 10% 0px" }
    );
    io.observe(el);
    // Failsafe: ensure content is shown after 1s even if observer never fires
    const failsafe = setTimeout(() => setShown(true), 1000 + delay);
    return () => {io.disconnect();clearTimeout(failsafe);};
  }, [delay]);
  return (
    <Tag ref={ref} className={`reveal ${shown ? "in" : ""} ${className}`}>
      {children}
    </Tag>);

}

// Word-by-word kinetic reveal for headlines.
// Wrap a string in <Kinetic>…</Kinetic>; each word slides up + fades in,
// staggered. Plays in concert with the parent .reveal.in class so it only
// fires when scrolled into view. JSX children are rendered as a single word.
function Kinetic({ children, baseDelay = 60, lineDelay = 0, as: Tag = "span" }) {
  // Flatten children into an ordered list of "tokens": strings split into words,
  // and elements treated as a single word. We preserve whitespace.
  const tokens = [];
  const push = (t) => tokens.push(t);
  React.Children.forEach(children, (c, i) => {
    if (typeof c === "string") {
      const parts = c.split(/(\s+)/);
      parts.forEach((p) => {
        if (p === "") return;
        if (/^\s+$/.test(p)) push({ type: "ws", v: p });else
        push({ type: "word", v: p });
      });
    } else if (React.isValidElement(c)) {
      push({ type: "node", v: c, key: i });
    }
  });
  let wIndex = 0;
  return (
    <Tag className="kinetic-line">
      {tokens.map((t, i) => {
        if (t.type === "ws") return <React.Fragment key={i}>{t.v}</React.Fragment>;
        const delay = lineDelay + wIndex++ * baseDelay;
        return (
          <span
            key={i}
            className="kinetic-word"
            style={{ transitionDelay: `${delay}ms` }}>
            {t.type === "node" ? t.v : t.v}
          </span>);
      })}
    </Tag>);
}

// CountUp — animates a numeric value from 0 to target when revealed into view.
// Accepts a number or a string like "1.8" / ">1.8" — animates the numeric
// portion and preserves prefix/suffix text. Triggers via IntersectionObserver.
function CountUp({ value, duration = 1400, prefix = "", suffix = "", decimals = null }) {
  const ref = React.useRef(null);
  const [n, setN] = React.useState(0);
  // Parse leading non-digit prefix and trailing suffix, plus the numeric core.
  const str = String(value);
  const m = str.match(/^(\D*)([\d.]+)(.*)$/);
  const parsedPrefix = (m ? m[1] : "") + prefix;
  const target = m ? parseFloat(m[2]) : 0;
  const parsedSuffix = (m ? m[3] : "") + suffix;
  const dec = decimals !== null ? decimals : m && m[2].includes(".") ? m[2].split(".")[1].length : 0;

  React.useEffect(() => {
    const el = ref.current;
    if (!el) return;
    let started = false;
    let raf;
    const start = () => {
      if (started) return;
      started = true;
      const t0 = performance.now();
      const tick = (now) => {
        const p = Math.min(1, (now - t0) / duration);
        const eased = 1 - Math.pow(1 - p, 3);
        setN(target * eased);
        if (p < 1) raf = requestAnimationFrame(tick);
      };
      raf = requestAnimationFrame(tick);
    };
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {if (e.isIntersecting) {start();io.unobserve(el);}});
    }, { threshold: 0.4 });
    io.observe(el);
    return () => {io.disconnect();if (raf) cancelAnimationFrame(raf);};
  }, [target, duration]);

  return <span ref={ref}>{parsedPrefix}{n.toFixed(dec)}{parsedSuffix}</span>;
}

// Hook: track cursor over an element and write CSS vars --mx / --my.
// Used by platform cards to drive a follow-the-mouse radial highlight.
function useCursorGlow() {
  const ref = React.useRef(null);
  React.useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const onMove = (e) => {
      const r = el.getBoundingClientRect();
      el.style.setProperty("--mx", `${(e.clientX - r.left) / r.width * 100}%`);
      el.style.setProperty("--my", `${(e.clientY - r.top) / r.height * 100}%`);
    };
    el.addEventListener("pointermove", onMove);
    return () => el.removeEventListener("pointermove", onMove);
  }, []);
  return ref;
}

// Section header — eyebrow + title pattern
function SHead({ id, eyebrow, children, className = "" }) {
  const hasLeft = id || eyebrow;
  return (
    <Reveal className={`s-head ${className} ${hasLeft ? "" : "no-left"}`}>
      {hasLeft ?
      <div className="left">
          {id ? <div className="id">{id}</div> : null}
          {eyebrow ? <div className="h-eyebrow">{eyebrow}</div> : null}
        </div> :
      null}
      <h2>{children}</h2>
    </Reveal>);

}

// Inline arrow component
function Arr({ size = 14, color = "currentColor" }) {
  return (
    <svg width={size} height={size} viewBox="0 0 14 14" fill="none">
      <path d="M1 7 H13 M8 2 L13 7 L8 12" stroke={color} strokeWidth="1" />
    </svg>);

}

// Crosshair / target SVG
function CrosshairIcon({ size = 22, color = "currentColor" }) {
  return (
    <svg width={size} height={size} viewBox="0 0 22 22" fill="none" stroke={color} strokeWidth="1">
      <circle cx="11" cy="11" r="7" />
      <circle cx="11" cy="11" r="2.5" />
      <line x1="11" y1="0" x2="11" y2="5" />
      <line x1="11" y1="17" x2="11" y2="22" />
      <line x1="0" y1="11" x2="5" y2="11" />
      <line x1="17" y1="11" x2="22" y2="11" />
    </svg>);

}

// Wave / soft robotics SVG
function WaveIcon({ size = 22, color = "currentColor" }) {
  return (
    <svg width={size} height={size} viewBox="0 0 22 22" fill="none" stroke={color} strokeWidth="1">
      <path d="M1 7 Q5.5 2, 11 7 T21 7" />
      <path d="M1 12 Q5.5 7, 11 12 T21 12" />
      <path d="M1 17 Q5.5 12, 11 17 T21 17" />
    </svg>);

}

// Shield mark
function ShieldIcon({ size = 22, color = "currentColor" }) {
  return (
    <svg width={size} height={size} viewBox="0 0 22 22" fill="none" stroke={color} strokeWidth="1">
      <path d="M11 1 L19 4 V10 C19 15, 15 19, 11 21 C7 19, 3 15, 3 10 V4 Z" />
      <path d="M11 7 V14" />
      <path d="M7 10 H15" />
    </svg>);

}

// Star
function Star({ size = 14, color = "currentColor", filled = true }) {
  return (
    <svg width={size} height={size} viewBox="0 0 14 14" fill={filled ? color : "none"} stroke={color} strokeWidth="1">
      <path d="M7 1 L8.8 5.4 L13.5 5.7 L9.9 8.6 L11.1 13 L7 10.5 L2.9 13 L4.1 8.6 L0.5 5.7 L5.2 5.4 Z" />
    </svg>);

}

// Brand mark — shield + flag stripes (original abstract)
function BrandSeal({ size = 60 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 60 60" fill="none" aria-hidden>
      {/* Outer shield */}
      <path d="M30 3 L52 10 V28 C52 41, 42 51, 30 56 C18 51, 8 41, 8 28 V10 Z"
      stroke="currentColor" strokeWidth="1" fill="none" />
      {/* Inner stripes */}
      <g>
        <rect x="14" y="22" width="32" height="2.5" fill="currentColor" opacity="0.85" />
        <rect x="14" y="27" width="32" height="2.5" fill="#b33a3a" />
        <rect x="14" y="32" width="32" height="2.5" fill="currentColor" opacity="0.6" />
        <rect x="14" y="37" width="32" height="2.5" fill="#b33a3a" />
        <rect x="14" y="42" width="32" height="2.5" fill="currentColor" opacity="0.4" />
      </g>
      {/* Stars row */}
      <g fill="currentColor">
        <circle cx="20" cy="16" r="1.4" />
        <circle cx="26" cy="16" r="1.4" />
        <circle cx="32" cy="16" r="1.4" />
        <circle cx="38" cy="16" r="1.4" />
        <circle cx="44" cy="16" r="1.4" />
      </g>
    </svg>);

}

// Topographic / contour decoration as SVG overlay
function ContourBg({ opacity = 0.08, color = "#ede7da" }) {
  return (
    <svg
      style={{ position: "absolute", inset: 0, width: "100%", height: "100%", pointerEvents: "none", opacity }}
      viewBox="0 0 1200 600" preserveAspectRatio="none">
      
      <defs>
        <pattern id="contour-pat" width="1200" height="600" patternUnits="userSpaceOnUse">
          {[...Array(20)].map((_, i) => {
            const r = 40 + i * 30;
            return (
              <ellipse key={i} cx="600" cy="300" rx={r} ry={r * 0.55}
              fill="none" stroke={color} strokeWidth="0.4" />);

          })}
        </pattern>
      </defs>
      <rect width="1200" height="600" fill="url(#contour-pat)" />
    </svg>);

}

// Document bar — small column header
function DocBar({ left, center, right }) {
  return (
    <div className="doc-bar">
      <div className="index">{left}</div>
      <div className="title" style={{ fontSize: "48px", fontFamily: "\"Inter Tight\"", letterSpacing: "-1.21818px", lineHeight: "0.98", width: "636.449px", height: "47.7486px", fontWeight: "500" }}>{center}</div>
      <div className="meta">{right}</div>
    </div>);

}

// CTA block reused at bottom of pages
function CtaBlock({ tweaks }) {
  return (
    <section className="cta-block">
      <div className="topo-bg" />
      <div className="container" style={{ textAlign: "center" }}>
        <div className="cta-inner" style={{ marginTop: 40, display: "flex", flexDirection: "column", alignItems: "center" }}>
          <Reveal>
            <h2 style={{ color: "rgb(255, 255, 255)" }}>
              Ready to defend America <span className="em" style={{ color: "rgb(241, 241, 241)" }}>together</span>.
            </h2>
            <p style={{
              fontFamily: "var(--font-display)", fontWeight: 300,
              fontSize: 18, lineHeight: 1.5,
              maxWidth: 540, marginTop: 20, marginLeft: "auto", marginRight: "auto", textAlign: "center", color: "rgb(255, 255, 255)"
            }}>
              Partner with America First Defense.AI. Contact us to learn more.
            </p>
          </Reveal>
          <Reveal delay={120}>
            <div className="cta-actions" style={{ marginTop: 12, justifyContent: "center" }}>
              <a href="#/contact" className={tweaks?.accent === "crimson" ? "btn btn-crimson" : "btn"}>
                Contact <Arr />
              </a>
              <a href="#/mission" className="btn btn-ghost">
                Read Mission <Arr />
              </a>
            </div>
          </Reveal>
        </div>
      </div>
    </section>);

}

// Footer
function Footer() {
  return (
    <footer className="footer footer-bone">
      <div className="container">
        <div className="footer-top">
          <div className="footer-brand">
            <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
              <img src={window.__resources && window.__resources.logoImg || "assets/logo.png"} alt="America First Defense.AI" style={{ height: 44, width: "auto", display: "block" }} />
              <div>
                <div className="nm">America First Defense.AI</div>
                <div className="tag" style={{ marginTop: 4 }}>EST. 2026 · NEW JERSEY</div>
              </div>
            </div>
            <div className="tag" style={{ maxWidth: 360, marginTop: 8 }}>
              American-owned defense systems engineered for the conflicts of the next decade.
              Protocol-precise, deployable at scale.
            </div>
          </div>
          <div className="footer-col">
            <h5>Platforms</h5>
            <a href="#/counter-drone">Detachable Drone Hijacker</a>
            <a href="#/soft-robotics">Soft Robotics Platform</a>
          </div>
          <div className="footer-col">
            <h5>Company</h5>
            <a href="#/mission">Mission</a>
            <a href="#/partners">Partners</a>
            <a href="#/contact">Contact</a>
          </div>
          <div className="footer-flag" aria-hidden="true" style={{ display: "flex", alignItems: "flex-start", justifyContent: "flex-end" }}>
            <svg width="156" height="99" viewBox="0 0 120 76" fill="none" style={{ display: "block" }}>
              <rect x="0.5" y="0.5" width="119" height="75" fill="var(--bone)" stroke="rgba(10,14,20,0.18)" strokeWidth="1" />
              {[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12].map((i) =>
              <rect key={i} x="0" y={i * (76 / 13)} width="120" height={76 / 13} fill={i % 2 === 0 ? "#b22234" : "transparent"} />
              )}
              <rect x="0" y="0" width="48" height={76 * 7 / 13} fill="#1b2c4a" />
              {(() => {
                const cantonW = 48;
                const cantonH = 76 * 7 / 13;
                const xStep = cantonW / 12;
                const yStep = cantonH / 10;
                const r = 1.2;
                const starPath = (cx, cy) => {
                  const pts = [];
                  for (let k = 0; k < 10; k++) {
                    const ang = -Math.PI / 2 + k * Math.PI / 5;
                    const rad = k % 2 === 0 ? r : r * 0.4;
                    pts.push(`${(cx + Math.cos(ang) * rad).toFixed(2)},${(cy + Math.sin(ang) * rad).toFixed(2)}`);
                  }
                  return `M${pts.join(" L")}Z`;
                };
                const stars = [];
                // 9 rows: rows 0,2,4,6,8 have 6 stars (at x=1,3,5,7,9,11); rows 1,3,5,7 have 5 stars (at x=2,4,6,8,10)
                for (let row = 0; row < 9; row++) {
                  const isLong = row % 2 === 0;
                  const cols = isLong ? [1, 3, 5, 7, 9, 11] : [2, 4, 6, 8, 10];
                  const cy = (row + 1) * yStep;
                  cols.forEach((c) => {
                    stars.push(<path key={`${row}-${c}`} d={starPath(c * xStep, cy)} fill="#fff" />);
                  });
                }
                return stars;
              })()}
            </svg>
          </div>
        </div>
        <div className="footer-bottom">
          <div>© {new Date().getFullYear()} America First Defense.AI · All Rights Reserved</div>
          <div></div>
          <div>BUILT IN THE UNITED STATES OF AMERICA</div>
        </div>
      </div>
    </footer>);

}

Object.assign(window, {
  Reveal, SHead, Arr, CrosshairIcon, WaveIcon, ShieldIcon, Star,
  BrandSeal, ContourBg, DocBar, CtaBlock, Footer,
  Kinetic, CountUp, useCursorGlow
});