import { createContext, useContext } from "react";
import { type Todo, useTodos } from "./useTodos";

type TodosContextValue = ReturnType<typeof useTodos>;

const TodosContext = createContext<TodosContextValue | null>(null);

export function TodosProvider({ children }: { children: React.ReactNode }) {
  const store = useTodos();
  return (
    <TodosContext.Provider value={store}>{children}</TodosContext.Provider>
  );
}

export function useTodosCtx(): TodosContextValue {
  const ctx = useContext(TodosContext);
  if (!ctx) {
    throw new Error("use TodosCtx must be used within <TodosProvider>");
  }
  return ctx;
}

export type { Todo };
