// primitives.jsx — shared UI bits used across sections (Arabic / RTL).

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

// IntersectionObserver-driven reveal
function Reveal({ children, delay = 0, as: Tag = "div", className = "", style }) {
  const ref = useRef(null);
  const [shown, setShown] = useState(false);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting) {
          setTimeout(() => setShown(true), delay);
          io.unobserve(el);
        }
      });
    }, { threshold: 0.12 });
    io.observe(el);
    return () => io.disconnect();
  }, [delay]);
  return (
    <Tag ref={ref} className={`reveal ${shown ? "in" : ""} ${className}`} style={style}>
      {children}
    </Tag>
  );
}

function Nav() {
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 24);
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  useEffect(() => {
    document.body.style.overflow = open ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [open]);

  const items = [
    { label: "النظام", href: "#system" },
    { label: "كيف نعمل", href: "#process" },
    { label: "الأسعار", href: "#pricing" },
    { label: "النتائج", href: "#proof" },
    { label: "أسئلة شائعة", href: "#faq" },
  ];
  return (
    <header style={{
      position: "fixed", top: 0, left: 0, right: 0, zIndex: 100,
      backdropFilter: scrolled ? "blur(14px) saturate(140%)" : "none",
      WebkitBackdropFilter: scrolled ? "blur(14px) saturate(140%)" : "none",
      background: scrolled ? "rgba(11,20,32,0.78)" : "transparent",
      borderBottom: scrolled ? "1px solid var(--hairline)" : "1px solid transparent",
      transition: "all 0.25s ease",
    }}>
      <div className="container" style={{
        height: 72, display: "flex", alignItems: "center", justifyContent: "space-between",
      }}>
        <a href="#top" style={{ display: "flex", alignItems: "center", gap: 12, direction: "ltr" }}>
          <BranchMark />
          <div style={{ display: "flex", flexDirection: "column", lineHeight: 1 }}>
            <span style={{ fontFamily: "var(--f-en)", fontWeight: 600, fontSize: 16, letterSpacing: "-0.01em" }}>
              Clinic Growth Ops
            </span>
            <span className="mono" style={{ fontSize: 9.5, letterSpacing: "0.18em", color: "var(--text-dim)", textTransform: "uppercase", marginTop: 3 }}>
              Predictable Growth Systems
            </span>
          </div>
        </a>

        {/* Desktop nav */}
        <nav className="nav-desktop" style={{ display: "flex", gap: 32, alignItems: "center" }}>
          {items.map((it) => (
            <a key={it.label} href={it.href}
               style={{ fontSize: 14, color: "var(--text-mute)" }}
               onMouseEnter={(e) => e.currentTarget.style.color = "var(--text)"}
               onMouseLeave={(e) => e.currentTarget.style.color = "var(--text-mute)"}>
              {it.label}
            </a>
          ))}
          <a href="#contact" className="btn btn-primary" style={{ height: 40, padding: "0 18px", fontSize: 13 }}>
            احجز مكالمة تشخيص
            <Arrow flip />
          </a>
        </nav>

        {/* Mobile toggle */}
        <button className="nav-mobile-toggle"
          aria-label="القائمة"
          onClick={() => setOpen(!open)}
          style={{
            display: "none", background: "transparent", border: "1px solid var(--hairline-strong)",
            width: 44, height: 44, borderRadius: 4, alignItems: "center", justifyContent: "center",
          }}>
          <svg width="18" height="18" viewBox="0 0 18 18" fill="none" aria-hidden="true">
            {open ? (
              <>
                <path d="M3 3 L15 15" stroke="currentColor" strokeWidth="1.4" />
                <path d="M15 3 L3 15" stroke="currentColor" strokeWidth="1.4" />
              </>
            ) : (
              <>
                <path d="M2 5 H16" stroke="currentColor" strokeWidth="1.4" />
                <path d="M2 9 H16" stroke="currentColor" strokeWidth="1.4" />
                <path d="M2 13 H16" stroke="currentColor" strokeWidth="1.4" />
              </>
            )}
          </svg>
        </button>
      </div>

      {/* Mobile menu sheet */}
      {open && (
        <div className="nav-mobile-sheet" style={{
          position: "fixed", top: 72, left: 0, right: 0, bottom: 0,
          background: "rgba(11,20,32,0.98)", backdropFilter: "blur(14px)",
          padding: 28, display: "flex", flexDirection: "column", gap: 4, zIndex: 99,
        }}>
          {items.map((it) => (
            <a key={it.label} href={it.href}
               onClick={() => setOpen(false)}
               style={{
                 fontSize: 22, fontFamily: "var(--f-display)", fontWeight: 500,
                 padding: "18px 0", borderBottom: "1px solid var(--hairline)",
                 color: "var(--text)",
               }}>
              {it.label}
            </a>
          ))}
          <a href="#contact" className="btn btn-primary"
             onClick={() => setOpen(false)}
             style={{ marginTop: 24 }}>
            احجز مكالمة تشخيص <Arrow flip />
          </a>
        </div>
      )}

      <style>{`
        @media (max-width: 880px) {
          .nav-desktop { display: none !important; }
          .nav-mobile-toggle { display: flex !important; }
        }
      `}</style>
    </header>
  );
}

