"use client";
// PLACE AT: app/(dashboard)/modules/meetings/room/[code]/page.tsx
// Shows the pre-join screen (device picker + preview) BEFORE entering the meeting.
import { useParams, useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import MeetingRoom from "@/components/meeting/MeetingRoom";
import PreJoin, { PreJoinResult } from "@/components/meeting/PreJoin";
import { makeMeetingApi } from "@/lib/api/meeting.api";

const SOCKET_URL = (process.env.NEXT_PUBLIC_API_URL || "").replace(/\/api\/?$/, "");
const getStaffToken = () => typeof window !== "undefined" ? localStorage.getItem("access_token") || "" : "";

export default function StaffMeetingRoomPage() {
  const { code } = useParams<{ code: string }>();
  const router = useRouter();
  const [ice, setIce] = useState<RTCIceServer[] | null>(null);
  const [meetingId, setMeetingId] = useState<number | undefined>(undefined);
  const [choice, setChoice] = useState<PreJoinResult | null>(null);

  useEffect(() => {
    const api = makeMeetingApi({ getToken: getStaffToken });
    api.getTurnCredentials().then(setIce).catch(() => setIce([{ urls: "stun:stun.l.google.com:19302" }]));
    api.getByCode(code).then((res: any) => { const m = res?.data ?? res; if (m?.id) setMeetingId(Number(m.id)); }).catch(() => {});
  }, [code]);

  // Step 1 — pre-join screen
  if (!choice) {
    return (
      <PreJoin
        title="Ready to join?"
        roomCode={code}
        defaultName="Auditor"
        onJoin={setChoice}
        onCancel={() => router.push("/modules/meetings")}
      />
    );
  }

  if (!ice) return <div style={{ padding: 40, textAlign: "center" }}>Preparing meeting…</div>;

  // Step 2 — the meeting, using the chosen devices
  return (
    <MeetingRoom
      socketUrl={SOCKET_URL}
      roomId={code}
      token={getStaffToken()}
      displayName={choice.displayName || "Auditor"}
      role="auditor"
      iceServers={ice}
      title="Audit meeting"
      meetingId={meetingId}
      getToken={getStaffToken}
      audioDeviceId={choice.audioDeviceId}
      videoDeviceId={choice.videoDeviceId}
      startMuted={!choice.micOn}
      startCamOff={!choice.camOn}
      onLeave={() => router.push("/modules/meetings")}
    />
  );
}
