// Rôle : fournit le panneau de filtres générique des pages de données de jeu.
import { Icon } from "../../components/Icon.jsx";

export function GameFiltersPanel({
  title,
  nameLabel = "Nom",
  resetLabel = "Réinitialiser",
  matchLabel = "Correspondance",
  logicLabels = { and: "Et", or: "Ou" },
  filters,
  selectedKey,
  options,
  getOptionId = (option) => option,
  getOptionLabel = (option) => option,
  getOptionClassName = () => "",
  renderOptionMedia,
  onChange
}) {
  const selected = new Set(filters[selectedKey] || []);
  const logicLabel = filters.logic === "or" ? logicLabels.or : logicLabels.and;

  function update(updater) {
    onChange(updater(filters));
  }

  return (
    <div className="filter-panel">
      <div className="filter-panel-head">
        <div>
          <p className="eyebrow">Filtres</p>
          <h2>{title}</h2>
        </div>
        <button
          className="filter-reset-button"
          onClick={() => onChange({ name: "", [selectedKey]: [], logic: "and" })}
          aria-label={resetLabel}
          title={resetLabel}
        >
          <Icon name="rubber" />
        </button>
      </div>
      <label className="field compact">
        <span>{nameLabel}</span>
        <input value={filters.name} placeholder="Rechercher..." onChange={(event) => update((state) => ({ ...state, name: event.target.value }))} />
      </label>
      <div className="filter-logic">
        <span>{matchLabel}</span>
        <button onClick={() => update((state) => ({ ...state, logic: state.logic === "and" ? "or" : "and" }))}>{logicLabel}</button>
      </div>
      <div className="filter-options legacy-scrollbar">
        {options.map((option) => {
          const optionId = getOptionId(option);
          return (
            <label className={`filter-chip ${getOptionClassName(option)} ${selected.has(optionId) ? "active" : ""}`} key={optionId}>
              <input
                type="checkbox"
                checked={selected.has(optionId)}
                onChange={(event) => update((state) => {
                  const values = new Set(state[selectedKey] || []);
                  if (event.target.checked) values.add(optionId);
                  else values.delete(optionId);
                  return { ...state, [selectedKey]: [...values] };
                })}
              />
              {renderOptionMedia?.(option)}
              <span>{getOptionLabel(option)}</span>
            </label>
          );
        })}
      </div>
    </div>
  );
}