function BranchMark() {
  return (
    <svg width="28" height="28" viewBox="0 0 28 28" fill="none" aria-hidden="true">
      <circle cx="14" cy="14" r="13.5" stroke="var(--accent)" strokeOpacity="0.5" />
      <path d="M7 21 L14 14 L21 7" stroke="var(--accent)" strokeWidth="1.5" />
      <path d="M14 14 L20 18" stroke="var(--accent)" strokeWidth="1.5" strokeOpacity="0.7" />
      <path d="M14 14 L9 11" stroke="var(--accent)" strokeWidth="1.5" strokeOpacity="0.7" />
      <circle cx="14" cy="14" r="2" fill="var(--accent)" />
    </svg>
  );
}

// Arrow — flipped for RTL by default (points to the start of the line, like ←).
function Arrow({ size = 14, flip = true }) {
  return (
    <svg width={size} height={size} viewBox="0 0 14 14" fill="none" aria-hidden="true"
         style={{ transform: flip ? "scaleX(-1)" : "none" }}>
      <path d="M2 7h10M8 3l4 4-4 4" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

function SectionId({ n, label }) {
  return <div className="sid">{n} &nbsp;·&nbsp; {label}</div>;
}

function Sparkline({ seed = 1, w = 120, h = 32, up = true, color }) {
  const pts = useMemo(() => {
    const rng = (s) => { let x = s; return () => (x = (x * 9301 + 49297) % 233280) / 233280; };
    const r = rng(seed);
    const n = 24;
    const arr = [];
    let v = 0.5;
    for (let i = 0; i < n; i++) {
      v += (r() - 0.5) * 0.18 + (up ? 0.012 : -0.012);
      v = Math.max(0.05, Math.min(0.95, v));
      arr.push(v);
    }
    return arr;
  }, [seed, up]);
  const c = color || "var(--accent)";
  const path = pts.map((v, i) => {
    const x = (i / (pts.length - 1)) * w;
    const y = h - v * h;
    return `${i === 0 ? "M" : "L"} ${x.toFixed(1)} ${y.toFixed(1)}`;
  }).join(" ");
  const fill = `${path} L ${w} ${h} L 0 ${h} Z`;
  return (
    <svg className="spark" width={w} height={h} viewBox={`0 0 ${w} ${h}`}>
      <path d={fill} fill={c} fillOpacity="0.10" />
      <path d={path} fill="none" stroke={c} strokeWidth="1.4" />
    </svg>
  );
}

function CountUp({ to, suffix = "", duration = 1400, decimals = 0 }) {
  const ref = useRef(null);
  const [val, setVal] = useState(0);
  useEffect(() => {
    const el = ref.current; if (!el) return;
    let started = false;
    const io = new IntersectionObserver((es) => {
      es.forEach((e) => {
        if (e.isIntersecting && !started) {
          started = true;
          const t0 = performance.now();
          const tick = (t) => {
            const p = Math.min(1, (t - t0) / duration);
            const eased = 1 - Math.pow(1 - p, 3);
            setVal(to * eased);
            if (p < 1) requestAnimationFrame(tick);
          };
          requestAnimationFrame(tick);
        }
      });
    }, { threshold: 0.4 });
    io.observe(el);
    return () => io.disconnect();
  }, [to, duration]);
  return (
    <span ref={ref} className="tabnum" style={{ direction: "ltr", display: "inline-block" }}>
      {decimals === 0 ? Math.round(val).toLocaleString("en-US") : val.toFixed(decimals)}{suffix}
    </span>
  );
}

Object.assign(window, {
  Reveal, Nav, BranchMark, Arrow, SectionId, Sparkline, CountUp,
});
