﻿import { useRef, useState, useEffect } from "react";
import { Link } from "@/lib/nextRouterAdapter";

const BRAND      = "#4A1429";
const GOLD       = "#D4B038";
const GOLD_DEEP  = "#B8963C";

const LEVEL_DEFS = [
  {
    name: "Beginner Founder", xp: "0 – 500 XP", icon: "🌱", num: 1,
    color: "#22C55E", darkColor: "#15803D", bg: "#F0FDF4", border: "#86EFAC",
    tagline: "Plant your first seed.",
    teaser: "What happens at this level?",
    reward: "+50 XP on your very first lesson",
    unlocks: [
      { icon: "📖", text: "First lesson access" },
      { icon: "📋", text: "10 starter templates" },
      { icon: "👥", text: "Community (read-only)" },
      { icon: "🏅", text: "Beginner badge" },
    ],
    challenge: "Complete your first lesson in the next 10 minutes",
    xpBar: 100,
  },
  {
    name: "Growing Founder", xp: "500 – 2k XP", icon: "📈", num: 2,
    color: GOLD, darkColor: GOLD_DEEP, bg: "#FFFBEB", border: "#FDE68A",
    tagline: "Momentum is everything.",
    teaser: "Unlock this level →",
    reward: "+200 XP streak bonus at this level",
    unlocks: [
      { icon: "📚", text: "Full template library" },
      { icon: "✍️", text: "Community posting" },
      { icon: "🔥", text: "Streak XP multiplier" },
      { icon: "⚡", text: "Daily mission rewards" },
    ],
    challenge: "Build a 7-day learning streak",
    xpBar: 100,
  },
  {
    name: "Business Builder", xp: "2k – 5k XP", icon: "🏗️", num: 3,
    color: "#3B82F6", darkColor: "#1D4ED8", bg: "#EFF6FF", border: "#93C5FD",
    tagline: "Build what others only dream of.",
    teaser: "See what you'll unlock →",
    reward: "Personal feedback on your submissions",
    unlocks: [
      { icon: "🎯", text: "Submission feedback" },
      { icon: "🚀", text: "Advanced courses" },
      { icon: "🏆", text: "Badge showcase wall" },
      { icon: "📊", text: "Business analytics tools" },
    ],
    challenge: "Submit 3 business tasks for review",
    xpBar: 100,
  },
  {
    name: "Business Leader", xp: "5k – 10k XP", icon: "👑", num: 4,
    color: "#A855F7", darkColor: "#7E22CE", bg: "#FAF5FF", border: "#D8B4FE",
    tagline: "Lead. Inspire. Grow.",
    teaser: "Discover leader perks →",
    reward: "Live Q&A with Krishnatrya monthly",
    unlocks: [
      { icon: "🎙️", text: "Monthly live Q&A" },
      { icon: "🤝", text: "Mentor matching" },
      { icon: "📦", text: "Exclusive resources" },
      { icon: "🌍", text: "Global leader network" },
    ],
    challenge: "Reach top 20 on the leaderboard",
    xpBar: 100,
  },
  {
    name: "Expert Founder", xp: "10k+ XP", icon: "🏆", num: 5,
    color: "#F97316", darkColor: "#C2410C", bg: "#FFF7ED", border: "#FDBA74",
    tagline: "The pinnacle. The 1%.",
    teaser: "The ultimate reward →",
    reward: "Hall of Fame + CV recognition",
    unlocks: [
      { icon: "🌟", text: "Hall of Fame entry" },
      { icon: "🎓", text: "Alumni network access" },
      { icon: "📜", text: "CV recognition badge" },
      { icon: "💼", text: "Career profile boost" },
    ],
    challenge: "Complete all 5 course modules",
    xpBar: 100,
  },
];

function PulsingOrb({ color, size = 10, delay = 0 }) {
  return (
    <div className="relative flex items-center justify-center" style={{ width: size, height: size }}>
      <div className="absolute rounded-full animate-ping"
        style={{ width: size, height: size, backgroundColor: `${color}30`, animationDelay: `${delay}ms`, animationDuration: "2s" }} />
      <div className="relative rounded-full" style={{ width: size * 0.6, height: size * 0.6, backgroundColor: color }} />
    </div>
  );
}

