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

const LOGO = "assets/borneo-logo.png";
const TG_URL = "https://t.me/borneocapital";

/* ------------------------------------------------------------------ */
/*  Dot-matrix Borneo / coin SVG used for the loading screen reveal   */
/* ------------------------------------------------------------------ */
function LoaderDotLogo({ go }) {
  // build a generative dot grid within a coin/circle, with denser cluster
  // shaped to roughly suggest the Borneo silhouette (organic dot mass)
  const dots = useMemo(() => {
    const arr = [];
    const size = 220;
    const cx = size / 2, cy = size / 2;
    const R = 96;
    const step = 7;
    let id = 0;
    for (let y = -R; y <= R; y += step) {
      for (let x = -R; x <= R; x += step) {
        const d = Math.hypot(x, y);
        if (d > R) continue;
        // create some organic variation: omit a few in outer band to feel like dot-matrix island
        const outerBand = d > R * 0.78;
        if (outerBand && Math.random() < 0.35) continue;
        if (!outerBand && Math.random() < 0.04) continue;
        const r = d > R * 0.7 ? 1.4 + Math.random() * 0.6 : 1.8 + Math.random() * 0.7;
        const op = 0.45 + Math.random() * 0.55;
        arr.push({
          id: id++,
          cx: cx + x,
          cy: cy + y,
          r,
          op,
          // delay grows with distance from center for "ripple from center" reveal
          delay: (d / R) * 1.2 + Math.random() * 0.15,
        });
      }
    }
    return arr;
  }, []);

  return (
    <svg viewBox="0 0 220 220" width="220" height="220" aria-hidden="true">
      <defs>
        <radialGradient id="dotG" cx="50%" cy="40%" r="65%">
          <stop offset="0%" stopColor="#ffffff" stopOpacity="1" />
          <stop offset="60%" stopColor="#cfe2ff" stopOpacity="0.9" />
          <stop offset="100%" stopColor="#7eb3ff" stopOpacity="0.5" />
        </radialGradient>
      </defs>
      {dots.map((d) => (
        <circle
          key={d.id}
          className="ldot"
          cx={d.cx}
          cy={d.cy}
          r={d.r}
          fill="url(#dotG)"
          opacity={d.op}
          style={{ animationDelay: go ? `${d.delay}s` : "0s" }}
        />
      ))}
    </svg>
  );
}

/* ------------------------------------------------------------------ */
/*  Loading Screen                                                    */
/* ------------------------------------------------------------------ */
function LoadingScreen({ done }) {
  const [revealDots, setRevealDots] = useState(false);
  const title = "BORNEO CAPITAL";

  useEffect(() => {
    const t = setTimeout(() => setRevealDots(true), 120);
    return () => clearTimeout(t);
  }, []);

  return (
    <div className={`loader ${done ? "hidden" : ""}`}>
      <div className={`loader-logo ${revealDots ? "go" : ""}`}>
        <div className="glow" />
        <div className="ring" />
        <LoaderDotLogo go={revealDots} />
      </div>

      <div className="loader-title" aria-label={title}>
        {title.split("").map((ch, i) => (
          <span key={i} style={{ animationDelay: `${0.8 + i * 0.05}s` }}>
            {ch === " " ? "\u00A0" : ch}
          </span>
        ))}
      </div>

      <div className="loader-bar"><i /></div>
      <div className="loader-sub">KOMUNITAS XAU&nbsp;·&nbsp;EST. 2018</div>
    </div>
  );
}

/* ------------------------------------------------------------------ */
/*  Navbar (floating pill)                                            */
/* ------------------------------------------------------------------ */
const NAV_ITEMS = [
  { href: "#team", label: "Tim" },
  { href: "#hasil", label: "Hasil" },
  { href: "#tutorial", label: "Tutorial HFM", icon: "assets/hfm-logo.jpg" },
];

function Navbar() {
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 16);
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === "Escape") setOpen(false); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open]);

  return (
    <>
      <nav className={`nav ${scrolled ? "scrolled" : ""}`} data-screen-label="Navbar">
        <a href="#top" className="nav-brand" aria-label="Borneo Capital home">
          <div className="nav-logo"><img src={LOGO} alt="" /></div>
          <span className="b1">Borneo Capital</span>
        </a>

        <ul className="nav-links">
          {NAV_ITEMS.map((it) => (
            <li key={it.href}>
              <a className={it.icon ? "has-icon" : ""} href={it.href}>
                {it.icon && <img src={it.icon} alt="" />}
                {it.label}
              </a>
            </li>
          ))}
        </ul>

        <a className="btn-cta" href={TG_URL} target="_blank" rel="noopener noreferrer">
          <span>Gabung</span>
          <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h14M13 5l7 7-7 7"/></svg>
        </a>

        <button className="nav-menu-btn" onClick={() => setOpen((o) => !o)} aria-label="Open menu" aria-expanded={open}>
          {open ? (
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M6 6l12 12M18 6L6 18"/></svg>
          ) : (
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M4 7h16M4 12h16M4 17h16"/></svg>
          )}
        </button>
      </nav>

      <div className={`nav-mobile ${open ? "open" : ""}`} role="menu">
        <ul>
          {NAV_ITEMS.map((it) => (
            <li key={it.href}>
              <a className={it.icon ? "has-icon" : ""} href={it.href} onClick={() => setOpen(false)}>
                {it.icon && <img src={it.icon} alt="" />}
                <span>{it.label}</span>
              </a>
            </li>
          ))}
          <li>
            <a href={TG_URL} target="_blank" rel="noopener noreferrer" onClick={() => setOpen(false)}>
              <svg width="22" height="22" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M21.5 4.5L2.5 12l5.5 2 2 6 3-4 5 4 3.5-15.5z"/></svg>
              <span>Gabung VIP Gratis</span>
            </a>
          </li>
        </ul>
      </div>
    </>
  );
}

