import { useRef, type ReactNode } from "react";
import { useLocation, useNavigate } from "react-router";

type SystemTab = { id: string; label: string; content: ReactNode };

export function DesignSystemTabs({ tabs }: { tabs: SystemTab[] }) {
  const { hash } = useLocation();
  const navigate = useNavigate();
  const buttons = useRef<Array<HTMLButtonElement | null>>([]);
  const selected = tabs.findIndex((tab) => hash === `#${tab.id}`);
  const active = selected < 0 ? 0 : selected;

  function select(index: number) {
    navigate({ hash: `#${tabs[index]!.id}` });
  }

  return (
    <div className="ds-explorer">
      <div className="ds-tab-bar" role="tablist" aria-label="Design system sections">
        {tabs.map((tab, index) => (
          <button
            key={tab.id}
            ref={(element) => { buttons.current[index] = element; }}
            type="button"
            role="tab"
            id={`ds-tab-${tab.id}`}
            aria-controls={`ds-panel-${tab.id}`}
            aria-selected={active === index}
            tabIndex={active === index ? 0 : -1}
            onClick={() => select(index)}
            onKeyDown={(event) => {
              let next = index;
              if (event.key === "ArrowRight") next = (index + 1) % tabs.length;
              else if (event.key === "ArrowLeft") next = (index - 1 + tabs.length) % tabs.length;
              else if (event.key === "Home") next = 0;
              else if (event.key === "End") next = tabs.length - 1;
              else return;
              event.preventDefault();
              select(next);
              buttons.current[next]?.focus();
            }}
          >
            {tab.label}
          </button>
        ))}
      </div>
      {/* Keep panels mounted so editors and examples retain their local state. */}
      {tabs.map((tab, index) => (
        <div
          key={tab.id}
          id={`ds-panel-${tab.id}`}
          role="tabpanel"
          aria-labelledby={`ds-tab-${tab.id}`}
          tabIndex={0}
          hidden={active !== index}
          className="ds-tab-panel"
        >
          {tab.content}
        </div>
      ))}
    </div>
  );
}
