/* eslint-disable no-console */
import React from "react";
import { render, screen } from "@testing-library/react-native";
import { Text } from "react-native";
import { useZStore, ZStoreProvider } from "../ZStoreProvider";
import { useStore } from "zustand";

interface TestState {
  value: string;
}

// Test component that uses the store
const TestComponent = ({ storeName }: { storeName: string }) => {
  const store = useZStore(storeName);
  const value = useStore(store, (state: any) => (state as TestState).value);

  return <Text testID="test-value">{value}</Text>;
};

// Test component that provides a store
const TestProvider = ({ children }: { children: React.ReactNode }) => {
  return (
    <ZStoreProvider name="testStore" value={{ value: "test-value" }}>
      {children}
    </ZStoreProvider>
  );
};

describe("ZStoreProvider and useZStore", () => {
  it("should provide a store and allow access via useZStore", () => {
    render(
      <TestProvider>
        <TestComponent storeName="testStore" />
      </TestProvider>
    );

    expect(screen.getByTestId("test-value").props.children).toBe("test-value");
  });

  it("should throw error when useZStore is used outside provider", () => {
    // Suppress console.error for this test
    const originalError = console.error;
    console.error = jest.fn();

    expect(() => {
      render(<TestComponent storeName="testStore" />);
    }).toThrow("useZStore must be used within a ZStoreProvider");

    console.error = originalError;
  });

  it("should throw error when store name is not found", () => {
    // Suppress console.error for this test
    const originalError = console.error;
    console.error = jest.fn();

    expect(() => {
      render(
        <TestProvider>
          <TestComponent storeName="nonExistentStore" />
        </TestProvider>
      );
    }).toThrow('Store with name "nonExistentStore" not found');

    console.error = originalError;
  });
});