/* ------------------------------------------------------------------ */
/*  Reveal-on-scroll wrapper                                          */
/* ------------------------------------------------------------------ */
function Reveal({ children, child, as: As = "div", className = "", ...rest }) {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const obs = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => { if (e.isIntersecting) { el.classList.add("in"); obs.unobserve(el); } });
      },
      { threshold: 0.14, rootMargin: "0px 0px -60px 0px" }
    );
    obs.observe(el);
    return () => obs.disconnect();
  }, []);
  const cls = [child ? "reveal-child" : "reveal", className].filter(Boolean).join(" ");
  return <As ref={ref} className={cls} {...rest}>{children}</As>;
}

/* ------------------------------------------------------------------ */
/*  Interactive cursor-reactive dot constellation                     */
/* ------------------------------------------------------------------ */
function HeroDotField({ heroRef }) {
  const canvasRef = useRef(null);

  useEffect(() => {
    const canvas = canvasRef.current;
    const hero = heroRef.current;
    if (!canvas || !hero) return;
    const ctx = canvas.getContext("2d");
    const DPR = Math.min(window.devicePixelRatio || 1, 2);

    let W = 0, H = 0;
    let dots = [];
    const SPACING = 38;

    const buildDots = () => {
      dots = [];
      const cols = Math.ceil(W / SPACING) + 2;
      const rows = Math.ceil(H / SPACING) + 2;
      for (let i = 0; i < rows; i++) {
        for (let j = 0; j < cols; j++) {
          const ox = (j - 1) * SPACING + (i % 2 === 0 ? 0 : SPACING / 2);
          const oy = (i - 1) * SPACING;
          // base opacity falls off near edges, slight randomness for life
          const baseOp = 0.12 + Math.random() * 0.28;
          dots.push({
            ox, oy,
            x: ox, y: oy,
            vx: 0, vy: 0,
            baseOp,
            op: baseOp,
            phase: Math.random() * Math.PI * 2,
          });
        }
      }
    };

    const resize = () => {
      const rect = hero.getBoundingClientRect();
      W = rect.width;
      H = rect.height;
      canvas.width = W * DPR;
      canvas.height = H * DPR;
      canvas.style.width = W + "px";
      canvas.style.height = H + "px";
      ctx.scale(DPR, DPR);
      buildDots();
    };

    const mouse = { x: -9999, y: -9999, active: false };
    const onMove = (e) => {
      const rect = hero.getBoundingClientRect();
      const cx = (e.touches ? e.touches[0].clientX : e.clientX) - rect.left;
      const cy = (e.touches ? e.touches[0].clientY : e.clientY) - rect.top;
      mouse.x = cx; mouse.y = cy; mouse.active = true;
    };
    const onLeave = () => { mouse.x = -9999; mouse.y = -9999; mouse.active = false; };

    resize();
    window.addEventListener("resize", resize);
    hero.addEventListener("mousemove", onMove);
    hero.addEventListener("mouseleave", onLeave);
    hero.addEventListener("touchmove", onMove, { passive: true });
    hero.addEventListener("touchend", onLeave);

    const RADIUS = 140;
    const STRENGTH = 36;
    let raf = 0;
    let t0 = performance.now();

    const tick = (now) => {
      const t = (now - t0) / 1000;
      ctx.clearRect(0, 0, W, H);

      // background subtle linework between near dots (constellation)
      ctx.lineWidth = 1;

      for (let i = 0; i < dots.length; i++) {
        const d = dots[i];
        // gentle idle drift
        const driftX = Math.sin(t * 0.6 + d.phase) * 0.8;
        const driftY = Math.cos(t * 0.5 + d.phase * 1.3) * 0.8;
        let tx = d.ox + driftX;
        let ty = d.oy + driftY;

        // repel from cursor
        const dx = tx - mouse.x;
        const dy = ty - mouse.y;
        const dist = Math.hypot(dx, dy);
        let highlight = 0;
        if (mouse.active && dist < RADIUS) {
          const f = (1 - dist / RADIUS);
          const push = f * STRENGTH;
          const ang = Math.atan2(dy, dx);
          tx += Math.cos(ang) * push;
          ty += Math.sin(ang) * push;
          highlight = f;
        }

        // smooth spring back
        d.x += (tx - d.x) * 0.18;
        d.y += (ty - d.y) * 0.18;
        d.op = d.baseOp + highlight * 0.7;

        const r = 1.1 + highlight * 1.6;
        ctx.beginPath();
        ctx.fillStyle = highlight > 0.05
          ? `rgba(180, 215, 255, ${Math.min(1, d.op)})`
          : `rgba(170, 200, 255, ${d.op})`;
        if (highlight > 0.1) {
          ctx.shadowColor = `rgba(96, 176, 255, ${highlight * 0.9})`;
          ctx.shadowBlur = 10 * highlight;
        } else {
          ctx.shadowBlur = 0;
        }
        ctx.arc(d.x, d.y, r, 0, Math.PI * 2);
        ctx.fill();
      }
      ctx.shadowBlur = 0;

      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);

    return () => {
      cancelAnimationFrame(raf);
      window.removeEventListener("resize", resize);
      hero.removeEventListener("mousemove", onMove);
      hero.removeEventListener("mouseleave", onLeave);
      hero.removeEventListener("touchmove", onMove);
      hero.removeEventListener("touchend", onLeave);
    };
  }, [heroRef]);

  return <canvas ref={canvasRef} className="hero-canvas" aria-hidden="true" />;
}

