import { useEffect, useState } from 'react';
import { NavLink, Outlet } from 'react-router-dom';
import { useAuth } from '../AuthContext';
import { formatCredits } from '../api';
import DropFeed from './DropFeed';

const FEED_KEY = 'caseforge-feed-drop';

export default function Layout() {
  const { user, logout } = useAuth();
  const [feedOpen, setFeedOpen] = useState(() => {
    try {
      return localStorage.getItem(FEED_KEY) === '1';
    } catch {
      return false;
    }
  });

  useEffect(() => {
    try {
      localStorage.setItem(FEED_KEY, feedOpen ? '1' : '0');
    } catch {
      /* ignore */
    }
  }, [feedOpen]);

  return (
    <div className={`app-shell${feedOpen ? ' feed-open' : ''}`}>
      <header className="topnav">
        <NavLink to="/dashboard" className="brand">
          CaseForge
        </NavLink>
        <nav className="nav-links">
          {user && user.role !== 'admin' && (
            <>
              <NavLink to="/dashboard">Inventory</NavLink>
              <NavLink to="/cases">Cases</NavLink>
              <NavLink to="/bet">Bet Item</NavLink>
              <NavLink to="/shop">Shop</NavLink>
              <button
                type="button"
                className={`nav-toggle${feedOpen ? ' active' : ''}`}
                onClick={() => setFeedOpen((v) => !v)}
                aria-pressed={feedOpen}
              >
                Feed Drop
              </button>
            </>
          )}
          <NavLink to="/leaderboard">Leaderboard</NavLink>
          {user?.role === 'admin' && <NavLink to="/admin">Admin</NavLink>}
          {user && (
            <span className="balance-pill">{formatCredits(user.balance)} cr</span>
          )}
          {user ? (
            <>
              <NavLink to="/profile" className="nav-user" title="Profile">
                {user.avatarUrl ? (
                  <img src={user.avatarUrl} alt="" className="nav-avatar" />
                ) : null}
                <span className="muted">{user.username}</span>
              </NavLink>
              <button type="button" className="btn ghost" onClick={logout}>
                Logout
              </button>
            </>
          ) : (
            <NavLink to="/login">Login</NavLink>
          )}
        </nav>
      </header>
      <div className="app-body">
        {feedOpen && user && user.role !== 'admin' && <DropFeed />}
        <main className="main">
          <Outlet />
        </main>
      </div>
    </div>
  );
}
