import React, { useSyncExternalStore } from 'react';
import { UILocation } from '@paarrot/plugin-manager';
import {
  SidebarItem,
  SidebarItemTooltip,
  SidebarAvatar,
} from '../../../components/sidebar';
import { pluginRegistry } from './PluginAPI';
import { subscribeToButtons, getStoreVersion } from './PluginButtonSlot';

interface PluginSidebarSlotProps {
  /** The UI location to render sidebar icon entries for. */
  location: UILocation;
}

/**
 * Renders plugin buttons as `SidebarItem` entries, matching the style of
 * built-in sidebar tabs like SearchTab, InboxTab, and SettingsTab.
 * Intended for the `sidebar-actions` location in the main left sidebar.
 */
export function PluginSidebarSlot({ location }: PluginSidebarSlotProps): React.ReactElement | null {
  useSyncExternalStore(subscribeToButtons, getStoreVersion);

  const buttons = pluginRegistry.getButtonsForLocation(location);
  if (buttons.length === 0) return null;

  return (
    <>
      {buttons.map((button) => (
        <SidebarItem key={button.id}>
          <SidebarItemTooltip tooltip={button.label}>
            {(triggerRef) => (
              <SidebarAvatar
                as="button"
                ref={triggerRef}
                onClick={() => button.onClick?.()}
                aria-label={button.label}
              >
                <span aria-hidden style={{ fontSize: '1.2em', lineHeight: 1 }}>
                  {button.icon ?? '🔌'}
                </span>
              </SidebarAvatar>
            )}
          </SidebarItemTooltip>
        </SidebarItem>
      ))}
    </>
  );
}