/* ------------------------------------------------------------------ */
/*  Title with per-letter rise + magnetic group tilt                  */
/* ------------------------------------------------------------------ */
function MagneticTitle() {
  const wrapRef = useRef(null);
  const innerRef = useRef(null);

  useEffect(() => {
    const wrap = wrapRef.current;
    const inner = innerRef.current;
    if (!wrap || !inner) return;
    let raf = 0;
    let tx = 0, ty = 0, cx = 0, cy = 0;

    const onMove = (e) => {
      const r = wrap.getBoundingClientRect();
      tx = ((e.clientX - r.left) / r.width - 0.5) * 2;   // -1..1
      ty = ((e.clientY - r.top) / r.height - 0.5) * 2;
      if (!raf) raf = requestAnimationFrame(tick);
    };
    const onLeave = () => { tx = 0; ty = 0; if (!raf) raf = requestAnimationFrame(tick); };
    const tick = () => {
      cx += (tx - cx) * 0.12;
      cy += (ty - cy) * 0.12;
      inner.style.setProperty("--tx", cx.toFixed(3));
      inner.style.setProperty("--ty", cy.toFixed(3));
      if (Math.abs(tx - cx) > 0.002 || Math.abs(ty - cy) > 0.002) {
        raf = requestAnimationFrame(tick);
      } else {
        raf = 0;
      }
    };

    // Listen on the hero so cursor anywhere over the hero drives the tilt.
    const hero = wrap.closest(".hero") || wrap;
    hero.addEventListener("mousemove", onMove);
    hero.addEventListener("mouseleave", onLeave);
    return () => {
      cancelAnimationFrame(raf);
      hero.removeEventListener("mousemove", onMove);
      hero.removeEventListener("mouseleave", onLeave);
    };
  }, []);

  const part1 = "Trading Emas";
  const part2 = "Bukan Judi.";
  let i = 0;
  const renderLetters = (text, italic = false) =>
    text.split("").map((ch, k) => {
      const delay = 0.1 + (i++) * 0.045;
      return (
        <span
          key={`${italic ? "i" : "r"}-${k}`}
          className={`title-letter${italic ? " italic" : ""}`}
          style={{ animationDelay: `${delay}s` }}
        >
          {ch === " " ? "\u00A0" : ch}
        </span>
      );
    });

  return (
    <div className="magnetic" ref={wrapRef}>
      <div className="magnetic-inner" ref={innerRef} style={{ "--tx": 0, "--ty": 0 }}>
        <div className="hero-pill">
          <svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M12 2l2.39 7.36H22l-6.19 4.5L18.18 21 12 16.5 5.82 21l2.37-7.14L2 9.36h7.61z"/></svg>
          <span>Berpengalaman 7+ Tahun di XAU/USD</span>
        </div>

        <h1 className="h-display hero-title" aria-label="Trading Emas Bukan Judi.">
          {renderLetters(part1)}
          <br />
          {renderLetters(part2, true)}
        </h1>

        <p className="hero-sub">
          Bergabung dengan <b style={{ color: "var(--white)" }}>2,000+ trader</b> yang sudah profit konsisten bersama Borneo Capital sejak 2018.
        </p>

        <div className="hero-actions">
          <a className="btn-hero-primary" href={TG_URL} target="_blank" rel="noopener noreferrer">
            <span style={{ position: "relative", zIndex: 1, display: "inline-flex", alignItems: "center", gap: 10 }}>
              <span>Gabung VIP <b style={{ color: "#fff8d6" }}>GRATIS</b></span>
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h14M13 5l7 7-7 7"/></svg>
            </span>
          </a>
          <a className="btn-hero-secondary" href={TG_URL} target="_blank" rel="noopener noreferrer">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M21.5 4.5L2.5 12l5.5 2 2 6 3-4 5 4 3.5-15.5z"/></svg>
            <span>Lihat Channel Publik</span>
          </a>
        </div>

        <div className="slot-pulse">
          <span style={{ fontSize: 14 }}>⚡</span>
          <span>Slot gratis tersisa: <b style={{ color: "var(--white)" }}>130 orang</b> — setelah penuh, VIP akan berbayar.</span>
        </div>
      </div>
    </div>
  );
}

