import { Navigate, useParams } from 'react-router';
import type { LayoutNode } from 'officerdev';
import { WorkspaceView, DEFAULT_GITEA_SECTION, giteaSectionPath, isGiteaSection } from 'officerdev';
import { useDashboardState } from 'state/useDashboardState';
import { defaultLayout } from './defaultLayout';

// /gitea uses the Workspace/Panel system (like /transmission): a section nav on the left and the section view
// on the right. Both talk to the officer-gitea sidecar through the /api/gitea auth proxy, which holds no
// Gitea credentials of its own — the instance URL and the access token live in the sidecar.
//
// The open section is :section in the URL, so the panels read it with useParams instead of passing state
// between themselves over a channel. This screen backs both /gitea and /gitea/:section and is the single
// place that decides what an absent or bogus section means.

export const GiteaScreen = () => {
  const { section, owner, name } = useParams();
  const workspace = useDashboardState<LayoutNode>('screens/gitea', defaultLayout);

  // Bare /gitea, or a section that doesn't exist, resolves to a canonical URL rather than rendering a default
  // while the address bar says something else — the nav highlight is derived from the URL.
  //
  // A repository route (/gitea/repo/:owner/:name/…) has no :section at all and is exempt: it is a second,
  // deeper shape on the same screen, not a malformed section.
  const inRepo = !!owner && !!name;
  if (!inRepo && !isGiteaSection(section)) {
    return <Navigate to={giteaSectionPath(DEFAULT_GITEA_SECTION)} replace />;
  }

  return (
    <div className="h-full w-full pt-2">
      <WorkspaceView
        workspace={workspace}
        locked
        appTypes={{ allowed: ['gitea-nav', 'gitea-view'], fallback: 'gitea-view' }}
      />
    </div>
  );
};
