import { ArrowRight, MessageCircle, PlayCircle, Sparkles, TrendingUp, TrendingDown } from "lucide-react";
import { useEffect, useState } from "react";
import hero from "@/assets/hero-mentor.jpg";

type Ticker = { price: number; changePct: number };

export function Hero() {
  const [btc, setBtc] = useState<Ticker>({ price: 67842.5, changePct: 2.41 });
  const [xau, setXau] = useState<Ticker>({ price: 2650.0, changePct: 0.42 });

  useEffect(() => {
    let cancelled = false;

    const fetchBtc = async () => {
      try {
        const res = await fetch(
          "https://api.bybit.com/v5/market/tickers?category=spot&symbol=BTCUSDT",
          { cache: "no-store" }
        );
        const json = await res.json();
        const t = json?.result?.list?.[0];
        if (!cancelled && t) {
          setBtc({
            price: parseFloat(t.lastPrice),
            changePct: parseFloat(t.price24hPcnt) * 100,
          });
        }
      } catch {
        /* keep last */
      }
    };

    const fetchXau = async () => {
      try {
        const res = await fetch("https://api.gold-api.com/price/XAU", {
          cache: "no-store",
        });
        const json = await res.json();
        if (!cancelled && json?.price) {
          const price = Number(json.price);
          // change vs cached price from ~24h ago
          const key = "xau-prev-24h";
          const raw = typeof window !== "undefined" ? localStorage.getItem(key) : null;
          let changePct = 0;
          const now = Date.now();
          if (raw) {
            const { p, t } = JSON.parse(raw);
            if (p && now - t < 36 * 60 * 60 * 1000) {
              changePct = ((price - p) / p) * 100;
            } else {
              localStorage.setItem(key, JSON.stringify({ p: price, t: now }));
            }
          } else if (typeof window !== "undefined") {
            localStorage.setItem(key, JSON.stringify({ p: price, t: now }));
          }
          setXau({ price, changePct });
        }
      } catch {
        /* keep last */
      }
    };

    fetchBtc();
    fetchXau();
    const id = setInterval(() => {
      fetchBtc();
      fetchXau();
    }, 60 * 60 * 1000); // hourly
    return () => {
      cancelled = true;
      clearInterval(id);
    };
  }, []);

  const btcUp = btc.changePct >= 0;
  const xauUp = xau.changePct >= 0;

  return (
    <section id="top" className="relative overflow-hidden">
      <div className="absolute inset-0 grid-pattern opacity-40 [mask-image:radial-gradient(ellipse_at_center,black,transparent_70%)]" />
      <div className="absolute -top-32 -right-32 h-96 w-96 rounded-full bg-gradient-primary opacity-20 blur-3xl animate-[float_8s_ease-in-out_infinite]" />
      <div className="absolute -bottom-32 -left-32 h-96 w-96 rounded-full bg-[color:var(--gold)] opacity-15 blur-3xl animate-[float_10s_ease-in-out_infinite]" />

      <div className="relative mx-auto grid max-w-7xl items-center gap-12 px-4 py-14 md:grid-cols-2 md:px-8 md:py-24">
        <div data-aos="fade-right">
          <div className="inline-flex items-center gap-2 rounded-full border border-primary/30 bg-primary/10 px-4 py-1.5 text-xs font-semibold text-primary backdrop-blur">
            <Sparkles className="h-3.5 w-3.5" />
            LEARN. ANALYZE. TRADE. GROW.
          </div>
          <h1 className="mt-6 text-[2.6rem] font-bold leading-[1.02] md:text-7xl">
            Learn{" "}
            <span className="relative inline-block">
              <span className="text-gradient-primary">Share Market</span>
              <svg className="absolute -bottom-2 left-0 w-full" viewBox="0 0 200 8" fill="none" preserveAspectRatio="none">
                <path d="M2 5 Q100 -2 198 5" stroke="url(#u)" strokeWidth="3" strokeLinecap="round" />
                <defs>
                  <linearGradient id="u" x1="0" x2="1">
                    <stop offset="0" stopColor="oklch(0.7 0.2 150)" />
                    <stop offset="1" stopColor="oklch(0.62 0.21 165)" />
                  </linearGradient>
                </defs>
              </svg>
            </span>
            <br />
            Crypto & Forex Like a <span className="text-gradient-navy">Pro</span>
          </h1>
          <p className="mt-6 max-w-xl text-base text-muted-foreground md:text-lg leading-relaxed">
            Live mentorship, practical learning & real market analysis — all in one place.
            <span className="block mt-1 font-medium text-foreground">Smarter you, stronger tomorrow.</span>
          </p>
          <div className="mt-8 flex flex-wrap gap-3">
            <a href="#courses" className="group relative inline-flex items-center gap-2 overflow-hidden rounded-full bg-gradient-primary px-7 py-4 text-sm font-bold text-primary-foreground shadow-glow transition-all hover:scale-105 hover-bounce animate-[pulse-glow_2.5s_ease-in-out_infinite]">
              <span className="relative z-10 flex items-center gap-2">
                Join Now <ArrowRight className="h-4 w-4 transition-transform group-hover:translate-x-1" />
              </span>
            </a>
            <a href="#courses" className="inline-flex items-center gap-2 rounded-full border border-border bg-surface-elevated px-7 py-4 text-sm font-bold text-foreground transition-all hover:border-primary/40 hover:scale-105 hover-bounce shadow-card">
              <PlayCircle className="h-4 w-4 text-primary" /> View Courses
            </a>
            <a href="https://chat.whatsapp.com/LgHUxIFP8rPEgoQ2aJmVzR?mlu=4&s=cl&p=a" target="_blank" rel="noreferrer" className="inline-flex items-center gap-2 rounded-full border border-primary/40 bg-primary/10 px-7 py-4 text-sm font-bold text-primary transition-all hover:bg-primary/20 hover:scale-105 hover-bounce">
              <MessageCircle className="h-4 w-4" /> Join Free WhatsApp Group
            </a>
            <a href="https://wa.me/917029490341" target="_blank" rel="noreferrer" className="inline-flex items-center gap-2 rounded-full border border-border bg-surface-elevated px-7 py-4 text-sm font-bold text-foreground transition-all hover:border-primary/40 hover:scale-105 hover-bounce shadow-card">
              <MessageCircle className="h-4 w-4 text-primary" /> Chat on WhatsApp
            </a>
          </div>
          <div className="mt-10 grid grid-cols-3 gap-3 max-w-md">
            {[
              { k: "5000+", v: "Students" },
              { k: "4.9★", v: "Rated" },
              { k: "24/7", v: "Support" },
            ].map((s, i) => (
              <div
                key={s.v}
                className="rounded-2xl border border-border bg-surface-elevated p-4 text-center shadow-card transition-all hover:-translate-y-1 hover:shadow-glow hover:border-primary/40"
                style={{ animation: `fade-up 0.8s ease-out ${0.3 + i * 0.1}s both` }}
              >
                <div className="text-2xl font-bold text-gradient-primary">{s.k}</div>
                <div className="mt-1 text-[10px] uppercase tracking-widest text-muted-foreground">{s.v}</div>
              </div>
            ))}
          </div>
        </div>

        <div className="relative" data-aos="zoom-in" data-aos-delay="200">
          <div className="absolute -inset-8 bg-gradient-mesh blur-3xl opacity-70" />
          <div className="relative overflow-hidden rounded-3xl border border-border shadow-soft">
            <img src={hero} alt="Live trading mentor teaching students" width={1280} height={1280} className="h-full w-full object-cover" />
          </div>

          {/* Live trade card — BTCUSDT (updates hourly via Bybit) */}
          <div className="absolute -right-3 -top-4 md:-right-6 rounded-2xl glass p-4 shadow-soft animate-[float_6s_ease-in-out_infinite]">
            <div className="flex items-center gap-3">
              <div className={`flex h-10 w-10 items-center justify-center rounded-xl ${btcUp ? "bg-primary/15 text-primary" : "bg-destructive/15 text-destructive"}`}>
                {btcUp ? <TrendingUp className="h-5 w-5" /> : <TrendingDown className="h-5 w-5" />}
              </div>
              <div>
                <div className="text-[10px] uppercase tracking-wider text-muted-foreground">BTCUSDT</div>
                <div className="text-base font-bold text-foreground">
                  ${btc.price.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
                </div>
                <div className={`text-xs font-semibold ${btcUp ? "text-primary" : "text-destructive"}`}>
                  {btcUp ? "+" : ""}{btc.changePct.toFixed(2)}% {btcUp ? "▲" : "▼"}
                </div>
              </div>
            </div>
          </div>

          {/* Live trade card — XAUUSD (Gold, hourly) */}
          <div className="absolute -left-3 -bottom-4 md:-left-6 rounded-2xl glass p-4 shadow-soft animate-[float_7s_ease-in-out_infinite]">
            <div className="flex items-center gap-3">
              <div className={`flex h-10 w-10 items-center justify-center rounded-xl ${xauUp ? "bg-primary/15 text-primary" : "bg-destructive/15 text-destructive"}`}>
                {xauUp ? <TrendingUp className="h-5 w-5" /> : <TrendingDown className="h-5 w-5" />}
              </div>
              <div>
                <div className="text-[10px] uppercase tracking-wider text-muted-foreground">XAUUSD</div>
                <div className="text-base font-bold text-foreground">
                  ${xau.price.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
                </div>
                <div className={`text-xs font-semibold ${xauUp ? "text-primary" : "text-destructive"}`}>
                  {xauUp ? "+" : ""}{xau.changePct.toFixed(2)}% {xauUp ? "▲" : "▼"}
                </div>
              </div>
            </div>
          </div>

          {/* Live badge */}
          <div className="absolute right-4 bottom-4 inline-flex items-center gap-1.5 rounded-full bg-destructive/95 px-3 py-1 text-[10px] font-bold uppercase tracking-wider text-white shadow-soft">
            <span className="h-1.5 w-1.5 rounded-full bg-white animate-pulse" /> Live Now
          </div>
        </div>
      </div>

      {/* Marquee */}
      <div className="relative border-y border-border bg-surface-elevated/50 backdrop-blur py-4 overflow-hidden">
        <div className="flex animate-[marquee_30s_linear_infinite] whitespace-nowrap">
          {[...Array(2)].map((_, j) => (
            <div key={j} className="flex shrink-0 items-center gap-12 px-6 text-sm font-semibold text-muted-foreground">
              {["📈 Live Market Sessions", "🎯 Smart Money Concepts", "🛡️ Risk Management", "🌍 Bengali + Hindi + English", "💼 Funding Account Support", "⚡ Daily Trade Setups", "👥 Community of 5000+"].map((t) => (
                <span key={t} className="flex items-center gap-12">
                  <span>{t}</span>
                  <span className="text-primary">•</span>
                </span>
              ))}
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}