function XPFillBar({ pct, color, delay = 0 }) {
  const [w, setW] = useState(0);
  const ref = useRef(null);
  useEffect(() => {
    let timeoutId;
    let frameId;

    const startFill = () => {
      setW(0);
      frameId = requestAnimationFrame(() => {
        timeoutId = setTimeout(() => setW(pct), delay);
      });
    };

    const el = ref.current;
    if (el && "IntersectionObserver" in window) {
      const obs = new IntersectionObserver(([entry]) => {
        if (entry.isIntersecting) {
          startFill();
          obs.disconnect();
        }
      }, { threshold: 0.1 });
      obs.observe(el);
      return () => {
        obs.disconnect();
        clearTimeout(timeoutId);
        cancelAnimationFrame(frameId);
      };
    }

    startFill();
    return () => {
      clearTimeout(timeoutId);
      cancelAnimationFrame(frameId);
    };
  }, [pct, delay]);

  return (
    <div ref={ref} className="w-full rounded-full overflow-hidden" style={{ height: 6, backgroundColor: "#F0E8DF" }}>
      <div className="relative h-full rounded-full transition-all duration-1000 ease-out overflow-hidden"
        style={{ width: `${w}%`, backgroundColor: color, boxShadow: `0 0 8px ${color}60` }}>
        <div
          className="absolute inset-y-0 w-16 opacity-60 xp-ladder-shine"
          style={{ background: "linear-gradient(90deg, transparent, rgba(255,255,255,0.9), transparent)" }}
        />
      </div>
    </div>
  );
}

function XPLadderRunner() {
  return (
    <div className="pointer-events-none absolute inset-x-0 top-1/2 -translate-y-1/2">
      <div className="xp-ladder-runner h-4 w-4 rounded-full shadow-lg"
        style={{ backgroundColor: GOLD, boxShadow: `0 0 0 6px ${GOLD}22, 0 0 18px ${GOLD}AA` }} />
    </div>
  );
}