/* ------------------------------------------------------------------ */
/*  Live XAU ticker (animated fake-live price)                        */
/* ------------------------------------------------------------------ */
function LiveTicker() {
  const [price, setPrice] = useState(2342.18);
  const [delta, setDelta] = useState(+12.4);
  const baseRef = useRef(2342.18);

  useEffect(() => {
    const id = setInterval(() => {
      const drift = (Math.random() - 0.45) * 1.6;
      baseRef.current = Math.max(2320, Math.min(2360, baseRef.current + drift));
      setPrice(baseRef.current);
      setDelta((baseRef.current - 2329.78));
    }, 1400);
    return () => clearInterval(id);
  }, []);

  const up = delta >= 0;
  return (
    <div className="ticker">
      <span className="live-badge"><i />LIVE</span>
      <span className="pair">XAU/USD</span>
      <span className="price">${price.toFixed(2)}</span>
      <svg className="spark" viewBox="0 0 60 20" preserveAspectRatio="none" aria-hidden="true">
        <path d="M0 14 L8 12 L14 15 L22 8 L30 11 L38 6 L46 9 L54 4 L60 6" fill="none" stroke={up ? "#86efac" : "#fca5a5"} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
      </svg>
      <span className={`delta ${up ? "" : "down"}`}>{up ? "▲" : "▼"} {Math.abs(delta).toFixed(2)}</span>
    </div>
  );
}

/* ------------------------------------------------------------------ */
/*  Floating signal cards                                             */
/* ------------------------------------------------------------------ */
// 5 inline gradient SVG avatars so we don't depend on remote services.
const AVATAR_DATA = [
  { bg: "#4A9EFF,#1A3A6B", ini: "A" },
  { bg: "#f0c674,#8a5a00", ini: "S" },
  { bg: "#86efac,#15803d", ini: "R" },
  { bg: "#fca5a5,#9f1239", ini: "D" },
  { bg: "#c4b5fd,#4c1d95", ini: "N" },
];
function makeAvatarDataUri({ bg, ini }) {
  const [c1, c2] = bg.split(",");
  const svg = `
<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64'>
  <defs><linearGradient id='g' x1='0' x2='1' y1='0' y2='1'>
    <stop offset='0%' stop-color='${c1}'/><stop offset='100%' stop-color='${c2}'/>
  </linearGradient></defs>
  <rect width='64' height='64' fill='url(#g)'/>
  <text x='32' y='40' text-anchor='middle' font-family='DM Sans, sans-serif' font-weight='700' font-size='28' fill='rgba(255,255,255,0.92)'>${ini}</text>
</svg>`;
  return "data:image/svg+xml;utf8," + encodeURIComponent(svg);
}
const AVATARS = AVATAR_DATA.map(makeAvatarDataUri);

function FloatCards() {
  return (
    <>
      {/* fc-1: Sentimen Pasar gauge (replaces 'Sinyal terakhir') */}
      <div className="float-card fc-1">
        <div className="row" style={{ justifyContent: "space-between" }}>
          <span className="label">Sentimen XAU</span>
          <span className="badge buy">BULLISH</span>
        </div>
        <div className="row" style={{ marginTop: 8 }}>
          <span className="value">72%</span>
          <span style={{ color: "var(--dim)", fontSize: 11, marginLeft: 6 }}>BUY bias</span>
        </div>
        <div className="row" style={{ marginTop: 8, gap: 3 }}>
          {Array.from({ length: 10 }).map((_, k) => (
            <i key={k} style={{
              flex: 1, height: 5, borderRadius: 2,
              background: k < 7 ? "linear-gradient(90deg, #4A9EFF, #86efac)" : "rgba(255,255,255,0.08)"
            }}/>
          ))}
        </div>
      </div>

      <div className="float-card fc-2">
        <div className="row" style={{ justifyContent: "space-between" }}>
          <span className="label">Sesi NY · hari ini</span>
          <svg className="mini-spark" viewBox="0 0 40 22" preserveAspectRatio="none" aria-hidden="true">
            <path d="M0 16 L8 14 L14 17 L22 8 L30 11 L40 4" fill="none" stroke="#86efac" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </div>
        <div className="row" style={{ marginTop: 8 }}>
          <span className="value" style={{ color: "#86efac" }}>+$1,420</span>
        </div>
        <div className="row" style={{ marginTop: 4, color: "var(--dim)", fontSize: 11 }}>
          Closed · +185 pips
        </div>
      </div>

      <div className="float-card fc-3">
        <div className="row">
          <div className="avatars">
            {AVATARS.map((src, k) => <img key={k} src={src} alt="" />)}
          </div>
          <span className="value" style={{ fontSize: 16, marginLeft: 4 }}>654+</span>
        </div>
        <div className="row" style={{ marginTop: 6, color: "var(--dim)", fontSize: 11 }}>
          Trader aktif minggu ini
        </div>
      </div>

      <div className="float-card fc-4">
        <div className="row" style={{ justifyContent: "space-between" }}>
          <span className="label">Win rate</span>
          <span className="badge">Mei 2026</span>
        </div>
        <div className="row" style={{ marginTop: 8 }}>
          <span className="value">85.4%</span>
        </div>
        <div className="row" style={{ marginTop: 6, gap: 4 }}>
          {Array.from({ length: 8 }).map((_, k) => (
            <i key={k} style={{
              flex: 1, height: 4, borderRadius: 2,
              background: k < 7 ? "linear-gradient(90deg, #4A9EFF, #86efac)" : "rgba(255,255,255,0.08)"
            }}/>
          ))}
        </div>
      </div>
    </>
  );
}

