// import { useSearchParams } from "react-router-dom";
// import JitsiMeeting from "../components/JitsiMeeting";

// const MeetingPage = () => {
//   const [params] = useSearchParams();
//   const room = params.get("room");
//   const name = params.get("name");

//   if (!room) return <div>Missing meeting details</div>;

//   return (
//     <div style={{ height: "100vh", width: "100vw" }}>
//       <JitsiMeeting roomName={room} displayName={name} />
//     </div>
//   );
// };

// export default MeetingPage;

// src/pages/MeetingPage.jsx - Meeting validation and loading
import React, { useState, useEffect } from "react";
import { useSearchParams } from "react-router-dom";
import axios from "../config/axiosInstance";
import JitsiMeeting from "../components/JitsiMeeting";
import "./MeetingPage.css";

const MeetingPage = () => {
  const [params] = useSearchParams();
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [meetingData, setMeetingData] = useState(null);

  const room = params.get("room");
  const name = params.get("name");
  // const token = params.get("token");
  const role = params.get("role");
  console.log("Meeting params:", { room, name, role });
  const token = sessionStorage.getItem("meetingToken");
  console.log("Meeting token from session:", token);
  const storedRole = sessionStorage.getItem("meetingRole");
  useEffect(() => {
    if (!room || !token) {
      setError("Invalid meeting link - missing room or authentication");
      setLoading(false);
      return;
    }

    validateMeeting();
  }, [room, token]);

  const validateMeeting = async () => {
    try {
      const response = await axios.post("/meetings/validate", {
        roomId: room,
        token: token,
      });

      if (response.data.success) {
        setMeetingData(response.data.data);
        setLoading(false);
      } else {
        setError(response.data.message || "Access denied");
      }
    } catch (error) {
      console.error("Meeting validation error:", error);
      if (error.response?.status === 410) {
        setError("This meeting has expired");
      } else if (error.response?.status === 403) {
        setError("Invalid or expired access token");
      } else {
        setError("Unable to join meeting. Please check your link.");
      }
      setLoading(false);
    }
  };

  if (loading) {
    return (
      <div className="meeting-loading">
        <div className="loading-spinner"></div>
        <h2>🔐 Validating access...</h2>
        <p>Checking your meeting invitation</p>
      </div>
    );
  }

  if (error) {
    return (
      <div className="meeting-error">
        <div className="error-content">
          <h2>❌ Unable to Join Meeting</h2>
          <p>{error}</p>
          <button onClick={() => window.close()} className="btn-close">
            Close Window
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="meeting-page">
      {/* Meeting Header */}
      <div className="meeting-page-header">
        <h3>🎥 {meetingData?.roomName || "Video Meeting"}</h3>
        <div className="meeting-info">
          <span>📋 Host: {meetingData?.ownerName}</span>
          {role === "moderator" && (
            <span className="moderator-badge">🔑 Moderator</span>
          )}
          {role === "participant" && (
            <span className="participant-badge">👤 Participant</span>
          )}
        </div>
      </div>

      {/* Jitsi Meeting Container */}
      <div className="jitsi-container">
        <JitsiMeeting
          roomName={room}
          displayName={name || "Guest"}
          token={token}
          role={role}
          meetingData={meetingData}
        />
      </div>
    </div>
  );
};

export default MeetingPage;
