"use client";

import { useAppDispatch, useAppSelector } from "@/store/hooks";
import {
  searchContent,
  setActiveType,
  selectSearchQuery,
  selectSearchType,
  selectSearchLoading,
} from "@/store/slices/searchSlice";
import { getStoredUser } from "@/lib/utils/persistAuth";

const TABS = [
  { id: "all",      type: 0, label: "All",       icon: <svg viewBox="0 0 24 24"><line x1="3" y1="6" x2="21" y2="6" /><line x1="3" y1="12" x2="21" y2="12" /><line x1="3" y1="18" x2="21" y2="18" /></svg> },
  { id: "articles", type: 1, label: "Articles",  icon: <svg viewBox="0 0 24 24"><path d="M4 4h12l4 4v12H4z" /><path d="M16 4v4h4M8 12h8M8 16h6" /></svg> },
  { id: "live",     type: 3, label: "Live News", icon: <svg viewBox="0 0 24 24"><rect x="2" y="5" width="20" height="14" rx="2" /><path d="M8 21h8M12 19v2" /><circle cx="12" cy="12" r="2" fill="currentColor" /></svg> },
  { id: "shows",    type: 4, label: "Shows",     icon: <svg viewBox="0 0 24 24"><polygon points="6 4 20 12 6 20" fill="currentColor" stroke="none" /></svg> },
];

export default function SearchTabs() {
  const dispatch = useAppDispatch();
  const query   = useAppSelector(selectSearchQuery);
  const active  = useAppSelector(selectSearchType);
  const loading = useAppSelector(selectSearchLoading);

  function switchTab(type: number) {
    if (loading) return;
    dispatch(setActiveType(type));
    if (query.trim()) {
      dispatch(searchContent({ query, type, userId: getStoredUser()?.id ?? 0 }));
    }
  }

  return (
    <nav className="search-tabs">
      <div className="wrap search-tabs-row">
        {TABS.map((tab) => (
          <button
            key={tab.id}
            className={`search-tab${active === tab.type ? " active" : ""}`}
            onClick={() => switchTab(tab.type)}
          >
            {tab.icon}
            {tab.label}
          </button>
        ))}
      </div>
    </nav>
  );
}