/* ------------------------------------------------------------------ */
/*  Hero                                                              */
/* ------------------------------------------------------------------ */
function Hero() {
  const heroRef = useRef(null);
  const logoRef = useRef(null);

  useEffect(() => {
    const onScroll = () => {
      const y = window.scrollY;
      if (y > 800) return;
      if (logoRef.current) logoRef.current.style.transform = `translate3d(0, ${y * -0.08}px, 0)`;
    };
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  return (
    <section id="top" className="hero section" data-screen-label="Hero" ref={heroRef}>
      <HeroDotField heroRef={heroRef} />
      <FloatCards />

      <div className="hero-inner">
        <div ref={logoRef} className="hero-logo">
          <div className="halo" />
          <img src={LOGO} alt="Borneo Capital" />
        </div>

        <MagneticTitle />
      </div>

      <div className="scroll-cue" aria-hidden="true">
        <span>Scroll</span>
        <span className="line" />
      </div>
    </section>
  );
}

/* ------------------------------------------------------------------ */
/*  Partner Marquee — running logo + name strip                       */
/* ------------------------------------------------------------------ */
function PartnerMarquee() {
  const partners = [
    { img: "assets/partner-forex-kalimantan.png", title: "Forex Kalimantan", sub: "Borneo Capital Market" },
    { img: "assets/hfm-logo.jpg", title: "HFM Global", sub: "HF Markets · Broker Resmi" },
    { img: "assets/mt5-logo.png", title: "MetaTrader 5", sub: "Platform Trading" },
  ];
  const reel = [];
  // 3 full loops so the track is long enough for a smooth seamless marquee
  for (let n = 0; n < 3; n++) {
    partners.forEach((p, i) => {
      reel.push(
        <React.Fragment key={`${n}-${i}`}>
          <div className="partner-chip">
            <img src={p.img} alt={p.title} />
            <div>
              <div className="pt-title">{p.title}</div>
              <div className="pt-sub">{p.sub}</div>
            </div>
          </div>
          <span className="star" aria-hidden="true">✦</span>
        </React.Fragment>
      );
    });
  }
  return (
    <section className="partners" data-screen-label="Partners">
      <div className="partners-label"><span>Official Partner & Platform</span></div>
      <div className="marquee" aria-label="Partners: Forex Kalimantan, HFM Global, MetaTrader 5">
        <div className="marquee-track">{reel}</div>
        <div className="marquee-track" aria-hidden="true">{reel}</div>
      </div>
    </section>
  );
}

/* ------------------------------------------------------------------ */
/*  Team section                                                      */
/* ------------------------------------------------------------------ */
function Team() {
  const members = [
    {
      photo: "assets/natan.jpg",
      role: "Founder · Lead Trader",
      name: "Natan Awan",
      handle: "@natanawan",
      tg: "https://t.me/natanawan",
      blurb:
        "Trader emas sejak 2018. Membangun Borneo Capital dari nol — fokus di XAU/USD dengan pendekatan price-action dan manajemen risiko yang ketat.",
      stats: [
        { n: "7+", l: "Thn Trading" },
        { n: "2K+", l: "Member" },
        { n: "XAU", l: "Spesialis" },
      ],
    },
    {
      photo: "assets/ceomarket.jpg",
      role: "Co-Founder · Mentor",
      name: "CEO MarketFX",
      handle: "@ceomarket28",
      tg: "https://t.me/ceomarket28",
      blurb:
        "Mentor & market analyst. Bantu komunitas tumbuh lewat edukasi strategi, mindset, dan analisis sesi London — NY setiap hari.",
      stats: [
        { n: "500+", l: "Murid" },
        { n: "Daily", l: "Analisis" },
        { n: "L–NY", l: "Sesi" },
      ],
    },
  ];

  return (
    <section className="section" data-screen-label="Team" id="team">
      <Reveal child style={{ marginBottom: 30 }}>
        <span className="eyebrow"><span className="dot" />Tim Inti</span>
        <h2 className="h-display section-title" style={{ marginTop: 18 }}>
          Dijalankan oleh trader <em>nyata</em>, bukan robot sinyal.
        </h2>
        <p className="section-sub">
          Tim mentor Borneo Capital yang langsung handle analisis, edukasi, dan support komunitas — tiap hari.
        </p>
      </Reveal>

      <Reveal child className="team-grid">
        {members.map((m, i) => (
          <div key={i} className="team-card glass">
            <div className="team-photo"><img src={m.photo} alt={m.name} /></div>
            <div className="team-info">
              <div className="team-role">{m.role}</div>
              <div className="team-name">{m.name}</div>
              <a className="team-handle" href={m.tg} target="_blank" rel="noopener noreferrer">
                <svg width="13" height="13" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M21.5 4.5L2.5 12l5.5 2 2 6 3-4 5 4 3.5-15.5z"/></svg>
                {m.handle}
              </a>
              <p className="team-blurb">{m.blurb}</p>
              <div className="team-stats">
                {m.stats.map((s, k) => (
                  <div key={k}><div className="n">{s.n}</div><div className="l">{s.l}</div></div>
                ))}
              </div>
              <div className="team-actions">
                <a className="team-tg" href={m.tg} target="_blank" rel="noopener noreferrer">
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M21.5 4.5L2.5 12l5.5 2 2 6 3-4 5 4 3.5-15.5z"/></svg>
                  Chat di Telegram
                </a>
              </div>
            </div>
          </div>
        ))}
      </Reveal>
    </section>
  );
}

/* ------------------------------------------------------------------ */
/*  Tutorial HFM Section                                              */
/* ------------------------------------------------------------------ */
const HFM_URL = "https://www.hfmtrade-ind.com/sv/en/?refid=30534202";

function TutorialHfm() {
  const steps = [
    {
      n: "01",
      title: "Daftar HFM",
      body: "Daftar lewat link partner Borneo Capital biar dapet bonus + akses sinyal VIP.",
      pill: "5 menit",
    },
    {
      n: "02",
      title: "Verifikasi KYC",
      body: "Upload KTP & selfie. Verifikasi biasanya keluar dalam 1–3 jam kerja.",
      pill: "Sekali aja",
    },
    {
      n: "03",
      title: "Deposit & Install MT4/5",
      body: "Top-up modal sesuai kemampuan. Install MT4 atau MT5 + login akun real.",
      pill: "Fleksibel",
    },
    {
      n: "04",
      title: "Ikuti Sinyal Komunitas",
      body: "Eksekusi sinyal XAU/USD dari mentor. Pakai lot sesuai manajemen risiko.",
      pill: "Daily setup",
    },
  ];
  return (
    <section id="tutorial" className="section" data-screen-label="Tutorial HFM">
      <Reveal child style={{ marginBottom: 24 }}>
        <span className="eyebrow"><span className="dot" />Tutorial · Broker Partner</span>
        <h2 className="h-display section-title" style={{ marginTop: 18 }}>
          Cara mulai trading di <em>HFM</em> bareng Borneo Capital.
        </h2>
        <p className="section-sub">
          HFM (HF Markets) adalah broker partner resmi kami. Spread tipis di XAU, eksekusi cepat, regulasi global — cocok buat ikuti sinyal komunitas.
        </p>
        <div className="tut-head" style={{ marginTop: 22 }}>
          <div className="tut-broker-chip">
            <img src="assets/hfm-logo.jpg" alt="HFM" />
            <div>
              <div className="l">Broker Partner</div>
              <div className="n">HFM · HF Markets</div>
            </div>
          </div>
        </div>
      </Reveal>

      <Reveal child className="tut-grid">
        {steps.map((s) => (
          <div key={s.n} className="tut-card glass">
            <div className="step">{s.n}</div>
            <h4>{s.title}</h4>
            <p>{s.body}</p>
            <span className="pill">{s.pill}</span>
          </div>
        ))}
      </Reveal>

      <Reveal>
        <div className="tut-cta">
          <div className="left">
            <img src="assets/hfm-logo.jpg" alt="" />
            <div>
              <div className="t">Buka akun HFM via link partner</div>
              <div className="s">Wajib pakai link ini biar bisa akses sinyal VIP gratis dari Borneo Capital.</div>
            </div>
          </div>
          <a className="tut-cta-btn" href={HFM_URL} target="_blank" rel="noopener noreferrer">
            Daftar HFM Sekarang
            <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M7 17L17 7M9 7h8v8"/></svg>
          </a>
        </div>
      </Reveal>
    </section>
  );
}

/* ------------------------------------------------------------------ */
/*  Animated Counter                                                  */
/* ------------------------------------------------------------------ */
function Counter({ to, suffix = "", duration = 1800, decimals = 0, formatThousands = true }) {
  const [val, setVal] = useState(0);
  const ref = useRef(null);
  const started = useRef(false);

  useEffect(() => {
    const el = ref.current; if (!el) return;
    const obs = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting && !started.current) {
          started.current = true;
          const t0 = performance.now();
          const ease = (t) => 1 - Math.pow(1 - t, 3);
          const tick = (now) => {
            const p = Math.min(1, (now - t0) / duration);
            setVal(to * ease(p));
            if (p < 1) requestAnimationFrame(tick);
          };
          requestAnimationFrame(tick);
        }
      });
    }, { threshold: 0.4 });
    obs.observe(el);
    return () => obs.disconnect();
  }, [to, duration]);

  let n = decimals ? val.toFixed(decimals) : Math.round(val).toString();
  if (formatThousands) n = Number(n).toLocaleString("en-US");
  return <span ref={ref}>{n}{suffix}</span>;
}

