/**
 * Organization switcher component.
 *
 * ⚠️ AUTO-GENERATED BY PRISM (GENERATE_ONCE) — safe to edit
 *
 * A dropdown component for switching between organizations.
 * Intended to be placed in a navigation bar or sidebar.
 */

import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  listMyOrganizations,
  type Organization,
} from '../../lib/orgApi';

interface OrgSwitcherProps {
  currentSlug?: string;
  onSwitch?: (org: Organization) => void;
}

export default function OrgSwitcher({ currentSlug, onSwitch }: OrgSwitcherProps) {
  const navigate = useNavigate();
  const [orgs, setOrgs] = useState<Organization[]>([]);
  const [isOpen, setIsOpen] = useState(false);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    listMyOrganizations()
      .then((data) => setOrgs(data.organizations))
      .catch(console.error)
      .finally(() => setLoading(false));
  }, []);

  const currentOrg = orgs.find((o) => o.{{ slug_field }} === currentSlug);

  function handleSelect(org: Organization) {
    setIsOpen(false);
    if (onSwitch) {
      onSwitch(org);
    } else {
      navigate(`/organizations/${org.{{ slug_field }}}`);
    }
  }

  if (loading) return <div className="text-sm text-gray-400">...</div>;
  if (orgs.length === 0) return null;

  return (
    <div className="relative">
      <button
        onClick={() => setIsOpen(!isOpen)}
        className="flex items-center gap-2 px-3 py-2 text-sm border rounded-lg hover:bg-gray-50 min-w-[180px]"
      >
        <span className="truncate">
          {currentOrg ? currentOrg.name : 'Select organization'}
        </span>
        <svg
          className={`w-4 h-4 transition-transform ${isOpen ? 'rotate-180' : ''}`}
          fill="none"
          viewBox="0 0 24 24"
          stroke="currentColor"
        >
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
        </svg>
      </button>

      {isOpen && (
        <>
          <div className="fixed inset-0 z-10" onClick={() => setIsOpen(false)} />
          <div className="absolute z-20 mt-1 w-full min-w-[220px] bg-white border rounded-lg shadow-lg py-1">
            {orgs.map((org) => (
              <button
                key={org.id}
                onClick={() => handleSelect(org)}
                className={`w-full text-left px-4 py-2 text-sm hover:bg-gray-50 flex items-center justify-between ${
                  org.{{ slug_field }} === currentSlug ? 'bg-blue-50 text-blue-700' : ''
                }`}
              >
                <span className="truncate">{org.name}</span>
                <span className="text-xs text-gray-400">{org.current_user_role}</span>
              </button>
            ))}
{% if allow_multiple_orgs %}
            <div className="border-t my-1" />
            <button
              onClick={() => {
                setIsOpen(false);
                navigate('/organizations/new');
              }}
              className="w-full text-left px-4 py-2 text-sm text-blue-600 hover:bg-gray-50"
            >
              + Create Organization
            </button>
{% endif %}
          </div>
        </>
      )}
    </div>
  );
}
