import * as React from "react";

import { isTV } from "@applicaster/zapp-react-native-utils/reactUtils";
import { usePathname } from "@applicaster/zapp-react-native-utils/reactHooks/navigation/usePathname";
import { useRivers } from "@applicaster/zapp-react-native-utils/reactHooks";

type Props = ZappUIComponentProps & {
  rivers: ZappRivers;
  screenId: string;
  screenData?: ZappRivers;
};

export function withRiver(Component: ZappComponent): ZappComponent {
  const RiverWithData = ({ screenId, ...otherProps }: Props) => {
    const river = useRivers()?.[screenId];
    const pathname = usePathname();

    if (!river) {
      return null;
    }

    return (
      <Component
        screenId={screenId}
        river={river}
        key={isTV() ? pathname : undefined}
        {...otherProps}
        screenData={otherProps.screenData || river}
      />
    );
  };

  RiverWithData.displayName = `RiverWithData(${Component.displayName || Component.name})`;

  return RiverWithData;
}
