import React from "react";
import ReactDOM from "react-dom/client";
import { createBrowserRouter, RouterProvider } from "react-router-dom";
import BrowseRoute from "./routes/BrowseRoute";
import SettingsRoute from "./routes/SettingsRoute";
import MapRoute from "./routes/MapRoute";
import StatisticsRoute from "./routes/StatisticsRoute";
import CableDetailRoute from "./routes/CableDetailRoute";

// Root
const root = ReactDOM.createRoot(document.getElementById("root"));

// Socket handler
console.log("Connecting to WebSocket server.");
const hostname = window.location.hostname;  // Get the hostname from the URL bar
const wsPort = "9000";
const socket = new WebSocket(`ws://${hostname}:${wsPort}`);
socket.addEventListener("open", function (event) {
  console.log("Websocket connected.");
  console.log("Welcome to Belden Jukebox!");
  init();
});

// Initialize the app
const init = () => {
  const router = createBrowserRouter([
    {
      path: "/",
      element: <BrowseRoute socket={socket}></BrowseRoute>,
      // errorElement: <ErrorRoute></ErrorRoute>,
    },
    {
      path: "/browse",
      element: <BrowseRoute socket={socket}></BrowseRoute>,
      // errorElement: <ErrorRoute></ErrorRoute>,
    },
    {
      path: "/settings",
      element: <SettingsRoute socket={socket}></SettingsRoute>,
      // errorElement: <ErrorRoute></ErrorRoute>,
    },
    {
      path: "/map",
      element: <MapRoute socket={socket}></MapRoute>,
      // errorElement: <ErrorRoute></ErrorRoute>,
    },
    {
      path: "/statistics",
      element: <StatisticsRoute socket={socket}></StatisticsRoute>,
      // errorElement: <ErrorRoute></ErrorRoute>,
    },
    {
      path: "/browse/cable/:cablePos",
      element: <CableDetailRoute socket={socket} />,
      // errorElement: <ErrorRoute></ErrorRoute>,
    },
    {
      path: "/map/cable/:cablePos",
      element: <CableDetailRoute socket={socket} />,
      // errorElement: <ErrorRoute></ErrorRoute>,
    },
  ]);

  root.render(
    <div>
      <RouterProvider router={router} />
    </div>
  );
};
