import { useParams, useSearchParams } from 'react-router';
import {
  DEFAULT_GITEA_REPO_TAB,
  DEFAULT_GITEA_SECTION,
  isGiteaRepoTab,
  isGiteaSection,
  type GiteaRepoTab,
  type GiteaSectionId,
} from './shared';

// Where the app is, read straight off the URL — per docs/navigation-audit.md, the URL is the selection.
//
// Every gitea panel calls one of these instead of being handed state by a sibling, which is what makes
// cmd-click, the back button and a pasted link all work without anything extra.

export function useGiteaSection(): GiteaSectionId {
  const { section } = useParams();
  return isGiteaSection(section) ? section : DEFAULT_GITEA_SECTION;
}

export type GiteaLocation = {
  /** Null when the URL is not pointing at a repository at all — i.e. this is a top-level section. */
  owner: string | null;
  repo: string | null;
  tab: GiteaRepoTab;
  /** Issue / PR number or a commit sha, from the segment after the tab. */
  item: string | null;
  /** Path within the repository being browsed. Empty string is the root, which is a real location. */
  path: string;
  /** Branch, tag or sha. Null means "whatever the repo's default branch is", resolved by the caller. */
  refName: string | null;
};

export function useGiteaLocation(): GiteaLocation {
  const { owner, name, tab, item } = useParams();
  const [params] = useSearchParams();

  return {
    owner: owner ?? null,
    repo: name ?? null,
    tab: isGiteaRepoTab(tab) ? tab : DEFAULT_GITEA_REPO_TAB,
    item: item ?? null,
    path: params.get('path') ?? '',
    refName: params.get('ref') || null,
  };
}
