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

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

/* Floating nav (same pill style) */
function HasilNav() {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 16);
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  return (
    <nav className={`nav ${scrolled ? "scrolled" : ""}`} data-screen-label="Navbar">
      <a href="index.html" 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">
        <li><a href="index.html">Beranda</a></li>
        <li><a href="index.html#team">Tim</a></li>
        <li><a href="index.html#tutorial" className="has-icon"><img src="assets/hfm-logo.jpg" alt="" />Tutorial HFM</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>
    </nav>
  );
}

/* Reveal-on-scroll */
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.12, 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>;
}

/* Counter (reused) */
function Counter({ to, duration = 1600, prefix = "", suffix = "" }) {
  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]);
  const n = Math.round(val).toLocaleString("en-US");
  return <span ref={ref}>{prefix}{n}{suffix}</span>;
}

/* Filters: derive from data + add Semua */
function classifyTag(t) {
  if (t.tag === "Whale") return "Whale";
  if (t.tagStyle === "swing") return "Swing";
  if (t.tagStyle === "scalp") return "Scalp";
  return "Daily";
}

function HasilPage() {
  const trades = window.TRADES;
  const [active, setActive] = useState(null);
  const [filter, setFilter] = useState("Semua");

  const groups = useMemo(() => {
    const counts = { Semua: trades.length, Daily: 0, Scalp: 0, Swing: 0 };
    trades.forEach((t) => { const k = classifyTag(t); if (counts[k] !== undefined) counts[k]++; });
    return counts;
  }, [trades]);

  const filtered = useMemo(() => {
    if (filter === "Semua") return trades;
    return trades.filter((t) => classifyTag(t) === filter);
  }, [filter, trades]);

  const idx = filtered.findIndex((t) => t === active);
  const onOpen = (t) => setActive(t);
  const onClose = () => setActive(null);
  const onPrev = idx > 0 ? () => setActive(filtered[idx - 1]) : null;
  const onNext = idx >= 0 && idx < filtered.length - 1 ? () => setActive(filtered[idx + 1]) : null;

  // aggregate stats
  const usdTotal = trades.reduce((acc, t) => {
    // skip IDR/cent rows for USD total
    if (String(t.amount).startsWith("+Rp")) return acc;
    return acc + (t.amountVal || 0);
  }, 0);

  return (
    <>
      <HasilNav />

      <section className="h-hero">
        <Reveal>
          <a href="index.html" className="back">
            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M19 12H5M12 19l-7-7 7-7"/></svg>
            Kembali ke Beranda
          </a>
        </Reveal>
        <Reveal child>
          <span className="eyebrow" style={{ marginBottom: 18 }}><span className="dot" />Daily Trades · Member</span>
          <h1 className="h-display" style={{ fontSize: "clamp(46px, 9vw, 96px)", lineHeight: 0.94 }}>
            Hasil <em>nyata</em> dari komunitas.
          </h1>
          <p className="section-sub" style={{ margin: "16px auto 0", textAlign: "center" }}>
            Screenshot PnL terkini dari member Borneo Capital. Diverifikasi, transparan, dan diupdate setiap hari.
          </p>
        </Reveal>

        <Reveal child className="h-stats-row">
          <div className="h-stat glass">
            <div className="l">Total Profit (USD)</div>
            <div className="v green">+<Counter to={Math.round(usdTotal)} prefix="$" /></div>
            <div className="meta">Akumulasi screenshot member · Mei 2026</div>
          </div>
          <div className="h-stat glass">
            <div className="l">Trade Tercatat</div>
            <div className="v"><Counter to={trades.length} suffix="" /></div>
            <div className="meta">Posisi closed dengan screenshot</div>
          </div>
          <div className="h-stat glass">
            <div className="l">Member Terdaftar</div>
            <div className="v"><Counter to={trades.length} /></div>
            <div className="meta">Trader aktif yang share hasil</div>
          </div>
          <div className="h-stat glass">
            <div className="l">Win Rate</div>
            <div className="v green">85.4<span style={{fontSize: "0.55em", marginLeft: 4, color: "var(--accent-2)"}}>%</span></div>
            <div className="meta">Bulan berjalan</div>
          </div>
        </Reveal>
      </section>

      <div className="filters">
        {["Semua", "Daily", "Scalp", "Swing"].map((f) => (
          <button key={f} className={`filter-chip ${filter === f ? "active" : ""}`} onClick={() => setFilter(f)}>
            {f}
            <span className="count">{groups[f]}</span>
          </button>
        ))}
      </div>

      <div className="h-grid">
        {filtered.map((t, i) => (
          <ReavealCard key={t.id + filter} delay={i * 60}>
            <TradeCard t={t} onOpen={onOpen} />
          </ReavealCard>
        ))}
      </div>

      {filtered.length === 0 && (
        <div className="h-empty">Belum ada trade di kategori ini.</div>
      )}

      {/* Re-use footer style from main page */}
      <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.
        </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>

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

/* Per-card reveal with stagger */
function ReavealCard({ children, delay = 0 }) {
  const ref = useRef(null);
  const [shown, setShown] = useState(false);
  useEffect(() => {
    const el = ref.current; if (!el) return;
    const obs = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting) {
          setTimeout(() => setShown(true), delay);
          obs.unobserve(el);
        }
      });
    }, { threshold: 0.08 });
    obs.observe(el);
    return () => obs.disconnect();
  }, [delay]);
  return (
    <div
      ref={ref}
      style={{
        opacity: shown ? 1 : 0,
        transform: shown ? "translateY(0)" : "translateY(24px)",
        transition: "opacity 0.7s cubic-bezier(.2,.7,.2,1), transform 0.7s cubic-bezier(.2,.7,.2,1)",
      }}
    >
      {children}
    </div>
  );
}

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