/* global React */
const { useState, useEffect, useRef } = React;
const { Arrow, Check } = window.RivalIcons;

// ============ Hero variant A: Live payment receipt ============
function HeroReceipt() {
  const [tick, setTick] = useState(0);
  useEffect(() => {
    const id = setInterval(() => setTick(t => t + 1), 2200);
    return () => clearInterval(id);
  }, []);

  // States: 0 input, 1 routing, 2 captured, 3 settled
  const phase = tick % 4;
  const amount = "AED 12,480.00";
  const rails = ["Visa", "Mastercard", "Apple Pay", "Mada", "Tabby", "Bank transfer"];
  const rail = rails[tick % rails.length];

  return (
    <div className="hero-payment" style={styles.wrap}>
      <div style={styles.card}>
        <div style={styles.cardHead}>
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <span style={styles.dot}></span>
            <span style={styles.cardHeadLabel}>Live transaction</span>
          </div>
          <span className="t-mono" style={{ color: "var(--text-3)" }}>txn_8f2a91</span>
        </div>

        <div style={styles.amountRow}>
          <div style={styles.amountLabel}>Charge</div>
          <div style={styles.amount} className="t-num">{amount}</div>
        </div>

        <div style={styles.steps}>
          <Step n={1} label="Customer pays via" detail={rail} state={phase >= 0 ? "done" : "pending"} />
          <Step n={2} label="Route via Rival" detail="3 acquirers compared · 14ms" state={phase >= 1 ? "done" : phase === 0 ? "active" : "pending"} />
          <Step n={3} label="Captured" detail="ENBD · acquirer A" state={phase >= 2 ? "done" : phase === 1 ? "active" : "pending"} />
          <Step n={4} label="Settled to your account" detail="T+1 · AED" state={phase >= 3 ? "done" : phase === 2 ? "active" : "pending"} last />
        </div>

        <div style={styles.cardFoot}>
          <div style={styles.footMetric}>
            <div style={styles.footLabel}>Auth rate</div>
            <div style={styles.footValue} className="t-num">98.6%</div>
          </div>
          <div style={styles.footDiv}/>
          <div style={styles.footMetric}>
            <div style={styles.footLabel}>p50 latency</div>
            <div style={styles.footValue} className="t-num">142<span style={{ color: "var(--text-3)", fontSize: 12, marginLeft: 4 }}>ms</span></div>
          </div>
          <div style={styles.footDiv}/>
          <div style={styles.footMetric}>
            <div style={styles.footLabel}>Cost</div>
            <div style={styles.footValue} className="t-num">−18<span style={{ color: "var(--text-3)", fontSize: 12, marginLeft: 4 }}>bps</span></div>
          </div>
        </div>
      </div>

      <div style={styles.float1}>
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <svg width="14" height="14" viewBox="0 0 16 16" fill="none">
            <circle cx="8" cy="8" r="7" stroke="var(--success)" strokeWidth="1.5"/>
            <path d="M5 8 7 10 11 6" stroke="var(--success)" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
          <span style={{ fontSize: 12, fontWeight: 500 }}>Settled to ENBD ****4421</span>
        </div>
        <div style={{ fontSize: 11, color: "var(--text-3)", marginTop: 4 }}>2 min ago · AED 12,480.00</div>
      </div>

      <div style={styles.float2}>
        <div style={{ fontSize: 10, color: "var(--text-3)", letterSpacing: "0.1em", textTransform: "uppercase", marginBottom: 6 }}>Routing decision</div>
        <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
          <RouteLine name="ENBD" rate="98.6%" winner />
          <RouteLine name="ADCB" rate="97.1%" />
          <RouteLine name="Mashreq" rate="95.8%" />
        </div>
      </div>
    </div>
  );
}

function Step({ n, label, detail, state, last }) {
  const isDone = state === "done";
  const isActive = state === "active";
  const color = isDone ? "var(--success)" : isActive ? "var(--accent)" : "var(--text-4)";
  return (
    <div style={{ display: "flex", gap: 14, position: "relative", paddingBottom: last ? 0 : 18 }}>
      <div style={{ position: "relative" }}>
        <div style={{
          width: 24, height: 24, borderRadius: "50%",
          border: `1.5px solid ${color}`,
          background: isDone ? color : "transparent",
          color: isDone ? "white" : color,
          display: "flex", alignItems: "center", justifyContent: "center",
          fontSize: 11, fontWeight: 600,
          transition: "all 240ms ease",
          flexShrink: 0,
        }}>
          {isDone ? <Check/> : isActive ? <span style={{ width: 6, height: 6, background: "var(--accent)", borderRadius: "50%", animation: "pulse 1.4s infinite" }}/> : n}
        </div>
        {!last && (
          <div style={{ position: "absolute", left: "50%", top: 24, bottom: -18, width: 1.5, background: "var(--line)", transform: "translateX(-50%)" }}/>
        )}
      </div>
      <div style={{ paddingTop: 2, minWidth: 0, flex: 1 }}>
        <div style={{ fontSize: 13, color: "var(--text)", fontWeight: 500 }}>{label}</div>
        <div style={{ fontSize: 12, color: "var(--text-3)", marginTop: 2 }}>{detail}</div>
      </div>
    </div>
  );
}

function RouteLine({ name, rate, winner }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 11 }}>
      <span style={{ width: 6, height: 6, borderRadius: "50%", background: winner ? "var(--accent)" : "var(--text-4)" }}/>
      <span style={{ color: winner ? "var(--text)" : "var(--text-3)", fontWeight: winner ? 500 : 400, flex: 1 }}>{name}</span>
      <span className="t-num" style={{ color: winner ? "var(--text)" : "var(--text-3)" }}>{rate}</span>
    </div>
  );
}

