import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';

export default function Dashboard() {
  const [user, setUser] = useState(null);

  useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    const token = params.get('token');

    if (token) {
      localStorage.setItem('ranked_token', token);
      history.replaceState(null, '', window.location.pathname);

      try {
        // Decode payload (no signature verification — display only)
        const payload = JSON.parse(atob(token.split('.')[1]));
        setUser({ name: payload.name, avatar: payload.picture });
      } catch {
        setUser({ name: 'Player', avatar: null });
      }
    } else {
      // Token may have been stored from a previous visit
      const stored = localStorage.getItem('ranked_token');
      if (stored) {
        try {
          const payload = JSON.parse(atob(stored.split('.')[1]));
          setUser({ name: payload.name, avatar: payload.picture });
        } catch {
          setUser({ name: 'Player', avatar: null });
        }
      }
    }
  }, []);

  const initial = user?.name?.[0]?.toUpperCase() ?? '?';

  return (
    <>
      {/* Reuse the same animated background */}
      <div className="arena-bg">
        <div className="arena-grain" />
      </div>

      {/* User pill — top right */}
      {user && (
        <div className="dash__user-bar">
          {user.avatar ? (
            <img
              className="dash__avatar"
              src={user.avatar}
              alt={user.name}
              referrerPolicy="no-referrer"
            />
          ) : (
            <div className="dash__avatar dash__avatar--fallback">{initial}</div>
          )}
          <span className="dash__user-name">{user.name}</span>
        </div>
      )}

      {/* Main content */}
      <main className="page dashboard">
        <div className="dash__card">
          {/* Radar pulse */}
          <div className="dash__radar">
            <div className="dash__radar-ring" />
            <div className="dash__radar-ring" />
            <div className="dash__radar-ring" />
            <div className="dash__radar-core">🏆</div>
          </div>

          <p className="dash__eyebrow">Status</p>
          <h1 className="dash__title">Coming Soon</h1>
          <p className="dash__subtitle">
            Your dashboard, stats, and ranked matches are on the way.
            {user && ` Get ready, ${user.name.split(' ')[0]}.`}
          </p>

          <Link to="/" className="dash__back">
            Back to home
          </Link>
        </div>
      </main>
    </>
  );
}
