const { useState, useEffect, useRef } = React;

/* ---- Animated counter: counts from 0 to target when visible ---- */
function Counter({ value, prefix = "", suffix = "", decimals = 0, duration = 1400 }) {
  const ref = useRef(null);
  const [n, setN] = useState(0);
  const started = useRef(false);

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

  const display = n.toFixed(decimals);
  return (
    <span ref={ref} className="counter">
      {prefix}{display}{suffix}
    </span>
  );
}

/* Counter with comma grouping */
function FormattedCounter({ value, suffix = "", duration = 1600 }) {
  const ref = useRef(null);
  const [n, setN] = useState(0);
  const started = useRef(false);
  useEffect(() => {
    if (!ref.current) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => {
        if (e.isIntersecting && !started.current) {
          started.current = true;
          const start = performance.now();
          const tick = (t) => {
            const p = Math.min(1, (t - start) / duration);
            const eased = 1 - Math.pow(1 - p, 3);
            setN(Math.round(value * eased));
            if (p < 1) requestAnimationFrame(tick);
          };
          requestAnimationFrame(tick);
        }
      });
    }, { threshold: 0.3 });
    io.observe(ref.current);
    return () => io.disconnect();
  }, [value, duration]);
  return <span ref={ref} className="counter">{n.toLocaleString("en-US")}{suffix}</span>;
}

/* ---- Split headline into word spans with stagger ---- */
function StaggerHeadline({ children, className, style }) {
  // Accept React children that may include <br/> and <span>accent</span>
  // Walk the tree, wrap text words in <span class="word"> with animation-delay
  let idx = 0;
  const wrap = (node) => {
    if (typeof node === "string") {
      const parts = node.split(/(\s+)/);
      return parts.map((p, i) => {
        if (/^\s+$/.test(p)) return <span key={"s" + idx + i}>{p}</span>;
        if (p === "") return null;
        const delay = (idx++ * 0.06).toFixed(2);
        return (
          <span key={"w" + idx + i} className="word" style={{ animationDelay: delay + "s" }}>
            {p}
          </span>
        );
      });
    }
    if (Array.isArray(node)) return node.map(wrap);
    if (React.isValidElement(node)) {
      if (node.type === "br") return node;
      return React.cloneElement(node, {}, wrap(node.props.children));
    }
    return node;
  };

  return (
    <h1 className={(className || "") + " headline-stagger"} style={style}>
      {wrap(children)}
    </h1>
  );
}

