// app/dashboard/page.tsx
// Dashboard - now with auto-refresh!

import { query } from '@/lib/db';
import { LiveDotIcon } from '@/components/ui/icons';
import DashboardClient from '@/components/dashboard/DashboardClient';
export const dynamic = "force-dynamic";

async function getConnectedDrivers() {
  const sql = `
    SELECT 
      u.driver_guid,
      u.driver_name,
      u.driver_team,
      u.car_model,
      u.car_skin,
      u.user_rank,
      u.laps_completed,
      s.server_id,
      s.server_name,
      s.server_track,
      s.server_config,
      s.session_type,
      s.session_flag,
      s.session_time,
      s.session_laps,
      s.session_elapsed_time,
      s.session_ambient_temp,
      s.session_road_temp,
      s.connected_players
    FROM users u
    INNER JOIN servers s ON u.current_server = s.server_id
    WHERE u.is_connect = true
    ORDER BY s.server_id, u.user_rank ASC
  `;

  const rows = await query(sql);

  return rows.map((row: unknown) => ({
    driver_guid: row.driver_guid,
    driver_name: row.driver_name,
    driver_team: row.driver_team,
    car_model: row.car_model,
    car_skin: row.car_skin,
    laps_completed: row.laps_completed,
    user_rank: row.user_rank,
    server: {
      server_id: row.server_id,
      server_name: row.server_name,
      server_track: row.server_track,
      server_config: row.server_config,
      session_type: row.session_type,
      session_flag: row.session_flag,
      session_time: row.session_time,
      session_laps: row.session_laps,
      session_elapsed_time: row.session_elapsed_time,
      session_ambient_temp: row.session_ambient_temp,
      session_road_temp: row.session_road_temp,
      connected_players: row.connected_players,
    },
  }));
}

export default async function DashboardPage() {
  const initialDrivers = await getConnectedDrivers();

  return (
    <>
      {/* Hero */}
      <div className="relative border-b border-white/10 grid-overlay">
        <div className="max-w-7xl mx-auto px-6 py-16">
          <div className="space-y-4">
            <div className="inline-flex items-center space-x-2 px-3 py-1 border border-white/20">
              <LiveDotIcon className="w-2 h-2 text-white animate-pulse" />
              <span className="text-xs font-medium tracking-wider">LIVE SYSTEM</span>
            </div>
            <h1 className="text-6xl font-bold tracking-tight">
              LIVE DASHBOARD
            </h1>
            <p className="text-white/60 text-lg max-w-2xl">
              Real-time telemetry and session monitoring across all OpenWheels Racing infrastructure
            </p>
          </div>

          {/* Client component with auto-refresh */}
          <DashboardClient initialDrivers={initialDrivers} />
        </div>
      </div>
    </>
  );
}