/* ------------------------------------------------------------------ */
/*  Stats                                                             */
/* ------------------------------------------------------------------ */
function Stats() {
  const items = [
    { icon: "👥", num: 2000, suf: "+", label: "Member Aktif Komunitas" },
    { icon: "⏳", num: 7, suf: "+", label: "Tahun Pengalaman di XAU" },
    { icon: "🎯", num: 85, suf: "%", label: "Win Rate Bulanan Rata-rata" },
    { icon: "💬", text: "24/7", label: "Support & Analisis Pasar" },
  ];
  return (
    <section className="section" data-screen-label="Stats">
      <Reveal child className="stats">
        {items.map((it, i) => (
          <div key={i} className="stat glass">
            <div className="stat-icon">{it.icon}</div>
            <div className="stat-num">
              {it.text ? it.text : <><Counter to={it.num} /><span className="unit">{it.suf}</span></>}
            </div>
            <div className="stat-label">{it.label}</div>
          </div>
        ))}
      </Reveal>
    </section>
  );
}

/* ------------------------------------------------------------------ */
/*  Narrative                                                         */
/* ------------------------------------------------------------------ */
function Narrative() {
  const features = [
    { icon: "📊", title: "Sinyal XAU Premium", body: "Entry, TP, SL akurat dengan analisis lengkap setiap sesi." },
    { icon: "🎓", title: "Edukasi Trading", body: "Materi dari dasar sampai advanced, gratis untuk member VIP." },
    { icon: "💬", title: "Komunitas Solid", body: "Diskusi real-time, sharing setup, support sesama trader." },
    { icon: "📈", title: "Track Record Terbukti", body: "Hasil trading transparan, bisa dicek langsung." },
  ];

  return (
    <section className="section" data-screen-label="Narrative">
      <Reveal child style={{ textAlign: "left", marginBottom: 36 }}>
        <span className="eyebrow"><span className="dot" />Kenapa Borneo Capital</span>
        <h2 className="h-display section-title" style={{ marginTop: 18 }}>
          Bukan sekadar grup sinyal — <em>komunitas trader emas</em> yang tumbuh bareng.
        </h2>
      </Reveal>

      <Reveal className="narrative">
        <div className="narrative-card glass">
          <div className="kicker">Sejak 2018</div>
          <p>
            Borneo Capital dibangun dari pengalaman nyata di market sejak 2018.
            Dari modal kecil, belajar dari nol, jatuh bangun di market — sampai
            akhirnya menemukan sistem trading yang konsisten profit di XAU/USD.
          </p>
          <p>
            Di sini, kamu nggak cuma dapat sinyal — tapi juga edukasi, mindset
            trading yang benar, dan support dari komunitas yang solid.
            <em style={{ color: "var(--accent-3)", fontStyle: "italic" }}> Kita tumbuh bareng.</em>
          </p>

          <div style={{ display: "flex", gap: 18, marginTop: 26, flexWrap: "wrap" }}>
            <Mini label="Sesi harian" value="London + NY" />
            <Mini label="Pair fokus" value="XAU/USD" />
            <Mini label="Base" value="Kalimantan" />
          </div>
        </div>

        <div className="narrative-visual glass">
          <div className="narrative-overlay"><span className="live-dot" />LIVE · KOMUNITAS</div>
          <div className="map"><img src={LOGO} alt="Borneo Capital coin" /></div>
        </div>
      </Reveal>

      <Reveal child className="features">
        {features.map((f, i) => (
          <div key={i} className="feature glass">
            <div className="feature-icon">{f.icon}</div>
            <h4>{f.title}</h4>
            <p>{f.body}</p>
          </div>
        ))}
      </Reveal>
    </section>
  );
}

