/* ============== Reveal on scroll ============== */
function Reveal({ children, delay = 0, as: As = "div", className = "", style = {} }) {
  const ref = React.useRef(null);
  // Default to visible to avoid blank flashes; only animate-in items below the fold.
  const [visible, setVisible] = React.useState(true);
  const [armed, setArmed] = React.useState(false);
  React.useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const rect = el.getBoundingClientRect();
    const vh = window.innerHeight || document.documentElement.clientHeight;
    if (rect.top >= vh * 0.95) {
      // Below the fold — start hidden then animate in.
      setVisible(false);
      setArmed(true);
      const io = new IntersectionObserver(
        (entries) => entries.forEach((e) => {
          if (e.isIntersecting) {setVisible(true);io.disconnect();}
        }),
        { threshold: 0.05, rootMargin: "0px 0px -5% 0px" }
      );
      io.observe(el);
      const t = setTimeout(() => setVisible(true), 1500);
      return () => {io.disconnect();clearTimeout(t);};
    }
  }, []);
  return (
    <As
      ref={ref}
      className={"reveal " + (visible ? "in " : "") + className}
      style={{ transitionDelay: `${delay}ms`, ...style }}>
      
      {children}
    </As>);

}

/* ============== Stroke icons (no lucide CDN — inline svg, 1.25 stroke) ============== */
const I = (paths, vb = "0 0 24 24") => ({ size = 18, color = "currentColor", className = "", style = {} }) =>
<svg width={size} height={size} viewBox={vb} fill="none" stroke={color} strokeWidth="1.25" strokeLinecap="round" strokeLinejoin="round" className={className} style={style} aria-hidden="true">
    {paths}
  </svg>;


const IconArrow = I(<><path d="M5 12h14" /><path d="m13 6 6 6-6 6" /></>);
const IconArrowUp = I(<><path d="M7 17 17 7" /><path d="M8 7h9v9" /></>);
const IconCheck = I(<path d="m5 12 4 4 10-10" />);
const IconPlus = I(<><path d="M12 5v14" /><path d="M5 12h14" /></>);
const IconMinus = I(<path d="M5 12h14" />);
const IconBolt = I(<path d="M13 2 4 14h7l-1 8 9-12h-7l1-8Z" />);
const IconShield = I(<><path d="M12 3 4 6v6c0 5 3.5 8 8 9 4.5-1 8-4 8-9V6l-8-3Z" /><path d="m9 12 2.2 2.2L15 10.5" /></>);
const IconLock = I(<><rect x="4" y="10" width="16" height="11" rx="2" /><path d="M8 10V7a4 4 0 0 1 8 0v3" /></>);
const IconServer = I(<><rect x="3" y="4" width="18" height="7" rx="2" /><rect x="3" y="13" width="18" height="7" rx="2" /><path d="M7 7.5h.01" /><path d="M7 16.5h.01" /></>);
const IconGlobe = I(<><circle cx="12" cy="12" r="9" /><path d="M3 12h18" /><path d="M12 3a14 14 0 0 1 0 18a14 14 0 0 1 0-18Z" /></>);
const IconBank = I(<><path d="M3 10 12 4l9 6" /><path d="M5 10v8" /><path d="M9 10v8" /><path d="M15 10v8" /><path d="M19 10v8" /><path d="M3 21h18" /></>);
const IconReceipt = I(<><path d="M5 3h14v18l-3-2-2 2-2-2-2 2-2-2-3 2V3Z" /><path d="M9 8h6" /><path d="M9 12h6" /><path d="M9 16h4" /></>);
const IconUsers = I(<><circle cx="9" cy="8" r="3.2" /><path d="M3 20a6 6 0 0 1 12 0" /><path d="M16 11a3 3 0 1 0 0-6" /><path d="M21 20a5 5 0 0 0-4-5" /></>);
const IconChat = I(<><path d="M4 5h16v11H8l-4 4V5Z" /><path d="M8 10h.01" /><path d="M12 10h.01" /><path d="M16 10h.01" /></>);
const IconChart = I(<><path d="M4 19V5" /><path d="M4 19h16" /><path d="m7 15 3-4 3 2 5-7" /></>);
const IconSparkle = I(<><path d="M12 3v4" /><path d="M12 17v4" /><path d="M3 12h4" /><path d="M17 12h4" /><path d="m5.5 5.5 2.5 2.5" /><path d="m16 16 2.5 2.5" /><path d="m18.5 5.5-2.5 2.5" /><path d="m8 16-2.5 2.5" /></>);
const IconLayers = I(<><path d="m12 3 9 5-9 5-9-5 9-5Z" /><path d="m3 13 9 5 9-5" /><path d="m3 18 9 5 9-5" /></>);
const IconTelegram = I(<><path d="m4 12 16-7-3 16-5-5-2 4-1-6 11-9" /></>);
const IconKeys = I(<><circle cx="8" cy="14" r="4" /><path d="m11 11 9-9" /><path d="m17 5 3 3" /><path d="m14 8 3 3" /></>);
const IconAudit = I(<><path d="M5 4h10l4 4v12H5V4Z" /><path d="M14 4v5h5" /><path d="m9 14 2 2 4-4" /></>);

