import { useEffect, useRef, useState } from "react";
import { Button, Text, View } from "react-native";
import { DataNet } from "@sjs/sdk";

const CHANNEL = "demo.json.state";

export function StateSyncScreen({ apiKey }: { apiKey: string }) {
  const clientRef = useRef<DataNet | null>(null);
  const [mode, setMode] = useState("idle");

  useEffect(() => {
    const client = new DataNet({
      apiKey,
      clientId: "react-native-demo",
      deviceName: "React Native Demo",
    });
    clientRef.current = client;
    client.subscribe(CHANNEL, (data) => {
      const next = data as { mode?: string };
      if (next.mode) setMode(next.mode);
    });
    void client.connect();
    return () => client.disconnect();
  }, [apiKey]);

  return (
    <View style={{ padding: 24, gap: 12 }}>
      <Text>React Native state sync</Text>
      <Text>Channel: {CHANNEL}</Text>
      <Text>Mode: {mode}</Text>
      <Button
        title="Publish active"
        onPress={() => clientRef.current?.publish(CHANNEL, { mode: "active", source: "react-native-demo" })}
      />
    </View>
  );
}
