import { useEffect, useState } from "react";
import { useAuthStore } from "../stores/authStore";

const STYLES = `
  .lb-wrap {
    display: flex; align-items: center; gap: 0.55rem;
    background: white;
    border: 2px solid #f3f4f6;
    border-radius: 100px;
    padding: 0.38rem 0.75rem 0.38rem 0.42rem;
    box-shadow: 0 2px 10px rgba(0,0,0,0.05);
    animation: lbIn 0.4s cubic-bezier(0.34,1.56,0.64,1) both;
  }
  @keyframes lbIn {
    from { opacity:0; transform: scale(0.9) translateX(6px); }
    to   { opacity:1; transform: scale(1)   translateX(0);   }
  }

  /* Level bubble */
  .lb-bubble {
    width: 28px; height: 28px; border-radius: 50%; flex-shrink: 0;
    background: linear-gradient(135deg, #a855f7, #7c3aed);
    display: flex; align-items: center; justify-content: center;
    box-shadow: 0 2px 0 #5b21b644;
    font-family: 'Nunito', sans-serif;
    font-size: 0.7rem; font-weight: 900; color: white;
    letter-spacing: -0.02em;
  }

  /* Bar track */
  .lb-track {
    width: 80px; height: 7px;
    background: #f3f4f6; border-radius: 100px; overflow: hidden;
    flex-shrink: 0;
  }
  .lb-fill {
    height: 100%; border-radius: 100px;
    background: linear-gradient(90deg, #a855f7, #f97316);
    transition: width 1s cubic-bezier(0.34,1.56,0.64,1);
    position: relative; overflow: hidden;
  }
  .lb-fill::after {
    content: '';
    position: absolute; inset: 0;
    background: linear-gradient(90deg, transparent, rgba(255,255,255,0.45), transparent);
    transform: translateX(-100%);
    animation: lbShimmer 2.2s ease-in-out 1s infinite;
  }
  @keyframes lbShimmer { to { transform: translateX(200%); } }

  /* XP label */
  .lb-label {
    font-family: 'Nunito', sans-serif;
    font-size: 0.68rem; font-weight: 900;
    color: #a855f7; white-space: nowrap;
  }
`;

export const LevelBar = () => {
  const user = useAuthStore((s) => s.user);
  const u = user as any;

  const level = u?.current_level ?? u?.level ?? 1;
  const totalXP = u?.total_xp ?? u?.xp ?? 0;
  const levelStart = u?.current_level_start ?? u?.level_min_xp ?? 0;
  const levelEnd =
    u?.next_level_threshold ?? u?.level_max_xp ?? levelStart + 1000;

  const levelRange = Math.max(levelEnd - levelStart, 1);
  const xpIntoLevel = Math.max(totalXP - levelStart, 0);
  const rawPct = Math.min(Math.round((xpIntoLevel / levelRange) * 100), 100);

  const [pct, setPct] = useState(0);
  useEffect(() => {
    const id = requestAnimationFrame(() =>
      requestAnimationFrame(() => setPct(rawPct)),
    );
    return () => cancelAnimationFrame(id);
  }, [rawPct]);

  return (
    <>
      <style>{STYLES}</style>
      <div className="lb-wrap">
        <div className="lb-bubble">{level}</div>
        <div className="lb-track">
          <div className="lb-fill" style={{ width: `${pct}%` }} />
        </div>
        <span className="lb-label">{pct}%</span>
      </div>
    </>
  );
};