function LevelCard({ level, index, isActive, isDone }) {
  const [expanded, setExpanded] = useState(false);
  const [clicked, setClicked] = useState(false);

  const handleClick = () => {
    if (!clicked) setClicked(true);
    setExpanded(prev => !prev);
  };

  return (
    <div
      className={`relative rounded-2xl border bg-white flex flex-col transition-all duration-500 cursor-pointer select-none overflow-hidden
        ${expanded ? "shadow-2xl scale-[1.02]" : "hover:-translate-y-1 hover:shadow-lg"}`}
      style={{
        borderColor: expanded ? level.color : isActive ? `${level.color}55` : "#E5DDD5",
        borderTopWidth: 3,
        borderTopColor: level.color,
        boxShadow: expanded
          ? `0 12px 40px ${level.color}28, 0 0 0 2px ${level.color}20`
          : isActive ? `0 4px 20px ${level.color}20` : undefined,
      }}
      onClick={handleClick}
    >
      <div className="p-5 flex flex-col flex-1">
        {/* Level number + orb */}
        <div className="flex items-center justify-between mb-3">
          <div className="text-[9px] font-black uppercase tracking-widest" style={{ color: level.color }}>
            Level {String(level.num).padStart(2, "0")}
          </div>
          <PulsingOrb color={level.color} size={12} delay={index * 300} />
        </div>

        {/* Icon */}
        <div className="w-12 h-12 rounded-2xl flex items-center justify-center text-xl mb-3 border transition-all duration-300"
          style={{
            backgroundColor: expanded ? level.color + "22" : level.bg,
            borderColor: expanded ? level.color : level.border,
            transform: expanded ? "scale(1.1)" : "scale(1)",
          }}>
          {level.icon}
        </div>

        {/* Name + tagline */}
        <div className="font-black text-sm mb-1 leading-tight" style={{ color: BRAND }}>{level.name}</div>
        <div className="text-[10px] font-semibold mb-3" style={{ color: level.darkColor }}>{level.tagline}</div>

        {/* XP range pill */}
        <div className="text-[10px] font-bold mb-4 px-2 py-1 rounded-lg inline-block"
          style={{ backgroundColor: level.bg, color: level.darkColor, border: `1px solid ${level.border}` }}>
          {level.xp}
        </div>

        {/* Collapsed: show 2 unlock previews + teaser */}
        {!expanded && (
          <div className="mt-auto space-y-1.5">
            {level.unlocks.slice(0, 2).map((u, j) => (
              <div key={j} className="flex items-center gap-1.5 text-[10px] font-medium py-1 px-2 rounded-lg"
                style={{ backgroundColor: level.bg, color: "#4A3F3A" }}>
                <span>{u.icon}</span>
                <span className="truncate">{u.text}</span>
              </div>
            ))}
            <div className="flex items-center gap-1.5 text-[10px] font-black pt-2 border-t group"
              style={{ borderColor: "#F0E8DF", color: level.color }}>
              <span className="animate-pulse">✦</span>
              <span>{level.teaser}</span>
              <span className="ml-auto transition-transform group-hover:translate-x-1">›</span>
            </div>
          </div>
        )}

        {/* Expanded reveal */}
        {expanded && (
          <div className="mt-1 space-y-3 animate-fade-in-up">
            {/* Reward highlight */}
            <div className="rounded-xl p-3 border text-center"
              style={{ backgroundColor: level.bg, borderColor: level.border }}>
              <div className="text-base mb-1">🎁</div>
              <div className="text-[10px] font-black leading-tight" style={{ color: level.darkColor }}>{level.reward}</div>
            </div>

            {/* Unlocks list */}
            <div className="space-y-1.5">
              {level.unlocks.map((u, j) => (
                <div key={j} className="flex items-center gap-2 text-[10px] font-medium py-1 px-2 rounded-lg"
                  style={{ backgroundColor: "#FAFAF8", color: "#4A3F3A",
                    animationDelay: `${j * 80}ms` }}>
                  <span>{u.icon}</span>
                  <span>{u.text}</span>
                  <span className="ml-auto font-black" style={{ color: level.color }}>✓</span>
                </div>
              ))}
            </div>

            {/* Challenge */}
            <div className="rounded-xl p-3 border"
              style={{ background: `linear-gradient(135deg, ${BRAND}08, ${BRAND}04)`, borderColor: `${level.color}30` }}>
              <div className="text-[9px] font-black uppercase tracking-widest mb-1" style={{ color: level.color }}>
                🎯 Level Challenge
              </div>
              <div className="text-[10px] font-semibold" style={{ color: BRAND }}>{level.challenge}</div>
            </div>

            <div className="text-center pt-1">
              <span className="text-[9px] font-black" style={{ color: level.color }}>Click again to collapse ↑</span>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

// Connected XP path — nodes sit centered above each card column
function XPPath() {
  const ref = useRef(null);
  const [vis, setVis] = useState(false);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const obs = new IntersectionObserver(([e]) => { if (e.isIntersecting) setVis(true); }, { threshold: 0.1 });
    obs.observe(el);
    return () => obs.disconnect();
  }, []);

  return (
    <div ref={ref} className="hidden md:grid mb-3" style={{ gridTemplateColumns: "repeat(5, 1fr)", gap: "1rem" }}>
      {LEVEL_DEFS.map((level, i) => (
        <div key={i} className="flex items-center">
          {/* Node centered in column */}
          <div className="flex items-center w-full">
            <div className="flex-shrink-0 w-9 h-9 rounded-full border-2 flex items-center justify-center text-xs font-black transition-all duration-700 mx-auto"
              style={{
                backgroundColor: vis ? level.color : "#F0E8DF",
                borderColor: vis ? level.color : "#E5DDD5",
                color: vis ? "white" : "#B5A49A",
                transitionDelay: `${i * 150}ms`,
                boxShadow: vis ? `0 0 16px ${level.color}50` : "none",
                position: "relative", zIndex: 1,
              }}>
              {level.num}
            </div>
          </div>
        </div>
      ))}
      {/* Connector line drawn behind nodes — sits at vertical centre of the 36px nodes (half of 9 = 4.5px → -mt-[22px] centres through middle) */}
      <div className="col-span-5 flex items-center" style={{ marginTop: "-22px", height: 2, position: "relative", zIndex: 0 }}>
        <div className="w-full h-0.5 overflow-hidden rounded-full" style={{ backgroundColor: "#F0E8DF" }}>
          <div className="h-full transition-all duration-1000 rounded-full"
            style={{
              width: vis ? "100%" : "0%",
              background: `linear-gradient(90deg, ${LEVEL_DEFS[0].color}, ${LEVEL_DEFS[1].color}, ${LEVEL_DEFS[2].color}, ${LEVEL_DEFS[3].color}, ${LEVEL_DEFS[4].color})`,
              transitionDelay: "300ms",
            }} />
        </div>
      </div>
    </div>
  );
}

export default function FounderJourneySection({ isAuthenticated, userProgress }) {
  const totalXP = userProgress?.total_xp || 0;
  const getCurrentLevel = () => {
    if (totalXP >= 10000) return 4;
    if (totalXP >= 5000)  return 3;
    if (totalXP >= 2000)  return 2;
    if (totalXP >= 500)   return 1;
    return 0;
  };
  const currentLevelIndex = isAuthenticated ? getCurrentLevel() : -1;

  return (
    <section className="py-24 px-6" style={{ backgroundColor: "#FAF5F0" }}>
      <div className="max-w-6xl mx-auto">

        {/* Header */}
        <div className="text-center mb-10">
          <div className="cv-badge-gold inline-block mb-4">Your Journey</div>
          <h2 className="text-4xl md:text-5xl font-black tracking-tight mb-4" style={{ color: BRAND }}>
            Five levels.<br/>
            <span style={{ color: GOLD }}>One founder journey.</span>
          </h2>
          <p className="text-base max-w-lg mx-auto font-medium mb-3" style={{ color: "#6B5D52" }}>
            Every lesson earns XP. Every XP brings you closer to the next level — and the rewards that come with it.
          </p>
          {/* Engagement nudge */}
          <div className="inline-flex items-center gap-2 px-4 py-2 rounded-full border text-sm font-bold animate-pulse"
            style={{ backgroundColor: "rgba(212,176,56,0.10)", borderColor: "rgba(212,176,56,0.35)", color: GOLD_DEEP }}>
            <span>✦</span>
            <span>Click any level to discover what you unlock</span>
            <span>✦</span>
          </div>
        </div>

        {/* Animated XP connection path */}
        <XPPath />

        {/* Level cards */}
        <div className="grid md:grid-cols-5 gap-4 mb-12">
          {LEVEL_DEFS.map((level, i) => (
            <LevelCard
              key={i}
              level={level}
              index={i}
              isActive={i === currentLevelIndex}
              isDone={i < currentLevelIndex}
            />
          ))}
        </div>

        {/* Bottom XP progress strip */}
        <div className="rounded-2xl p-6 border mb-10" style={{ backgroundColor: "#FFFFFF", borderColor: "#E5DDD5" }}>
          <div className="flex items-center justify-between mb-4">
            <div>
              <div className="text-xs font-black uppercase tracking-widest mb-0.5" style={{ color: "#B5A49A" }}>The XP Ladder</div>
              <div className="font-black text-base" style={{ color: BRAND }}>Every action moves you forward</div>
            </div>
            <div className="text-xs font-bold px-3 py-1.5 rounded-xl"
              style={{ backgroundColor: "#FFF8E7", color: GOLD_DEEP, border: `1px solid ${GOLD}44` }}>
              10,000 XP to Expert
            </div>
          </div>
          <div className="relative flex items-center gap-0 mb-4 py-1">
            {LEVEL_DEFS.map((l, i) => (
              <div key={i} className="flex-1 relative">
                <XPFillBar pct={100} color={l.color} delay={i * 200 + 400} />
                {i < LEVEL_DEFS.length - 1 && <div className="absolute right-0 top-0 w-0.5 h-6 -translate-y-px" style={{ backgroundColor: "#FAF5F0" }} />}
              </div>
            ))}
            <XPLadderRunner />
          </div>
          <div className="grid grid-cols-5 text-center">
            {["0", "500", "2k", "5k", "10k+"].map((xp, i) => (
              <div key={i} className="text-[10px] font-black" style={{ color: LEVEL_DEFS[i].color }}>{xp} XP</div>
            ))}
          </div>
        </div>

        {/* CTA */}
        <div className="text-center">
          {isAuthenticated ? (
            <Link to="/progress" className="cv-btn-primary inline-block text-sm font-black px-10 py-4 rounded-2xl">
              View My Progress →
            </Link>
          ) : (
            <Link to="/register" className="cv-btn-primary inline-block text-sm font-black px-10 py-4 rounded-2xl">
              Start at Level 1 Today →
            </Link>
          )}
          <p className="text-xs mt-3 font-medium" style={{ color: "#B5A49A" }}>Free trial · No card required · Cancel anytime</p>
        </div>
      </div>
    </section>
  );
}