function Mini({ label, value }) {
  return (
    <div style={{ paddingRight: 18, borderRight: "1px solid rgba(255,255,255,0.08)" }}>
      <div style={{ fontSize: 11, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--dim)" }}>{label}</div>
      <div style={{ fontFamily: "var(--font-display)", fontWeight: 600, color: "var(--white)", fontSize: 18, marginTop: 4 }}>{value}</div>
    </div>
  );
}

/* ------------------------------------------------------------------ */
/*  PnL Gallery (real screenshots + lightbox)                         */
/* ------------------------------------------------------------------ */
function PnlGallery() {
  const [active, setActive] = useState(null);
  const teaser = window.TRADES.slice(0, 6);
  const idx = teaser.findIndex((t) => t === active);
  const onOpen = (t) => setActive(t);
  const onClose = () => setActive(null);
  const onPrev = idx > 0 ? () => setActive(teaser[idx - 1]) : null;
  const onNext = idx >= 0 && idx < teaser.length - 1 ? () => setActive(teaser[idx + 1]) : null;

  return (
    <section className="section" data-screen-label="Gallery" id="hasil">
      <Reveal child style={{ marginBottom: 36 }}>
        <span className="eyebrow"><span className="dot" />Bukti Performa</span>
        <h2 className="h-display section-title" style={{ marginTop: 18 }}>
          Bukti nyata, <em>bukan janji manis.</em>
        </h2>
        <p className="section-sub">
          Screenshot PnL asli dari member komunitas. Klik untuk lihat detail trade dan member-nya.
        </p>
      </Reveal>

      <Reveal child className="pnl-grid">
        {teaser.map((t) => (
          <TradeCard key={t.id} t={t} onOpen={onOpen} />
        ))}
      </Reveal>

      <Reveal>
        <div className="gallery-cta-row">
          <div className="lhs">
            <div className="ic">
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="3" width="7" height="7" rx="1"/><rect x="14" y="3" width="7" height="7" rx="1"/><rect x="3" y="14" width="7" height="7" rx="1"/><rect x="14" y="14" width="7" height="7" rx="1"/></svg>
            </div>
            <div>
              <div className="t">Mau lihat semua hasil member?</div>
              <div className="s">Daily trades, filter by tipe, dan detail tiap entry — update terus tiap hari.</div>
            </div>
          </div>
          <a className="btn-arrow" href="hasil.html">
            Lihat Semua Hasil
            <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h14M13 5l7 7-7 7"/></svg>
          </a>
        </div>
      </Reveal>

      <Lightbox trade={active} onClose={onClose} onPrev={onPrev} onNext={onNext} />
    </section>
  );
}

/* ------------------------------------------------------------------ */
/*  CTA Section                                                       */
/* ------------------------------------------------------------------ */
function CtaSection() {
  return (
    <section className="cta" data-screen-label="CTA">
      <Reveal child className="cta-card">
        <div className="cta-slot">
          <span style={{ fontSize: 14 }}>🔥</span>
          <span><Counter to={130} /> Slot Tersisa</span>
        </div>
        <h2>Siap profit bareng? 🚀</h2>
        <p>
          Gabung sekarang selagi slot gratis masih tersedia.
          Setelah 130 slot terisi, akses VIP akan berbayar <b style={{ color: "var(--white)" }}>Rp 500.000/bulan</b>.
        </p>
        <a className="btn-hero-primary" href={TG_URL} target="_blank" rel="noopener noreferrer" style={{ position: "relative" }}>
          <span style={{ position: "relative", zIndex: 1, display: "inline-flex", alignItems: "center", gap: 10 }}>
            <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M21.5 4.5L2.5 12l5.5 2 2 6 3-4 5 4 3.5-15.5z"/></svg>
            <span>GABUNG VIP GRATIS SEKARANG</span>
          </span>
        </a>
        <div className="trust">
          <span>100% Gratis</span>
          <span>Bisa keluar kapan saja</span>
          <span>Tanpa deposit</span>
        </div>
      </Reveal>
    </section>
  );
}

/* ------------------------------------------------------------------ */
/*  Footer                                                            */
/* ------------------------------------------------------------------ */
function Footer() {
  return (
    <footer className="footer" data-screen-label="Footer">
      <div className="footer-row">
        <div className="nav-logo" style={{ width: 32, height: 32 }}><img src={LOGO} alt="" /></div>
        <div className="copy">© 2018 — 2026 Borneo Capital</div>
      </div>
      <div className="legal">
        Trading mengandung risiko. Past performance tidak menjamin hasil di masa depan.
        Lakukan riset sendiri dan kelola risiko dengan bijak.
      </div>
      <div className="socials">
        <a href={TG_URL} target="_blank" rel="noopener noreferrer" aria-label="Telegram">
          <svg width="22" height="22" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
            <path d="M21.5 4.5L2.5 12l5.5 2 2 6 3-4 5 4 3.5-15.5z"/>
          </svg>
        </a>
      </div>
    </footer>
  );
}

/* ------------------------------------------------------------------ */
/*  App                                                               */
/* ------------------------------------------------------------------ */
function App() {
  const [loaded, setLoaded] = useState(false);
  useEffect(() => {
    const t = setTimeout(() => setLoaded(true), 2600);
    return () => clearTimeout(t);
  }, []);

  return (
    <>
      <LoadingScreen done={loaded} />
      <Navbar />
      <Hero />
      <PartnerMarquee />
      <Stats />
      <Narrative />
      <Team />
      <TutorialHfm />
      <PnlGallery />
      <CtaSection />
      <Footer />
    </>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