/* ============== Logo (ZertekFlow) — original, geometric ============== */
function Logo({ size = 20 }) {
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 10 }}>
      <svg width={size} height={size} viewBox="0 0 24 24" fill="none" aria-hidden="true">
        <defs>
          <linearGradient id="zfg" x1="0" x2="1" y1="0" y2="1">
            <stop offset="0" stopColor="#a8f5d0" />
            <stop offset="1" stopColor="#7af5c8" />
          </linearGradient>
        </defs>
        <path d="M4 4h16L8 20h12" stroke="url(#zfg)" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" fill="none" />
        <circle cx="20" cy="4" r="1.6" fill="#a8f5d0" />
      </svg>
      <span style={{ fontSize: 16, fontWeight: 600, letterSpacing: "-0.02em" }}>
        Zertek<span style={{ color: "var(--fg-dim)", fontWeight: 400 }}>Flow</span>
      </span>
    </span>);

}

/* ============== Marquee logos (placeholder text logos) ============== */
function LogoMarquee() {
  const items = [
  "Алматы Технолоджи", "ТОО Балтык", "АО ЦентрФинанс", "Astana Group",
  "ТОО Темiр Жолы", "Karagandy Co.", "ИП Смагулов", "АО Жетысу",
  "ТОО Каспий Лоджистикс", "Aral Holdings", "ТОО Шёлковый Путь", "Tau Mining"];

  const row = [...items, ...items];
  return (
    <div style={{ position: "relative", overflow: "hidden", maskImage: "linear-gradient(90deg, transparent, #000 12%, #000 88%, transparent)", WebkitMaskImage: "linear-gradient(90deg, transparent, #000 12%, #000 88%, transparent)" }}>
      <div className="marquee-track" style={{ display: "flex", gap: 56, width: "max-content", whiteSpace: "nowrap", opacity: 0.4 }}>
        {row.map((n, i) =>
        <span key={i} style={{ display: "inline-flex", alignItems: "center", gap: 10, fontSize: 15, color: "var(--fg-dim)", letterSpacing: "-0.01em" }}>
            <span style={{ width: 8, height: 8, borderRadius: 2, background: "linear-gradient(135deg, rgba(255,255,255,0.4), rgba(255,255,255,0.05))", border: "1px solid var(--line)" }} />
            {n}
          </span>
        )}
      </div>
    </div>);

}

/* ============== Animated counter ============== */
function CountUp({ to = 142, duration = 1600, prefix = "", suffix = "" }) {
  const [val, setVal] = React.useState(0);
  const ref = React.useRef(null);
  React.useEffect(() => {
    const el = ref.current;
    if (!el) return;
    let raf, started = false;
    const start = () => {
      if (started) return; 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(Math.round(to * eased));
        if (p < 1) raf = requestAnimationFrame(tick);
      };
      raf = requestAnimationFrame(tick);
    };
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => { if (e.isIntersecting) { start(); io.disconnect(); } });
    }, { threshold: 0.4 });
    io.observe(el);
    return () => { io.disconnect(); cancelAnimationFrame(raf); };
  }, [to, duration]);
  return <span ref={ref} className="counter-num">{prefix}{val}{suffix}</span>;
}

