import { useMemo } from 'react';
import { useParams } from 'react-router-dom';
import { useAtomValue } from 'jotai';
import { useMatrixClient } from '../../../hooks/useMatrixClient';
import { activeChannelsSpaceAtom } from '../../../state/activeChannelsSpace';
import { getCanonicalAliasRoomId, isRoomAlias } from '../../../utils/matrix';

const safeDecode = (raw: string): string | undefined => {
  try {
    return decodeURIComponent(raw);
  } catch {
    return undefined;
  }
};

// Resolves the active Space for the channels segment. Priority:
//   1. URL `:spaceIdOrAlias` param (if joined-orphan)
//   2. `activeChannelsSpaceAtom` (= localStorage, reactive) (if joined-orphan)
//   3. first joined-orphan Space
// Returns undefined when the user has 0 joined orphan spaces. Persistence
// (writing the atom) lives in `Channels.tsx`, where the inner route
// already has the resolved space context — at the index `/channels/`
// route, useParams().spaceIdOrAlias is always undefined.
//
// The persisted value is read via Jotai so writes from `Channels.tsx`
// immediately invalidate every consumer (notably `MobileTabsPager`,
// which stays mounted across tab swipes and would otherwise serve a
// stale cached value to its `destinationFor('channels')`).
export const useActiveSpace = (orphanSpaceIds: string[]): string | undefined => {
  const mx = useMatrixClient();
  const { spaceIdOrAlias } = useParams();
  const orphanSet = useMemo(() => new Set(orphanSpaceIds), [orphanSpaceIds]);
  const persisted = useAtomValue(activeChannelsSpaceAtom);

  const urlSpaceId = useMemo(() => {
    if (!spaceIdOrAlias) return undefined;
    const decoded = safeDecode(spaceIdOrAlias);
    if (!decoded) return undefined;
    const resolved = isRoomAlias(decoded) ? getCanonicalAliasRoomId(mx, decoded) : decoded;
    return resolved && orphanSet.has(resolved) ? resolved : undefined;
  }, [mx, spaceIdOrAlias, orphanSet]);

  const persistedSpaceId = useMemo(
    () => (persisted && orphanSet.has(persisted) ? persisted : undefined),
    [persisted, orphanSet]
  );

  return urlSpaceId ?? persistedSpaceId ?? orphanSpaceIds[0];
};
