// components/CourseDetailPage.jsx

/**
 * Course Detail Page Component
 *
 * Fetches and displays detailed information for a single course,
 * including overview, curriculum, instructor details, reviews,
 * and related courses. Uses tabs for content organization.
 */

// React, Hooks, PropTypes are globally available

function CourseDetailPage({ courseId }) {
  // --- State ---
  const [course, setCourse] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [activeTab, setActiveTab] = useState("overview"); // Default tab

  // --- API Endpoint ---
  const COURSE_DETAIL_ENDPOINT = "/api/get_course_detail.php";

  // --- Effects ---
  // Fetch course details when courseId changes
  useEffect(() => {
    const fetchCourse = async () => {
      // Reset state for new fetch
      setLoading(true);
      setError(null);
      setCourse(null);
      setActiveTab("overview"); // Reset tab on new course load

      // Ensure courseId is a valid number before proceeding
      const numericCourseId = parseInt(courseId, 10);
      if (isNaN(numericCourseId) || numericCourseId <= 0) {
          setError("Invalid Course ID provided.");
          setLoading(false);
          console.error("CourseDetailPage: Invalid courseId prop received:", courseId);
          return;
      }

      console.log(`CourseDetailPage: Fetching details for course ID: ${numericCourseId}`);

      try {
        const response = await fetch(`${COURSE_DETAIL_ENDPOINT}?id=${numericCourseId}`);

        // Check for network or server errors (non-2xx status)
        if (!response.ok) {
          let errorMsg = `HTTP error! Status: ${response.status}`;
          try {
            // Try to parse JSON error from backend
            const errData = await response.json();
            errorMsg = errData.error || errorMsg;
          } catch (e) { /* Ignore parsing error if body isn't JSON */ }
          throw new Error(errorMsg);
        }

        const data = await response.json();

        // Check for application-level errors (e.g., { success: false, error: '...' })
        if (!data.success) {
          // Handle specific "Not Found" error from API
          if (response.status === 404 || data.error?.toLowerCase().includes('not found')) {
              throw new Error(`Course with ID ${numericCourseId} not found.`);
          }
          throw new Error(data.error || "Failed to fetch course details");
        }

        console.log("CourseDetailPage: Course details fetched:", data.data);
        setCourse(data.data); // Set the fetched course data

      } catch (err) {
        console.error("CourseDetailPage: Error fetching course details:", err);
        setError(err.message); // Set error state to display message
      } finally {
        setLoading(false); // Ensure loading state is turned off
      }
    };

    fetchCourse();

    // Scroll to top when courseId changes for better UX
    window.scrollTo(0, 0);

  }, [courseId]); // Re-run effect if courseId changes

  // --- Helper Functions ---

  // Safely splits text by newline, handling null/undefined input and trimming lines
  const splitLines = (text) => {
    return text ? text.split('\n').map(line => line.trim()).filter(line => line !== '') : [];
  };

  // Renders star ratings using Font Awesome icons
  const renderStars = (rating) => {
    const numRating = parseFloat(rating) || 0;
    const fullStars = Math.floor(numRating);
    // Use Math.round to decide half star more conventionally
    const halfStar = Math.round(numRating - fullStars) === 1 ? 1 : 0;
    // Correct calculation for empty stars
    const emptyStars = 5 - fullStars - halfStar;
    return (
      <>
        {/* Render full stars */}
        {fullStars > 0 && Array(fullStars).fill(null).map((_, i) => <i key={`fs-${i}`} className="fas fa-star"></i>)}
        {/* Render half star */}
        {halfStar > 0 && <i key="hs" className="fas fa-star-half-alt"></i>}
        {/* Render empty stars */}
        {emptyStars > 0 && Array(emptyStars).fill(null).map((_, i) => <i key={`es-${i}`} className="far fa-star"></i>)}
      </>
    );
  };

  // Handles image loading errors for various images on the page
   const handleImageError = (e, placeholderType = 'course') => {
    e.target.onerror = null; // Prevent infinite loop
    let placeholderUrl = 'https://via.placeholder.com/400x225?text=No+Image'; // Default
    if (placeholderType === 'instructor') {
        placeholderUrl = 'https://via.placeholder.com/100?text=Inst';
    } else if (placeholderType === 'user') {
        placeholderUrl = 'https://via.placeholder.com/50?text=User';
    } else if (placeholderType === 'related') {
         placeholderUrl = 'https://via.placeholder.com/300x150?text=Related';
    }
    e.target.src = placeholderUrl;
  };


  // --- Render Logic ---

  // Loading State
  if (loading) {
    return <div className="status-message loading">Loading course details...</div>;
  }

  // Error State
  if (error) {
    return (
      <div className="status-message error">
        <h2>Error Loading Course</h2>
        <p>{error}</p>
        {/* Provide a way back */}
        <a href="#/" className="button-link button-secondary">Back to Courses</a>
      </div>
    );
  }

  // Course Not Found (Should be caught by error state now, but keep as fallback)
  if (!course) {
    return (
      <div className="status-message error">
        <h2>Course Not Found</h2>
        <p>The requested course could not be found.</p>
        <a href="#/" className="button-link button-secondary">Back to Courses</a>
      </div>
    );
  }

  // --- Tab Content Rendering ---
  const renderTabContent = () => {
    switch (activeTab) {
      case "overview":
        return (
          <div className="overview-section tab-pane active" id="tab-panel-overview" role="tabpanel" aria-labelledby="tab-overview">
            <h2>What you'll learn</h2>
            {course.learning_objectives && splitLines(course.learning_objectives).length > 0 ? (
              <ul className="learning-objectives">
                {splitLines(course.learning_objectives).map((objective, index) => (
                  <li key={`learn-${index}`}>{objective}</li>
                ))}
              </ul>
            ) : <p>Learning objectives not specified for this course.</p>}

            <h2>Requirements</h2>
            {course.requirements && splitLines(course.requirements).length > 0 ? (
              <ul className="requirements">
                {splitLines(course.requirements).map((req, index) => (
                  <li key={`req-${index}`}>{req}</li>
                ))}
              </ul>
            ) : <p>No specific prerequisites or requirements listed.</p>}

            <h2>Description</h2>
            <div className="detailed-description">
              {/* Render description safely. If it contains HTML, use a sanitizer or render plain text */}
              <p>{course.detailed_description || course.description || "No detailed description available."}</p>
            </div>
          </div>
        );

      case "curriculum":
        return (
          <div className="curriculum-section tab-pane active" id="tab-panel-curriculum" role="tabpanel" aria-labelledby="tab-curriculum">
            <h2>Course Curriculum</h2>
            {course.modules && course.modules.length > 0 ? (
              <div className="modules-accordion">
                {course.modules.map((module) => (
                  <details key={module.id} className="module-item">
                    <summary className="module-title">{module.title || `Module ${module.order_index}`}</summary>
                    <div className="module-content">
                      {module.lessons && module.lessons.length > 0 ? (
                        <ul className="lessons-list">
                          {module.lessons.map((lesson) => (
                            <li key={lesson.id} className="lesson-item">
                              {/* Choose icon based on content type */}
                              <i className={`fas fa-${
                                  lesson.content_type === 'video' ? 'play-circle' :
                                  lesson.content_type === 'quiz' ? 'question-circle' :
                                  lesson.content_type === 'assignment' ? 'file-signature' :
                                  'file-alt' // Default for text/link
                                 } lesson-icon`}></i>
                              <span className="lesson-title">{lesson.title || "Untitled Lesson"}</span>
                              {/* Display preview tag if applicable */}
                              {lesson.is_preview ? <span className="preview-tag">Preview</span> : null}
                              {lesson.duration_minutes > 0 && ( // Only show duration if > 0
                                <span className="lesson-duration">{lesson.duration_minutes} min</span>
                              )}
                            </li>
                          ))}
                        </ul>
                      ) : <p className="no-lessons">No lessons listed in this module.</p>}
                    </div>
                  </details>
                ))}
              </div>
            ) : <p>Curriculum details are not available for this course.</p>}
          </div>
        );

      case "instructor":
        return (
          <div className="instructor-section tab-pane active" id="tab-panel-instructor" role="tabpanel" aria-labelledby="tab-instructor">
            <h2>Instructor</h2>
            {course.instructor_name ? (
              <div className="instructor-profile">
                <div className="instructor-avatar">
                  <img
                    src={course.instructor_photo || 'https://via.placeholder.com/100?text=Inst'}
                    alt={course.instructor_name}
                    onError={(e) => handleImageError(e, 'instructor')}
                  />
                </div>
                <div className="instructor-details">
                  <h3>{course.instructor_name}</h3>
                  {course.instructor_title && <p className="instructor-title">{course.instructor_title}</p>}
                  <div className="instructor-rating" title={`Instructor Rating: ${course.instructor_rating?.toFixed(1) || 0}/5`}>
                    {renderStars(course.instructor_rating)}
                    <span className="rating-count"> ({course.instructor_total_ratings || 0} ratings)</span>
                  </div>
                  {course.instructor_bio ? (
                     <p className="instructor-bio">{course.instructor_bio}</p>
                  ) : (
                     <p className="instructor-bio">No biography available for this instructor.</p>
                  )}
                </div>
              </div>
            ) : <p>Instructor information is not available for this course.</p>}
          </div>
        );

      case "reviews":
        return (
          <div className="reviews-section tab-pane active" id="tab-panel-reviews" role="tabpanel" aria-labelledby="tab-reviews">
            <h2>Student Reviews ({course.reviews?.length || 0})</h2>
            {course.reviews && course.reviews.length > 0 ? (
              <div className="reviews-list">
                {course.reviews.map((review) => (
                  <div key={review.id} className="review-item">
                    <div className="review-header">
                       <div className="reviewer-avatar">
                         <img
                           src={review.profile_picture || 'https://via.placeholder.com/50?text=User'}
                           alt={review.full_name || review.username}
                           onError={(e) => handleImageError(e, 'user')}
                         />
                       </div>
                       <div className="reviewer-info">
                         <h4>{review.full_name || review.username || "Anonymous"}</h4>
                         <div className="review-meta">
                            <span className="review-rating" title={`Rated ${review.rating} out of 5`}>{renderStars(review.rating)}</span>
                            <span className="review-date">
                              {new Date(review.created_at).toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' })}
                            </span>
                         </div>
                       </div>
                    </div>
                    {review.content ? (
                       <p className="review-content">{review.content}</p>
                    ) : (
                       <p className="review-content italic">No comment provided.</p>
                    )}
                  </div>
                ))}
              </div>
            ) : <p>Be the first to review this course!</p>}
            {/* TODO: Add a "Write a Review" button/form here if user is enrolled and hasn't reviewed */}
          </div>
        );

      default:
        return null; // Should not happen
    }
  };

  // --- Main Course Detail Render ---
  return (
    <div className="course-detail-page">
      {/* --- Course Header Section --- */}
      <section className="course-detail-header-section">
          <div className="course-detail-header-content container">
              <div className="course-detail-info">
                <h1 className="course-main-title">{course.title}</h1>
                <p className="course-short-description">{course.description}</p>
                <div className="course-detail-meta">
                  <span className="rating" title={`Average Rating: ${course.rating?.toFixed(1) || 0}/5`}>
                    {renderStars(course.rating)} ({course.total_ratings || 0} ratings)
                  </span>
                  <span className="enrollment">
                    <i className="fas fa-users"></i> {course.enrollment_count || 0} students
                  </span>
                  <span className="level">
                    <i className="fas fa-signal"></i> {course.level || 'N/A'}
                  </span>
                   <span className="instructor-meta">
                     Created by: {course.instructor_name || 'Unknown'} {/* TODO: Link to instructor profile page if exists */}
                   </span>
                </div>
                <div className="course-actions">
                  {/* TODO: Add logic based on enrollment status */}
                  <button className="button-primary enroll-button">Enroll Now ({course.price > 0 ? `$${course.price.toFixed(2)}` : 'Free'})</button>
                  <button className="button-secondary wishlist-button">
                    <i className="far fa-heart"></i> Add to Wishlist
                  </button>
                </div>
              </div>
              <div className="course-detail-image">
                <img
                  src={course.image_url || 'https://via.placeholder.com/400x225?text=Course+Image'}
                  alt={course.title} // Add alt text
                  onError={(e) => handleImageError(e, 'course')}
                 />
              </div>
          </div>
      </section>

      {/* --- Course Content Section (Tabs) --- */}
      <section className="course-detail-content-section container">
        <div className="course-tabs" role="tablist" aria-label="Course Sections">
          {/* Tab Buttons */}
          {['overview', 'curriculum', 'instructor', 'reviews'].map(tabName => (
             <button
               key={tabName}
               id={`tab-${tabName}`} // ID for aria-labelledby
               className={`tab-button ${activeTab === tabName ? 'active' : ''}`}
               onClick={() => setActiveTab(tabName)}
               aria-controls={`tab-panel-${tabName}`}
               role="tab"
               aria-selected={activeTab === tabName}
             >
               {/* Capitalize first letter */}
               {tabName.charAt(0).toUpperCase() + tabName.slice(1)}
             </button>
          ))}
        </div>

        {/* Tab Panels */}
        <div className="tab-content-container">
           {/* Render the active tab's content */}
           {renderTabContent()}
        </div>
      </section>

      {/* --- Related Courses Section --- */}
      {course.related_courses && course.related_courses.length > 0 && (
        <section className="related-courses-section container">
          <h2>Related Courses</h2>
          {/* Use the CourseList component if suitable, or render cards directly */}
          <div className="course-list related-list">
            {course.related_courses.map((relatedCourse) => (
              // Use CourseCard component if available and suitable
              window.CourseCard ? (
                 <a key={relatedCourse.id} href={`#course/${relatedCourse.id}`} className="course-card-link">
                    <window.CourseCard course={relatedCourse} />
                 </a>
              ) : (
                 // Fallback direct render (should not be needed if CourseCard loads)
                 <a key={relatedCourse.id} href={`#course/${relatedCourse.id}`} className="course-card-link">
                    <article className="course-item">
                      <img src={relatedCourse.image_url || 'https://via.placeholder.com/300x150?text=Related'} alt={relatedCourse.title} onError={(e) => handleImageError(e, 'related')} />
                      <div className="course-item-content">
                        <h3>{relatedCourse.title}</h3>
                        <p className="course-category">{relatedCourse.category}</p>
                        {/* Add rating/instructor if available in related data */}
                      </div>
                    </article>
                 </a>
              )
            ))}
          </div>
        </section>
      )}
    </div>
  );
}

// --- Prop Type Validation ---
CourseDetailPage.propTypes = {
  // Expects a courseId prop, which should be a string (from hash) or number
  courseId: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired,
};

// Make CourseDetailPage globally available
window.CourseDetailPage = CourseDetailPage;
