// SONARA — Collapsible filter section (shared)
// Use inside .filter-rail to replace plain <div className="filter-group">.
// Header is clickable, body collapses smoothly. Active-filter count appears next to title.

function FilterSection({ title, count = 0, defaultOpen = true, children }) {
  const storageKey = "sonara-filter-section-" + title.toLowerCase().replace(/[^a-z0-9]+/g, "-");
  const [open, setOpen] = React.useState(() => {
    try {
      const v = localStorage.getItem(storageKey);
      if (v === null) return defaultOpen;
      return v === "1";
    } catch (e) { return defaultOpen; }
  });
  React.useEffect(() => {
    try { localStorage.setItem(storageKey, open ? "1" : "0"); } catch (e) {}
  }, [open, storageKey]);

  return (
    <div className={`filter-section ${open ? "open" : "closed"} ${count > 0 ? "has-count" : ""}`}>
      <button className="filter-section-head" onClick={() => setOpen(!open)} aria-expanded={open}>
        <span className="title">{title}</span>
        {count > 0 && <span className="count">{count}</span>}
        <span className="chevron" aria-hidden>
          <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><polyline points="6 9 12 15 18 9"/></svg>
        </span>
      </button>
      <div className="filter-section-body">
        {children}
      </div>
    </div>
  );
}

// Toolbar button to toggle the whole rail
function RailToggleButton({ open, onChange, activeCount = 0 }) {
  return (
    <button className={`rail-toggle-btn ${open ? "open" : "closed"}`} onClick={() => onChange(!open)} aria-pressed={open}>
      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <line x1="4" y1="6" x2="20" y2="6"/>
        <line x1="6" y1="12" x2="18" y2="12"/>
        <line x1="9" y1="18" x2="15" y2="18"/>
      </svg>
      <span>Filtri</span>
      {activeCount > 0 && <span className="rail-toggle-count">{activeCount}</span>}
    </button>
  );
}

window.FilterSection = FilterSection;
window.RailToggleButton = RailToggleButton;
