import { useEffect, useState } from 'react';
import { applyThemeAccent, getThemeAccent, themeAccents } from '../utils/themeAccent';

export default function ThemeAccentPicker({ compact = false, label = 'رنگ‌بندی' }) {
  const [accent, setAccent] = useState(getThemeAccent);

  useEffect(() => {
    const syncAccent = (event) => setAccent(event.detail?.accent || getThemeAccent());
    window.addEventListener('theme-accent-change', syncAccent);
    return () => window.removeEventListener('theme-accent-change', syncAccent);
  }, []);

  const changeAccent = (key) => {
    setAccent(applyThemeAccent(key));
  };

  return (
    <div className={`theme-accent-picker ${compact ? 'compact' : ''}`} aria-label="انتخاب تم رنگی">
      {!compact && <span>{label}</span>}
      <div>
        {themeAccents.map((item) => (
          <button
            key={item.key}
            type="button"
            className={accent === item.key ? 'active' : ''}
            onClick={() => changeAccent(item.key)}
            title={item.label}
            aria-label={`تم ${item.label}`}
            style={{ '--accent-swatch': item.color }}
          />
        ))}
      </div>
    </div>
  );
}