/* ============== Hero mockup — Telegram chat + 1C panel ============== */
function HeroMockup() {
  // Mouse-tilt parallax
  const wrapRef = React.useRef(null);
  const onMove = (e) => {
    const el = wrapRef.current; if (!el) return;
    const r = el.getBoundingClientRect();
    const x = (e.clientX - r.left) / r.width - 0.5;
    const y = (e.clientY - r.top) / r.height - 0.5;
    el.style.transform = `perspective(2000px) rotateY(${-14 + x * 6}deg) rotateX(${3 - y * 6}deg)`;
  };
  const onLeave = () => {
    const el = wrapRef.current; if (!el) return;
    el.style.transform = "perspective(2000px) rotateY(-14deg) rotateX(3deg)";
  };
  return (
    <div ref={wrapRef} onMouseMove={onMove} onMouseLeave={onLeave} className="glass grad-border mockup-tilt tilt-3d" style={{
      width: "100%", maxWidth: 720,
      padding: 14, borderRadius: 18,
      boxShadow: "0 30px 80px -20px rgba(0,0,0,0.6), 0 0 0 1px rgba(255,255,255,0.04)"
    }}>
      {/* window chrome */}
      <div style={{ display: "flex", alignItems: "center", gap: 8, padding: "4px 6px 12px" }}>
        <span style={{ width: 10, height: 10, borderRadius: 50, background: "rgba(255,255,255,0.12)" }} />
        <span style={{ width: 10, height: 10, borderRadius: 50, background: "rgba(255,255,255,0.12)" }} />
        <span style={{ width: 10, height: 10, borderRadius: 50, background: "rgba(255,255,255,0.12)" }} />
        <span className="mono" style={{ marginLeft: 12, fontSize: 11, color: "var(--fg-mute)" }}>zertekflow.app / live</span>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1.1fr 1fr", gap: 12 }}>
        {/* Left: Telegram bot */}
        <div style={{ background: "rgba(255,255,255,0.02)", border: "1px solid var(--line)", borderRadius: 12, padding: 12, minHeight: 280 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 12, paddingBottom: 10, borderBottom: "1px solid var(--line)" }}>
            <div style={{ width: 26, height: 26, borderRadius: 50, background: "linear-gradient(135deg, #a8f5d0, #7af5c8)", display: "grid", placeItems: "center", color: "#042418" }}>
              <IconTelegram size={14} />
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 12, fontWeight: 500 }}>ZertekFlow Bot</div>
              <div className="mono" style={{ fontSize: 10, color: "var(--fg-mute)", display: "flex", alignItems: "center", gap: 6 }}>
                <span className="live-dot" style={{ width: 5, height: 5, borderRadius: 50, background: "var(--accent)" }} />
                online · агент №7
              </div>
            </div>
          </div>

          <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
            <Bubble side="in">Поступил платёж от ТОО «Ромашка», 1 248 500 ₸. Создать ПКО?</Bubble>
            <Bubble side="out">Да, и сверь с актом №112</Bubble>
            <Bubble side="in">
              <span style={{ color: "var(--accent)" }}>✓</span> ПКО №3041 проведён.<br />
              Акт №112 совпал на 100%.
              <div className="mono" style={{ fontSize: 10, color: "var(--fg-mute)", marginTop: 6 }}>0.8 сек · 1С:БК 3.0</div>
            </Bubble>
            <Bubble side="in" small>
              <span style={{ color: "var(--fg-mute)" }}>сегодня обработано:</span> <CountUp to={142} /> операции
            </Bubble>
            <div style={{ display: "flex", alignItems: "center", gap: 6, paddingLeft: 4, marginTop: 2 }}>
              <span className="typing-dot" />
              <span className="typing-dot" />
              <span className="typing-dot" />
              <span className="mono" style={{ fontSize: 10, color: "var(--fg-mute)", marginLeft: 4 }}>агент печатает…</span>
            </div>
          </div>
        </div>

        {/* Right: 1C panel */}
        <div style={{ background: "rgba(255,255,255,0.02)", border: "1px solid var(--line)", borderRadius: 12, padding: 12, display: "flex", flexDirection: "column", gap: 10 }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
            <div className="mono" style={{ fontSize: 10, color: "var(--fg-mute)", letterSpacing: "0.08em" }}>БАНК · 04.05.2026</div>
            <div className="live-dot" style={{ width: 6, height: 6, borderRadius: 50, background: "var(--accent)" }} />
          </div>

          <Row label="ТОО Ромашка" sub="БИН 950140000123" amount="+1 248 500" ok live />
          <Row label="ИП Алматинский" sub="ИИН 880612300456" amount="+ 84 200" ok />
          <Row label="ТОО Темiр Жолы" sub="БИН 010240003344" amount="− 312 000" />
          <Row label="АО ЦентрФинанс" sub="БИН 020940011002" amount="+ 2 410 000" ok />

          {/* sparkline */}
          <div style={{ marginTop: 4, padding: 10, border: "1px solid var(--line)", borderRadius: 10 }}>
            <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 6 }}>
              <span style={{ fontSize: 10, color: "var(--fg-mute)" }} className="mono">CASH FLOW · 7d</span>
              <span style={{ fontSize: 10, color: "var(--accent)" }} className="mono">+12.4%</span>
            </div>
            <Sparkline />
          </div>
        </div>
      </div>
    </div>);

}

