import { useRole, ROLES, ROLE_LABELS, ROLE_COLORS } from "../hooks/useRole";
import { Shield, ChevronDown } from "lucide-react";
import { useState, useRef, useEffect } from "react";

export default function RoleSwitcher() {
  const { role, setRole } = useRole();
  const [open, setOpen] = useState(false);
  const ref = useRef(null);

  useEffect(() => {
    const handler = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, []);

  return (
    <div className="relative" ref={ref}>
      <button
        onClick={() => setOpen(!open)}
        className="flex items-center gap-2 px-3 py-1.5 rounded-full border border-border bg-card hover:bg-muted text-sm font-medium transition-colors"
      >
        <Shield className="w-3.5 h-3.5 text-primary" />
        <span className={`px-2 py-0.5 rounded-full text-xs font-semibold ${ROLE_COLORS[role]}`}>{ROLE_LABELS[role]}</span>
        <ChevronDown className={`w-3.5 h-3.5 text-muted-foreground transition-transform ${open ? "rotate-180" : ""}`} />
      </button>

      {open && (
        <div className="absolute right-0 top-full mt-2 w-52 bg-card border border-border rounded-xl shadow-lg z-50 overflow-hidden">
          <p className="text-xs text-muted-foreground px-4 pt-3 pb-1 font-semibold uppercase tracking-wide">Ganti Role</p>
          {Object.entries(ROLES).map(([key, val]) => (
            <button
              key={val}
              onClick={() => { setRole(val); setOpen(false); window.location.href = "/"; }}
              className={`w-full flex items-center gap-3 px-4 py-2.5 text-sm hover:bg-muted transition-colors text-left ${role === val ? "bg-primary/5" : ""}`}
            >
              <span className={`px-2 py-0.5 rounded-full text-xs font-semibold ${ROLE_COLORS[val]}`}>{ROLE_LABELS[val]}</span>
              {role === val && <span className="ml-auto text-primary text-xs">✓ Aktif</span>}
            </button>
          ))}
          <p className="text-xs text-muted-foreground px-4 pb-3 pt-1 border-t border-border mt-1">Demo mode - pilih peran Anda</p>
        </div>
      )}
    </div>
  );
}