/* ---- Live payment feed (hero product visual) ---- */
function LivePayments() {
  const seed = [
    { amt: "$248.00", biz: "Peptide Labs Co", card: "VISA · 4242", status: "Settled", time: "just now" },
    { amt: "$89.50", biz: "Nova Supplements", card: "MC · 5100", status: "Authorized", time: "2s ago" },
    { amt: "$1,420.00", biz: "Helios Telehealth", card: "AMEX · 3782", status: "Settled", time: "7s ago" },
    { amt: "$45.00", biz: "Coastal CBD", card: "VISA · 4000", status: "Captured", time: "12s ago" },
    { amt: "$312.75", biz: "Northbound Nutra", card: "DISC · 6011", status: "Settled", time: "18s ago" },
    { amt: "$76.00", biz: "Aurora MedSpa", card: "VISA · 4417", status: "Authorized", time: "24s ago" },
    { amt: "$920.40", biz: "Forge Coaching", card: "MC · 5555", status: "Settled", time: "33s ago" },
  ];
  const [rows, setRows] = useState(seed);

  useEffect(() => {
    const t = setInterval(() => {
      setRows(prev => {
        const cents = (Math.random() * 500 + 20).toFixed(2);
        const amt = "$" + cents;
        const biz = prev[(Math.floor(Math.random() * prev.length))].biz;
        const cards = ["VISA · 4242", "MC · 5100", "AMEX · 3782", "DISC · 6011", "VISA · 4417"];
        const card = cards[Math.floor(Math.random() * cards.length)];
        const statuses = ["Authorized", "Settled", "Captured"];
        const status = statuses[Math.floor(Math.random() * statuses.length)];
        const next = [{ amt, biz, card, status, time: "just now" }, ...prev.slice(0, 6)];
        return next;
      });
    }, 2200);
    return () => clearInterval(t);
  }, []);

  const statusColor = (s) => s === "Authorized" ? "var(--gold)" : s === "Captured" ? "var(--accent-light)" : "#87d37c";

  return (
    <div className="live-payments" style={{
      background: "linear-gradient(180deg, var(--surface) 0%, #0c0c0e 100%)",
      border: "1px solid var(--border)",
      borderRadius: 14,
      padding: "1.1rem 1.15rem",
      boxShadow: "0 40px 80px -40px rgba(0,0,0,.8), 0 0 0 1px rgba(242,122,26,0.05) inset",
    }}>
      {/* Header */}
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", paddingBottom: ".8rem", borderBottom: "1px solid var(--border)" }}>
        <div style={{ display: "flex", alignItems: "center", gap: ".55rem" }}>
          <span style={{
            width: 8, height: 8, borderRadius: "50%", background: "#87d37c",
            boxShadow: "0 0 10px #87d37c"
          }}/>
          <span style={{ fontSize: ".72rem", fontWeight: 700, color: "var(--white)", letterSpacing: ".06em", textTransform: "uppercase" }}>
            Dashboard Preview
          </span>
          <span style={{
            fontSize: ".58rem", fontWeight: 700, color: "var(--muted)",
            letterSpacing: ".08em", textTransform: "uppercase",
            padding: ".18rem .45rem", borderRadius: 4,
            border: "1px solid var(--border)", background: "rgba(255,255,255,0.02)",
            marginLeft: ".4rem",
          }}>Sample data</span>
        </div>
        <span style={{ fontSize: ".68rem", fontFamily: "var(--font-mono)", color: "var(--muted)" }}>
          asherpay.com/demo
        </span>
      </div>

      {/* Rows */}
      <div className="live-rows" style={{ padding: ".45rem 0", display: "grid", gap: ".1rem", minHeight: 320 }}>
        {rows.map((r, i) => (
          <div key={r.biz + i}
               className="live-row"
               style={{
                 display: "grid",
                 gridTemplateColumns: "1.4fr 1.2fr auto auto",
                 alignItems: "center",
                 gap: ".9rem",
                 padding: ".7rem .15rem",
                 borderBottom: "1px solid rgba(255,255,255,0.04)",
                 opacity: i === 0 ? 1 : 0.95 - (i * 0.06),
                 animation: i === 0 ? "rowIn .4s ease" : "none",
               }}>
            <div className="live-biz">
              <div style={{ fontSize: ".84rem", color: "var(--white)", fontWeight: 600 }}>{r.biz}</div>
              <div style={{ fontSize: ".66rem", color: "var(--muted)", marginTop: ".15rem", fontFamily: "var(--font-mono)" }}>{r.card}</div>
            </div>
            <div className="live-time" style={{ fontSize: ".66rem", color: "var(--muted)", textTransform: "uppercase", letterSpacing: ".06em" }}>
              {r.time}
            </div>
            <div className="live-status" style={{
              fontSize: ".66rem", fontWeight: 700,
              color: statusColor(r.status),
              textTransform: "uppercase",
              letterSpacing: ".05em",
              padding: ".2rem .5rem",
              borderRadius: 999,
              background: "rgba(255,255,255,0.03)",
              border: "1px solid rgba(255,255,255,0.06)",
              whiteSpace: "nowrap"
            }}>{r.status}</div>
            <div className="live-amt" style={{ fontFamily: "var(--font-mono)", fontSize: ".92rem", color: "var(--white)", fontWeight: 700, textAlign: "right", minWidth: 90 }}>{r.amt}</div>
          </div>
        ))}
      </div>

      {/* Footer summary */}
      <div style={{
        display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 0,
        borderTop: "1px solid var(--border)", paddingTop: ".9rem", marginTop: ".2rem",
      }}>
        {[
          { lbl: "Vol today", val: "$4.82M" },
          { lbl: "Approvals", val: "98.6%" },
          { lbl: "Chargebacks", val: "0.24%" },
        ].map((m, idx) => (
          <div key={m.lbl} style={{
            padding: "0 .9rem",
            borderLeft: idx === 0 ? "none" : "1px solid var(--border)",
            textAlign: idx === 0 ? "left" : "center",
          }}>
            <div style={{ fontSize: ".62rem", color: "var(--muted)", textTransform: "uppercase", letterSpacing: ".08em", fontWeight: 600 }}>{m.lbl}</div>
            <div style={{ fontSize: "1.05rem", fontFamily: "var(--font-mono)", fontWeight: 700, color: "var(--white)", marginTop: ".2rem" }}>{m.val}</div>
          </div>
        ))}
      </div>

      <style>{`
        @keyframes rowIn {
          from { opacity: 0; transform: translateX(-8px); background: rgba(242,122,26,0.08); }
          to   { opacity: 1; transform: none; background: transparent; }
        }
      `}</style>
    </div>
  );
}