const styles = {
  wrap: { position: "relative", width: "100%", maxWidth: 520, marginInline: "auto" },
  card: {
    background: "var(--ink-800)",
    border: "1px solid var(--line-2)",
    borderRadius: "var(--r-xl)",
    padding: 28,
    boxShadow: "0 30px 80px rgba(0,0,0,0.4), 0 0 0 1px rgba(255,255,255,0.02) inset",
  },
  cardHead: {
    display: "flex", justifyContent: "space-between", alignItems: "center",
    paddingBottom: 18, borderBottom: "1px solid var(--line)", marginBottom: 22,
  },
  dot: { width: 8, height: 8, borderRadius: "50%", background: "var(--success)", boxShadow: "0 0 12px var(--success)", animation: "pulse 1.8s ease-in-out infinite" },
  cardHeadLabel: { fontSize: 12, fontWeight: 500, color: "var(--text-2)", letterSpacing: "0.04em", textTransform: "uppercase" },
  amountRow: { display: "flex", flexDirection: "column", gap: 6, marginBottom: 28 },
  amountLabel: { fontSize: 12, color: "var(--text-3)", letterSpacing: "0.08em", textTransform: "uppercase" },
  amount: { fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 40, lineHeight: 1, letterSpacing: "-0.025em" },
  steps: { display: "flex", flexDirection: "column" },
  cardFoot: {
    display: "flex", alignItems: "center", marginTop: 24, paddingTop: 20,
    borderTop: "1px solid var(--line)", gap: 0,
  },
  footMetric: { flex: 1, display: "flex", flexDirection: "column", gap: 4 },
  footLabel: { fontSize: 11, color: "var(--text-3)", letterSpacing: "0.06em", textTransform: "uppercase" },
  footValue: { fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 18, letterSpacing: "-0.01em" },
  footDiv: { width: 1, alignSelf: "stretch", background: "var(--line)" },
  float1: {
    position: "absolute", left: -32, bottom: 40, padding: "12px 16px",
    background: "var(--ink-700)", border: "1px solid var(--line-2)", borderRadius: 12,
    fontFamily: "var(--font-body)", color: "var(--text)",
    boxShadow: "0 20px 40px rgba(0,0,0,0.4)",
    minWidth: 220,
    backdropFilter: "blur(8px)",
  },
  float2: {
    position: "absolute", right: -40, top: 60, padding: "14px 16px",
    background: "var(--ink-700)", border: "1px solid var(--line-2)", borderRadius: 12,
    boxShadow: "0 20px 40px rgba(0,0,0,0.4)",
    minWidth: 180,
  },
};

// ============ Hero variant B: Counter dashboard ============
function HeroDashboard() {
  const [vol, setVol] = useState(2840221);
  const [txn, setTxn] = useState(184392);
  useEffect(() => {
    const id = setInterval(() => {
      setVol(v => v + Math.floor(50 + Math.random() * 800));
      setTxn(t => t + Math.floor(Math.random() * 3) + 1);
    }, 800);
    return () => clearInterval(id);
  }, []);

  return (
    <div className="hero-dash" style={{ position: "relative", width: "100%", maxWidth: 540, marginInline: "auto" }}>
      <div style={styles.card}>
        <div style={styles.cardHead}>
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <span style={styles.dot}></span>
            <span style={styles.cardHeadLabel}>Live across the platform</span>
          </div>
          <span style={{ fontSize: 12, color: "var(--text-3)" }}>Last 24h</span>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 24, marginBottom: 28 }}>
          <div>
            <div style={styles.amountLabel}>Volume</div>
            <div style={{ ...styles.amount, fontSize: 34 }} className="t-num">${(vol/1000).toLocaleString(undefined, { maximumFractionDigits: 0 })}K</div>
          </div>
          <div>
            <div style={styles.amountLabel}>Transactions</div>
            <div style={{ ...styles.amount, fontSize: 34 }} className="t-num">{txn.toLocaleString()}</div>
          </div>
        </div>

        <Spark />

        <div style={styles.cardFoot}>
          <div style={styles.footMetric}>
            <div style={styles.footLabel}>Auth rate</div>
            <div style={styles.footValue} className="t-num">98.6%</div>
          </div>
          <div style={styles.footDiv}/>
          <div style={styles.footMetric}>
            <div style={styles.footLabel}>p50</div>
            <div style={styles.footValue} className="t-num">142ms</div>
          </div>
          <div style={styles.footDiv}/>
          <div style={styles.footMetric}>
            <div style={styles.footLabel}>Uptime</div>
            <div style={styles.footValue} className="t-num">99.99%</div>
          </div>
        </div>
      </div>
    </div>
  );
}

function Spark() {
  const points = [];
  let y = 50;
  for (let i = 0; i <= 60; i++) {
    y += (Math.random() - 0.5) * 8;
    y = Math.max(20, Math.min(80, y));
    points.push([i * (480/60), y]);
  }
  const d = points.map((p,i) => (i === 0 ? "M" : "L") + p[0] + " " + p[1]).join(" ");
  const area = d + ` L 480 100 L 0 100 Z`;
  return (
    <svg viewBox="0 0 480 100" style={{ width: "100%", height: 100, marginBottom: 4 }} preserveAspectRatio="none">
      <defs>
        <linearGradient id="sg" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0" stopColor="var(--accent)" stopOpacity="0.35"/>
          <stop offset="1" stopColor="var(--accent)" stopOpacity="0"/>
        </linearGradient>
      </defs>
      <path d={area} fill="url(#sg)"/>
      <path d={d} stroke="var(--accent)" strokeWidth="1.5" fill="none"/>
    </svg>
  );
}

window.RivalHeroReceipt = HeroReceipt;
window.RivalHeroDashboard = HeroDashboard;
