/**
 * Settings Section Component
 *
 * Collapsible section for organizing settings with badge and toggle-all functionality
 *
 * @package ProRank\SEO
 * @since   1.0.0
 */

import { useState, ReactNode } from '@wordpress/element';
import { __ } from '@wordpress/i18n';

interface SettingsSectionProps {
  title: string;
  badge?: string;
  defaultExpanded?: boolean;
  premiumBadge?: boolean;
  enabledCount?: number;
  totalCount?: number;
  onToggleAll?: (enabled: boolean) => void;
  children: ReactNode;
}

const SettingsSection = ({
  title,
  badge,
  defaultExpanded = false,
  premiumBadge = false,
  enabledCount,
  totalCount,
  onToggleAll,
  children,
}: SettingsSectionProps) => {
  const [expanded, setExpanded] = useState(defaultExpanded);

  const handleToggleAll = (e: React.MouseEvent) => {
    e.stopPropagation();
    if (!onToggleAll || typeof enabledCount !== 'number' || typeof totalCount !== 'number') {
      return;
    }
    const shouldEnable = enabledCount !== totalCount;
    onToggleAll(shouldEnable);
  };

  const handleHeaderKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {
    if (e.key === 'Enter' || e.key === ' ') {
      e.preventDefault();
      setExpanded(!expanded);
    }
  };

  const showToggleAll =
    onToggleAll &&
    typeof enabledCount === 'number' &&
    typeof totalCount === 'number';

  const toggleAllLabel =
    typeof enabledCount === 'number' && typeof totalCount === 'number' && enabledCount === totalCount
      ? __('Disable All', 'prorank-seo')
      : __('Enable All', 'prorank-seo');

  return (
    <div className={`prorank-settings-section ${expanded ? 'expanded' : 'collapsed'}`}>
      <div
        className="prorank-settings-section-header"
        role="button"
        tabIndex={0}
        onClick={() => setExpanded(!expanded)}
        onKeyDown={handleHeaderKeyDown}
        aria-expanded={expanded}
      >
        <div className="prorank-settings-section-header-left">
          <span className={`dashicons ${expanded ? 'dashicons-arrow-down-alt2' : 'dashicons-arrow-right-alt2'}`} />
          <span className="prorank-settings-section-title">{title}</span>
          {badge && <span className="prorank-settings-section-badge">{badge}</span>}
          {premiumBadge && <span className="prorank-settings-section-premium">PREMIUM</span>}
        </div>
        {showToggleAll && (
          <button
            type="button"
            className="prorank-settings-section-toggle-all"
            onClick={handleToggleAll}
          >
            {toggleAllLabel}
          </button>
        )}
      </div>
      {expanded && (
        <div className="prorank-settings-section-content">
          {children}
        </div>
      )}
    </div>
  );
};

export default SettingsSection;