function Hero({ layout }) {
  // layout: "split" | "center" | "dashboard"
  return (
    <section className="section" id="top" style={{ padding: "4.5rem 0 4rem" }}>
      <div className="container">
        {layout === "center" ? (
          <div style={{ textAlign: "center", maxWidth: 900, margin: "0 auto" }}>
            <div style={{
              display: "inline-flex", alignItems: "center", gap: ".45rem",
              fontSize: ".72rem", fontWeight: 700, color: "var(--gold)",
              textShadow: "0 0 12px var(--gold-glow)",
              letterSpacing: ".06em", textTransform: "uppercase",
              padding: ".4rem .9rem",
              border: "1px solid rgba(255,215,0,.35)",
              background: "rgba(255,215,0,.05)",
              borderRadius: 999,
              marginBottom: "1.4rem",
            }}>
              <span style={{ width: 6, height: 6, borderRadius: "50%", background: "var(--gold)", boxShadow: "0 0 8px var(--gold-glow)" }}/>
              Start processing in 5 days
            </div>
            <h1 className="display-xl" style={{ marginBottom: "1.1rem" }}>
              Payment processing<br/><span>built for growth.</span>
            </h1>
            <p className="lede" style={{ margin: "0 auto 2rem", fontSize: "1.08rem" }}>
              AsherPay turns high-risk headaches into reliable revenue. Low reserves, competitive rates, and the full stack — fraud tools, analytics, recurring billing, and APIs — from one dedicated team.
            </p>
            <div style={{ display: "flex", gap: ".7rem", justifyContent: "center", flexWrap: "wrap" }}>
              <a href="https://payments.asherpay.com" className="btn btn-primary">
                Get Processing →
              </a>
              <a href="#how" className="btn btn-ghost">See how it works</a>
            </div>
          </div>
        ) : layout === "dashboard" ? (
          <>
            <div style={{ textAlign: "center", maxWidth: 820, margin: "0 auto 3rem" }}>
              <div className="tag" style={{ justifyContent: "center" }}>
                <span className="tag-dot"/> Premium payment infrastructure
              </div>
              <h1 className="display-xl">
                Every transaction. <span>One platform.</span>
              </h1>
              <p className="lede" style={{ margin: ".9rem auto 0" }}>
                Accept payments, manage risk, and settle funds through the platform that won't freeze your MID.
              </p>
            </div>
            <div style={{ maxWidth: 900, margin: "0 auto" }}>
              <LivePayments />
            </div>
            <div style={{ display: "flex", gap: ".7rem", justifyContent: "center", flexWrap: "wrap", marginTop: "2.2rem" }}>
              <a href="https://payments.asherpay.com" className="btn btn-primary">Get Processing →</a>
              <a href="#developers" className="btn btn-ghost">Read the docs</a>
            </div>
          </>
        ) : (
          /* split */
          <div style={{
            display: "grid", gridTemplateColumns: "1.05fr .95fr",
            alignItems: "center", gap: "3.2rem",
          }} className="hero-grid">
            <div>
              <div className="tag">
                <span className="tag-dot"/> High-risk merchant processing
              </div>
              <StaggerHeadline className="display-xl" style={{ marginBottom: "1rem" }}>
                Built for modern<br/><span>payment operations.</span>
              </StaggerHeadline>
              <p className="lede" style={{ marginBottom: "1.2rem" }}>
                Accept payments, manage risk, and settle funds through one platform engineered for speed, reliability, and control — even in the verticals other processors decline.
              </p>
              <div style={{
                fontSize: ".88rem", fontWeight: 600, color: "var(--gold)",
                letterSpacing: ".04em",
                textShadow: "0 0 12px var(--gold-glow), 0 0 24px rgba(255,215,0,.25)",
                marginBottom: "1.6rem",
              }}>
                Start processing in 5 days
              </div>
              <div className="hero-buttons" style={{ display: "flex", gap: ".7rem", flexWrap: "wrap" }}>
                <a href="https://payments.asherpay.com" className="btn btn-primary">
                  Get Processing
                  <svg width="12" height="12" viewBox="0 0 12 12" fill="none" aria-hidden="true">
                    <path d="M2 6h8m-3-3 3 3-3 3" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"/>
                  </svg>
                </a>
                <a href="#how" className="btn btn-ghost">How it works</a>
              </div>

              {/* Micro-stat strip */}
              <div className="hero-stats" style={{
                display: "grid", gridTemplateColumns: "repeat(3,auto)",
                gap: "2rem", marginTop: "3rem", justifyContent: "start",
              }}>
                {[
                  { val: 2.4, prefix: "$", suffix: "B+", decimals: 1, l: "Annual volume" },
                  { val: 12000, prefix: "", suffix: "+", decimals: 0, l: "Merchants", commas: true },
                  { val: 99.99, prefix: "", suffix: "%", decimals: 2, l: "Platform uptime" },
                ].map(s => (
                  <div key={s.l}>
                    <div style={{ fontSize: "1.4rem", fontWeight: 900, color: "var(--white)", letterSpacing: "-0.02em" }}>
                      {s.commas ? (
                        <FormattedCounter value={s.val} suffix={s.suffix}/>
                      ) : (
                        <Counter value={s.val} prefix={s.prefix} suffix={s.suffix} decimals={s.decimals}/>
                      )}
                    </div>
                    <div style={{ fontSize: ".66rem", color: "var(--muted)", textTransform: "uppercase", letterSpacing: ".08em", marginTop: ".2rem", fontWeight: 600 }}>{s.l}</div>
                  </div>
                ))}
              </div>
            </div>

            <div className="hero-visual" style={{ position: "relative" }}>
              <LivePayments />
              {/* Floating corner badge */}
              <div className="live-badge" style={{
                position: "absolute",
                top: -14, right: -14,
                background: "var(--bg)",
                border: "1px solid var(--accent-border)",
                borderRadius: 10,
                padding: ".55rem .8rem",
                fontSize: ".68rem",
                fontWeight: 700,
                color: "var(--accent-light)",
                letterSpacing: ".08em",
                textTransform: "uppercase",
                boxShadow: "0 0 24px var(--accent-glow)"
              }}>
                ● LIVE
              </div>
            </div>
          </div>
        )}
      </div>

      <style>{`
        @media (max-width: 900px) {
          .hero-grid { grid-template-columns: 1fr !important; gap: 2.4rem !important; }
        }
      `}</style>
    </section>
  );
}

window.Hero = Hero;
window.LivePayments = LivePayments;