function Bubble({ side, children, small }) {
  const isOut = side === "out";
  return (
    <div style={{ display: "flex", justifyContent: isOut ? "flex-end" : "flex-start" }}>
      <div style={{
        maxWidth: "85%",
        padding: small ? "5px 10px" : "8px 11px",
        fontSize: small ? 10 : 11.5,
        lineHeight: 1.45,
        borderRadius: 10,
        background: isOut ? "rgba(168, 245, 208, 0.12)" : "rgba(255,255,255,0.04)",
        border: "1px solid " + (isOut ? "rgba(168, 245, 208, 0.18)" : "var(--line)"),
        color: isOut ? "#dffbe9" : "var(--fg)"
      }}>{children}</div>
    </div>);

}

function Row({ label, sub, amount, ok, live }) {
  return (
    <div className={live ? "row-live" : ""} style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "6px 8px", borderBottom: "1px solid var(--line-2)", borderRadius: 6 }}>
      <div style={{ minWidth: 0 }}>
        <div style={{ fontSize: 11.5, fontWeight: 500, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{label}</div>
        <div className="mono" style={{ fontSize: 9.5, color: "var(--fg-mute)" }}>{sub}</div>
      </div>
      <div className="mono" style={{ fontSize: 11, color: ok ? "var(--accent)" : "var(--fg-dim)", whiteSpace: "nowrap" }}>{amount} ₸</div>
    </div>);

}

function Sparkline() {
  const pts = [8, 12, 9, 14, 11, 18, 16, 22, 19, 26, 24, 30];
  const max = Math.max(...pts),min = Math.min(...pts);
  const w = 220,h = 38;
  const sx = (i) => i / (pts.length - 1) * w;
  const sy = (v) => h - (v - min) / (max - min) * h;
  const d = pts.map((v, i) => `${i === 0 ? "M" : "L"}${sx(i).toFixed(1)} ${sy(v).toFixed(1)}`).join(" ");
  const fill = `${d} L${w} ${h} L0 ${h} Z`;
  return (
    <svg width="100%" viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none" style={{ display: "block" }}>
      <defs>
        <linearGradient id="spk" x1="0" x2="0" y1="0" y2="1">
          <stop offset="0" stopColor="#a8f5d0" stopOpacity="0.35" />
          <stop offset="1" stopColor="#a8f5d0" stopOpacity="0" />
        </linearGradient>
      </defs>
      <path className="spark-fill" d={fill} fill="url(#spk)" />
      <path className="spark-path" d={d} stroke="#a8f5d0" strokeWidth="1.25" fill="none" strokeLinecap="round" strokeLinejoin="round" />
    </svg>);

}

/* ============== Magnetic button wrapper ============== */
function Magnetic({ children, strength = 8, className = "", style = {} }) {
  const ref = React.useRef(null);
  const onMove = (e) => {
    const el = ref.current; if (!el) return;
    const r = el.getBoundingClientRect();
    const dx = (e.clientX - (r.left + r.width / 2)) / r.width;
    const dy = (e.clientY - (r.top + r.height / 2)) / r.height;
    el.style.transform = `translate(${dx * strength}px, ${dy * strength}px)`;
  };
  const onLeave = () => {
    const el = ref.current; if (!el) return;
    el.style.transform = "translate(0,0)";
  };
  return (
    <span ref={ref} onMouseMove={onMove} onMouseLeave={onLeave}
      className={className}
      style={{ display: "inline-flex", transition: "transform .35s cubic-bezier(.2,.7,.2,1)", ...style }}>
      {children}
    </span>
  );
}

/* ============== Export to global ============== */
Object.assign(window, {
  Reveal, Logo, LogoMarquee, HeroMockup, CountUp, Magnetic,
  IconArrow, IconArrowUp, IconCheck, IconPlus, IconMinus, IconBolt, IconShield,
  IconLock, IconServer, IconGlobe, IconBank, IconReceipt, IconUsers, IconChat,
  IconChart, IconSparkle, IconLayers, IconTelegram, IconKeys, IconAudit
});