// @ts-expect-error We're calling an ESM from CJS, but it's fine as it's just for types purpose
import type { Key, StdoutProps, Box as BoxType, Text as TextType } from "ink";
import React, { useEffect, useState } from "react";

// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore We're calling an ESM from CJS, but it's fine as it's just for types purpose
const ink = import("ink");

export const Box = (props: React.ComponentProps<typeof BoxType>) => {
  const [Box, setBox] = useState<null | typeof BoxType>(null);

  useEffect(() => {
    ink.then(({ Box }) => setBox(() => Box));
  }, []);

  return Box ? <Box {...props} /> : <></>;
};

export const Text = (props: React.ComponentProps<typeof TextType>) => {
  const [Text, setText] = useState<null | typeof TextType>(null);

  useEffect(() => {
    ink.then(({ Text }) => setText(() => Text));
  }, []);

  return Text ? <Text {...props} /> : <></>;
};

export const render = async (node: React.JSX.Element) => {
  const { render } = await ink;

  render(node);
};

export type UseStdout = () => StdoutProps;

export type UseInput = (
  inputHandler: (input: string, key: Key) => void,
) => void;
