"use client";

import { useEffect, useMemo, useState } from "react";
import { useRouter } from "next/navigation";

import StartConsultationModal from "@/app/components/consultation/StartConsultationModal";

import "./astrologer-profile.css";

interface Astrologer {
  id: number;
  name: string;
  profileImage: string;
  charge: number;
  audioCallRate: number;
  videoCallRate: number;
  reportRate: number;
  experience: number;
  primarySkill: string;
  allSkill: string;
  languageKnown: string;
  category: string;
  rating: number;
  ratingCount: number;
  chatMinutes: number;
  callMinutes: number;
  isFreeAvailable: boolean;
  isFollowing: boolean;

  // Optional future API fields
  about?: string;
  gallery?: string[];
  isVerified?: boolean;

  // Confirmed real fields on the astrologer LIST endpoint
  // (POST /user/astrologers/list) — the richer getAstrologerById
  // response this page mainly renders from isn't confirmed to also
  // carry them, so fetchAstrologer() below merges these in from the
  // list lookup it already does to find this astrologer by slug.
  isOnline?: boolean;
  isBusy?: boolean;
}

interface Review {
  id: number;
  userId: number;
  astrologerId: number;
  name: string;
  profile: string;
  profileImage: string;
  rating: number;
  review: string;
  reply: string;
  isPublic: boolean;
  created_at: string;
}

interface Props {
  slug: string;
}

/*
 * ----------------------------------------------------
 * CREATE SLUG
 * ----------------------------------------------------
 */
function createSlug(name: string) {
  return name
    .toLowerCase()
    .trim()
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/^-+|-+$/g, "");
}

export default function AstrologerProfileClient({
  slug,
}: Props) {
  const router = useRouter();

  const [astrologer, setAstrologer] =
    useState<Astrologer | null>(null);

  const [reviews, setReviews] =
    useState<Review[]>([]);

  const [loading, setLoading] =
    useState(true);

  const [reviewLoading, setReviewLoading] =
    useState(true);

  const [showMoreAbout, setShowMoreAbout] =
    useState(false);

  const [showAllReviews, setShowAllReviews] =
    useState(false);

  const [error, setError] =
    useState("");

  /*
   * ----------------------------------------------------
   * CONSULTATION MODAL
   * ----------------------------------------------------
   *
   * CHAT  => medium="CHAT"
   * CALL  => medium="AUDIO"
   */
  const [showConsultationModal, setShowConsultationModal] =
    useState(false);

  const [consultationMedium, setConsultationMedium] =
    useState<"CHAT" | "AUDIO">("CHAT");

  // Live-confirmed via /precheck at click time — overrides the list's
  // own (sometimes stale) isOnline/isBusy fields once known, matching
  // AstrologerCard.tsx's identical pattern (see CLAUDE.md's Chat/Call
  // consultations section).
  const [liveStatus, setLiveStatus] =
    useState<"BUSY" | "OFFLINE" | null>(null);

  /*
  * ----------------------------------------------------
  * FOLLOW / UNFOLLOW
  * ----------------------------------------------------
  */
  const [showProfileMenu, setShowProfileMenu] =
    useState(false);

  const [showUnfollowModal, setShowUnfollowModal] =
    useState(false);

  const [followLoading, setFollowLoading] =
    useState(false);

  /*
   * ----------------------------------------------------
   * TOKEN
   * ----------------------------------------------------
   */
  const getToken = () => {
    if (typeof window === "undefined") return "";

    return (
      localStorage.getItem("token") ||
      localStorage.getItem("access_token") ||
      localStorage.getItem("user_token") ||
      ""
    );
  };

  /*
   * ----------------------------------------------------
   * ONLINE / BUSY / OFFLINE
   * ----------------------------------------------------
   *
   * Same three-state derivation as AstrologerCard.tsx (dashboard/
   * talk-to-astrologer): precheck (via StartConsultationModal's
   * onUnavailable callback below) is the live authority once known,
   * the list endpoint's isOnline/isBusy are just the fast fallback
   * hint shown before any click happens.
   */
  const isOffline =
    liveStatus === "OFFLINE" || (!liveStatus && !astrologer?.isOnline);
  const isBusy =
    liveStatus === "BUSY" || (!liveStatus && !!astrologer?.isOnline && !!astrologer?.isBusy);
  const isAvailable = !isOffline && !isBusy;

  const actionButtonLabel = (verb: "Chat" | "Call") =>
    isAvailable ? `${verb} now` : isBusy ? "Busy" : "Offline";

  const actionButtonTitle = isAvailable
    ? ""
    : isBusy
      ? "Busy with another consultation — join the waiting queue"
      : "This astrologer is currently offline";

  const actionButtonStyle: React.CSSProperties = isAvailable
    ? {}
    : {
        background: "transparent",
        color: isBusy ? "#EF4444" : "#7E775F",
        borderColor: isBusy ? "#EF4444" : "#7E775F",
      };

  /*
   * ----------------------------------------------------
   * CHAT BUTTON
   * ----------------------------------------------------
   */
  const handleChatClick = () => {
    if (!astrologer || isOffline) return;

    setConsultationMedium("CHAT");
    setShowConsultationModal(true);
  };

  /*
   * ----------------------------------------------------
   * CALL BUTTON
   * ----------------------------------------------------
   */
  const handleCallClick = () => {
    if (!astrologer || isOffline) return;

    setConsultationMedium("AUDIO");
    setShowConsultationModal(true);
  };

  /*
   * ----------------------------------------------------
   * CLOSE CONSULTATION MODAL
   * ----------------------------------------------------
   */
  const handleCloseConsultationModal = () => {
    setShowConsultationModal(false);
  };
  /*
  * ----------------------------------------------------
  * FOLLOW ASTROLOGER
  * ----------------------------------------------------
  */
  const handleFollow = async () => {
    if (!astrologer) return;

    try {
      setFollowLoading(true);

      const token = getToken();

      if (!token) {
        router.push("/signin");
        return;
      }

      const response = await fetch(
        "/api/astrologers/follow",
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${token}`,
          },
          body: JSON.stringify({
            astrologerId: astrologer.id,
          }),
        }
      );

      const text = await response.text();

      let data: any;

      try {
        data = JSON.parse(text);
      } catch {
        throw new Error(
          "Invalid response from follow API"
        );
      }

      if (!response.ok) {
        throw new Error(
          data?.message ||
            "Unable to follow astrologer"
        );
      }

      /*
      * API success
      */
      setAstrologer((previous) =>
        previous
          ? {
              ...previous,
              isFollowing: true,
            }
          : previous
      );

      setShowProfileMenu(false);

    } catch (error: any) {
      console.error(
        "Follow astrologer error:",
        error
      );

      alert(
        error?.message ||
          "Unable to follow astrologer"
      );
    } finally {
      setFollowLoading(false);
    }
  };
  /*
  * ----------------------------------------------------
  * UNFOLLOW ASTROLOGER
  * ----------------------------------------------------
  */
  const handleUnfollow = async () => {
    if (!astrologer) return;

    try {
      setFollowLoading(true);

      const token = getToken();

      if (!token) {
        router.push("/signin");
        return;
      }

      const response = await fetch(
        "/api/astrologers/unfollow",
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${token}`,
          },
          body: JSON.stringify({
            astrologerId: astrologer.id,
          }),
        }
      );

      const text = await response.text();

      let data: any;

      try {
        data = JSON.parse(text);
      } catch {
        throw new Error(
          "Invalid response from unfollow API"
        );
      }

      if (!response.ok) {
        throw new Error(
          data?.message ||
            "Unable to unfollow astrologer"
        );
      }

      /*
      * API success
      */
      setAstrologer((previous) =>
        previous
          ? {
              ...previous,
              isFollowing: false,
            }
          : previous
      );

      setShowUnfollowModal(false);
      setShowProfileMenu(false);

    } catch (error: any) {
      console.error(
        "Unfollow astrologer error:",
        error
      );

      alert(
        error?.message ||
          "Unable to unfollow astrologer"
      );
    } finally {
      setFollowLoading(false);
    }
  };

  const handleProfileMenuAction = () => {
    if (!astrologer) return;

    if (astrologer.isFollowing) {
      setShowProfileMenu(false);
      setShowUnfollowModal(true);
    } else {
      handleFollow();
    }
  };
  /*
   * ----------------------------------------------------
   * GET ASTROLOGER
   * ----------------------------------------------------
   */
  const fetchAstrologer = async () => {
    try {
      setLoading(true);
      setError("");

      const token = getToken();

      if (!token) {
        router.push("/signin");
        return;
      }

      /*
       * ==========================================
       * STEP 1
       * GET ALL ASTROLOGERS
       * ==========================================
       */

      const listResponse = await fetch(
        "/api/astrologers/list",
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${token}`,
          },
          body: JSON.stringify({}),
          cache: "no-store",
        }
      );

      /*
       * Prevent JSON parsing error if API route
       * returns HTML instead of JSON.
       */
      const listText = await listResponse.text();

      let listData: any = null;

      try {
        listData = JSON.parse(listText);
      } catch {
        throw new Error(
          "Invalid response received from astrologer list API"
        );
      }

      if (!listResponse.ok) {
        throw new Error(
          listData?.message ||
            "Unable to fetch astrologer list"
        );
      }

      /*
       * ==========================================
       * STEP 2
       * GET RECORD LIST
       * ==========================================
       */

      const astrologerList =
        listData?.recordList ||
        listData?.data ||
        listData?.records ||
        [];

      if (!Array.isArray(astrologerList)) {
        throw new Error(
          "Invalid astrologer list response"
        );
      }

      /*
       * ==========================================
       * STEP 3
       * FIND ASTROLOGER BY SLUG
       * ==========================================
       */

      const matchedAstrologer =
        astrologerList.find((item: any) => {
          const itemSlug = createSlug(
            item.name || ""
          );

          return itemSlug === slug;
        });

      if (!matchedAstrologer) {
        throw new Error(
          "Astrologer not found"
        );
      }

      /*
       * ==========================================
       * STEP 4
       * GET ASTROLOGER ID
       * ==========================================
       */

      const astrologerId =
        matchedAstrologer.id ||
        matchedAstrologer.astrologerId;

      if (!astrologerId) {
        throw new Error(
          "Astrologer ID not found"
        );
      }

      /*
       * ==========================================
       * STEP 5
       * GET COMPLETE PROFILE
       * ==========================================
       */

      const profileResponse = await fetch(
        "/api/astrologers/profile",
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${token}`,
          },
          body: JSON.stringify({
            astrologerId: Number(astrologerId),
          }),
          cache: "no-store",
        }
      );

      const profileText =
        await profileResponse.text();

      let profileData: any = null;

      try {
        profileData = JSON.parse(profileText);
      } catch {
        throw new Error(
          "Invalid response received from astrologer profile API"
        );
      }

      if (
        !profileResponse.ok ||
        !profileData?.recordList?.length
      ) {
        throw new Error(
          profileData?.message ||
            "Astrologer profile not found"
        );
      }

      const profile =
        profileData.recordList[0];

      /*
       * ==========================================
       * SET PROFILE
       * ==========================================
       */

      setAstrologer({
        ...profile,
        // profile's own value wins if it happens to carry these too —
        // matchedAstrologer (the list lookup) is only the confirmed
        // fallback source, not assumed to be more authoritative.
        isOnline: profile.isOnline ?? matchedAstrologer.isOnline,
        isBusy: profile.isBusy ?? matchedAstrologer.isBusy,
      });

      /*
       * ==========================================
       * STEP 6
       * GET REVIEWS
       * ==========================================
       */

      fetchReviews(
        Number(profile.id),
        token
      );
    } catch (error: any) {
      console.error(
        "Astrologer profile error:",
        error
      );

      setError(
        error?.message ||
          "Unable to load astrologer profile"
      );
    } finally {
      setLoading(false);
    }
  };

  /*
   * ----------------------------------------------------
   * GET REVIEWS
   * ----------------------------------------------------
   */
  const fetchReviews = async (
    astrologerId: number,
    token: string
  ) => {
    try {
      setReviewLoading(true);

      const response = await fetch(
        "/api/astrologers/reviews",
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${token}`,
          },
          body: JSON.stringify({
            astrologerId,
            startIndex: 0,
            fetchRecord: 10,
          }),
          cache: "no-store",
        }
      );

      const text = await response.text();

      let data: any = null;

      try {
        data = JSON.parse(text);
      } catch {
        console.error(
          "Invalid review API response:",
          text
        );

        setReviews([]);
        return;
      }

      if (!response.ok) {
        console.error(
          "Review API error:",
          data
        );

        setReviews([]);
        return;
      }

      setReviews(
        Array.isArray(data?.recordList)
          ? data.recordList
          : []
      );
    } catch (error) {
      console.error(
        "Reviews fetch error:",
        error
      );

      setReviews([]);
    } finally {
      setReviewLoading(false);
    }
  };

  /*
   * ----------------------------------------------------
   * FETCH ON SLUG CHANGE
   * ----------------------------------------------------
   */
  useEffect(() => {
    fetchAstrologer();
  }, [slug]);

  /*
   * ----------------------------------------------------
   * SKILLS
   * ----------------------------------------------------
   */
  const skills = useMemo(() => {
    if (!astrologer?.allSkill) return [];

    return astrologer.allSkill
      .split(",")
      .map((item) => item.trim())
      .filter(Boolean);
  }, [astrologer]);

  /*
   * ----------------------------------------------------
   * LANGUAGES
   * ----------------------------------------------------
   */
  const languages = useMemo(() => {
    if (!astrologer?.languageKnown) return [];

    return astrologer.languageKnown
      .split(",")
      .map((item) => item.trim())
      .filter(Boolean);
  }, [astrologer]);

  /*
   * ----------------------------------------------------
   * ABOUT
   * ----------------------------------------------------
   */
  const defaultAbout = astrologer
    ? `${astrologer.name} is an experienced astrologer who helps clients with guidance related to ${
        skills.join(", ") || "Astrology"
      }. Connect with the astrologer for personalized consultation and guidance.`
    : "";

  /*
   * ----------------------------------------------------
   * VISIBLE REVIEWS
   * ----------------------------------------------------
   */
  const visibleReviews = showAllReviews
    ? reviews
    : reviews.slice(0, 3);

  /*
   * ----------------------------------------------------
   * LOADING
   * ----------------------------------------------------
   */
  if (loading) {
    return (
      <main className="astro-profile-page" style={{ paddingTop: "100px", paddingBottom: "100px" }}>
        <div className="astro-profile-loading">
          <div className="astro-spinner" />

          <p>
            Loading astrologer profile...
          </p>
        </div>
      </main>
    );
  }

  /*
   * ----------------------------------------------------
   * ERROR
   * ----------------------------------------------------
   */
  if (error || !astrologer) {
    return (
      <main className="astro-profile-page" style={{ paddingTop: "100px", paddingBottom: "100px" }}>
        <div className="astro-profile-error">

          <h2>
            Astrologer not found
          </h2>

          <p>
            {error ||
              "Unable to load astrologer profile."}
          </p>

          <button
            onClick={() =>
              router.push(
                "/best-astrologer"
              )
            }
            className="astro-gold-button"
          >
            View Astrologers
          </button>

        </div>
      </main>
    );
  }

  /*
   * ----------------------------------------------------
   * RETURN UI
   * ----------------------------------------------------
   */
  return (
    <main className="astro-profile-page" style={{ paddingTop: "100px", paddingBottom: "100px" }}>

      {/* =========================================
          BREADCRUMB
      ========================================= */}

      <div className="astro-container">

        <div className="astro-breadcrumb">

          <span>
            HOME
          </span>

          <span className="breadcrumb-arrow">
            ›
          </span>

          <span>
            ASTROLOGERS
          </span>

          <span className="breadcrumb-arrow">
            ›
          </span>

          <strong>
            {astrologer.name}
          </strong>

        </div>

      </div>


      {/* =========================================
          PROFILE HEADER
      ========================================= */}

      <section className="astro-container">

        <div className="astro-profile-card">
          {/* =========================================
              PROFILE MENU
          ========================================= */}

          <div className="astro-profile-menu-wrapper">

            <button
              type="button"
              className="astro-profile-menu-button"
              onClick={() =>
                setShowProfileMenu(
                  !showProfileMenu
                )
              }
              aria-label="Astrologer options"
            >
              ⋮
            </button>


            {showProfileMenu && (
              <div className="astro-profile-dropdown">

                <button
                  type="button"
                  className="astro-profile-dropdown-item"
                  onClick={handleProfileMenuAction}
                  disabled={followLoading}
                >
                  <span>
                    {astrologer.isFollowing
                      ? "⊘"
                      : "+"}
                  </span>

                  <span>
                    {followLoading
                      ? "Please wait..."
                      : astrologer.isFollowing
                      ? "Following"
                      : "Follow"}
                  </span>
                </button>


                {/* <button
                  type="button"
                  className="astro-profile-dropdown-item report-item"
                  onClick={() => {
                    setShowProfileMenu(false);
                    alert(
                      "Report & Block functionality will be added here."
                    );
                  }}
                >
                  <span>
                    ⊘
                  </span>

                  <span>
                    Report & Block
                  </span>
                </button> */}

              </div>
            )}

          </div>

          <div className="astro-profile-top">

            {/* =====================================
                IMAGE
            ===================================== */}

            <div
              className="astro-avatar-wrapper"
              style={{ borderColor: isOffline ? "#7E775F" : "#21b45a" }}
            >

              <img
                src={
                  astrologer.profileImage ||
                  "/images/astrologer-placeholder.png"
                }
                alt={astrologer.name}
                className="astro-avatar"
              />

              <span
                className="astro-online-dot"
                title={isOffline ? "Offline" : "Online"}
                style={{ background: isOffline ? "#7E775F" : "#20bb5c" }}
              />

            </div>


            {/* =====================================
                PROFILE INFO
            ===================================== */}

            <div className="astro-profile-info">

              <div className="astro-name-row">

                <h1>
                  {astrologer.name}
                </h1>

                {astrologer.isVerified !== false && (
                  <span className="astro-verified">
                    <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
                      <path fill-rule="evenodd" clip-rule="evenodd" d="M7.16917 3.16584C7.88067 2.34504 8.91375 1.87397 10 1.875C11.1308 1.875 12.1442 2.375 12.8308 3.16584C13.9145 3.08846 14.9784 3.48595 15.7458 4.255C16.5146 5.02232 16.912 6.08575 16.835 7.16917C17.6555 7.88083 18.1262 8.91389 18.125 10C18.126 11.0863 17.655 12.1193 16.8342 12.8308C16.9112 13.9142 16.5137 14.9777 15.745 15.745C14.9777 16.5137 13.9143 16.9112 12.8308 16.8342C12.1193 17.655 11.0863 18.126 10 18.125C8.91375 18.126 7.88067 17.655 7.16917 16.8342C6.08558 16.9118 5.02177 16.5146 4.25417 15.7458C3.48521 14.9783 3.08773 13.9145 3.165 12.8308C2.34452 12.1192 1.87376 11.0861 1.875 10C1.875 8.86917 2.375 7.85583 3.16584 7.16917C3.0887 6.08574 3.48618 5.02226 4.255 4.255C5.02226 3.48618 6.08574 3.0887 7.16917 3.16584ZM13.0083 8.48833C13.1444 8.30697 13.1716 8.06612 13.0794 7.85897C12.9872 7.65181 12.79 7.51087 12.5641 7.49067C12.3383 7.47046 12.1192 7.57417 11.9917 7.76167L9.295 11.5367L7.94167 10.1833C7.69541 9.95387 7.31166 9.96064 7.07365 10.1987C6.83564 10.4367 6.82887 10.8204 7.05834 11.0667L8.93334 12.9417C9.06319 13.0714 9.24352 13.1375 9.42647 13.1224C9.60942 13.1074 9.77649 13.0126 9.88334 12.8633L13.0083 8.48833Z" fill="#38BDF8"/>
                    </svg>
                  </span>
                )}

              </div>


              {/* EXPERTISE */}

              <div className="astro-info-row">

                <span className="info-icon">
                  ☆
                </span>

                <span className="info-label">
                  EXPERTISE
                </span>

                <span className="info-value">

                  {skills.length
                    ? skills.join(" · ")
                    : astrologer.primarySkill}

                </span>

              </div>


              {/* LANGUAGES */}

              <div className="astro-info-row">

                <span className="info-icon">
                  文
                </span>

                <span className="info-label">
                  SPEAKS
                </span>

                <span className="info-value">

                  {languages.length
                    ? languages.join(", ")
                    : "Languages not available"}

                </span>

              </div>

            </div>


            {/* =====================================
                HEADER ACTIONS
            ===================================== */}

            <div className="astro-header-actions">

              {/* PRICE */}

              <div className="astro-price">
                ₹{astrologer.charge}

                <small>
                  /min
                </small>
              </div>


              {/* CHAT + CALL */}

              <div className="astro-action-buttons">

                {isAvailable ? (
                  <>
                    <button
                      type="button"
                      className="btn py-1 px-4 btn-primary rounded-3"
                      onClick={handleChatClick}
                    >
                      <span></span>
                      Chat now
                    </button>

                    <button
                      type="button"
                      className="btn py-1 px-4 btn-primary rounded-3"
                      onClick={handleCallClick}
                    >
                      <span></span>
                      Call now
                    </button>
                  </>
                ) : isBusy ? (
                  // Busy: Chat and Call are two genuinely different
                  // queues (the customer joins one medium), so both
                  // stay, relabelled as queue actions.
                  <>
                    <button
                      type="button"
                      className="btn py-1 px-4 rounded-pill border"
                      style={actionButtonStyle}
                      onClick={handleChatClick}
                      title={actionButtonTitle}
                    >
                      Join Chat Queue
                    </button>

                    <button
                      type="button"
                      className="btn py-1 px-4 rounded-pill border"
                      style={actionButtonStyle}
                      onClick={handleCallClick}
                      title={actionButtonTitle}
                    >
                      Join Call Queue
                    </button>
                  </>
                ) : (
                  // Offline is one real unavailable reason — two
                  // side-by-side disabled pills both saying "Offline"
                  // read as a rendering glitch, so it stays a single pill.
                  <button
                    type="button"
                    className="btn py-1 px-4 rounded-pill border"
                    style={actionButtonStyle}
                    disabled
                    title={actionButtonTitle}
                  >
                    {actionButtonLabel("Chat")}
                  </button>
                )}

              </div>

            </div>

          </div>


          {/* =====================================
              DIVIDER
          ===================================== */}

          <div className="astro-divider" />


          {/* =====================================
              STATS
          ===================================== */}

          <div className="astro-stats">

            {/* EXPERIENCE */}

            <div className="astro-stat">

              <strong>
                {astrologer.experience}+
              </strong>

              <span>
                Years Experience
              </span>

            </div>


            {/* CONSULTATIONS */}

            <div className="astro-stat">

              <strong>

                {astrologer.chatMinutes > 0
                  ? `${astrologer.chatMinutes}+`
                  : "10K+"}

              </strong>

              <span>
                Consultations
              </span>

            </div>


            {/* RATING */}

            <div className="astro-stat">


              <strong>

                {astrologer.rating > 0
                  ? astrologer.rating.toFixed(1)
                  : "0.0"}

              </strong>

              <span>
                Rating
              </span>

            </div>

          </div>

        </div>

      </section>


      {/* =========================================
          CONTENT
      ========================================= */}

      <section className="astro-container astro-content-grid">


        {/* =====================================
            LEFT CONTENT
        ===================================== */}

        <div className="astro-main-content">


          {/* =====================================
              ABOUT
          ===================================== */}

          <section className="astro-section">

            <h2>
              About {astrologer.name}
            </h2>

            <div
              className={
                showMoreAbout
                  ? "about-text expanded"
                  : "about-text"
              }
            >
              {astrologer.about ||
                defaultAbout}
            </div>


            <button
              type="button"
              className="read-more-button"
              onClick={() =>
                setShowMoreAbout(
                  !showMoreAbout
                )
              }
            >
              {showMoreAbout
                ? "Read less"
                : "Read more"}
            </button>

          </section>


          {/* =====================================
              EXPERTISE
          ===================================== */}

          <section className="astro-section">

            <h2>
              Areas of expertise
            </h2>

            <div className="skills-list">

              {skills.map(
                (skill) => (
                  <span key={skill}>

                    <b>
                      •
                    </b>

                    {skill}

                  </span>
                )
              )}

            </div>

          </section>


          {/* =====================================
              REVIEWS
          ===================================== */}

          <section className="astro-reviews">

            <div className="reviews-heading">

              <div>

                <h2>
                  Reviews
                </h2>

              </div>


              <div className="rating-summary">

                <strong>

                  {astrologer.rating > 0
                    ? astrologer.rating.toFixed(
                        1
                      )
                    : reviews.length
                    ? (
                        reviews.reduce(
                          (
                            sum,
                            review
                          ) =>
                            sum +
                            Number(
                              review.rating
                            ),
                          0
                        ) /
                        reviews.length
                      ).toFixed(1)
                    : "0.0"}

                </strong>


                <span className="stars">
                  ★★★★★
                </span>


                <span>

                  {astrologer.ratingCount ||
                    reviews.length}{" "}
                  reviews

                </span>

              </div>

            </div>


            {/* =================================
                REVIEW LIST
            ================================= */}

            {reviewLoading ? (

              <div className="reviews-loading">
                Loading reviews...
              </div>

            ) : visibleReviews.length > 0 ? (

              <div className="review-list">

                {visibleReviews.map(
                  (review) => (

                    <div
                      className="review-card"
                      key={review.id}
                    >

                      <div className="review-header">

                        <div className="review-user">

                          {review.profile ||
                          review.profileImage ? (

                            <img
                              src={
                                review.profile ||
                                review.profileImage
                              }
                              alt={review.name}
                            />

                          ) : (

                            <div className="review-initial">

                              {review.name
                                ?.charAt(
                                  0
                                )
                                .toUpperCase()}

                            </div>

                          )}


                          <strong>
                            {review.name}
                          </strong>

                        </div>


                        <div className="review-stars">

                          {"★".repeat(
                            Math.max(
                              0,
                              Math.min(
                                5,
                                Number(
                                  review.rating
                                )
                              )
                            )
                          )}

                        </div>

                      </div>


                      <p>
                        {review.review}
                      </p>

                    </div>

                  )
                )}

              </div>

            ) : (

              <div className="no-reviews">
                No reviews available.
              </div>

            )}


            {/* =================================
                VIEW MORE
            ================================= */}

            {reviews.length > 3 && (

              <button
                type="button"
                className="view-more"
                onClick={() =>
                  setShowAllReviews(
                    !showAllReviews
                  )
                }
              >

                {showAllReviews
                  ? "Show less"
                  : "View more"}{" "}

                →

              </button>

            )}

          </section>


        </div>


        {/* =====================================
            RIGHT CONSULT CARD
        ===================================== */}

        <aside className="astro-sidebar">

          <div className="consult-card">

            <h3>
              Consult
            </h3>


            <div className="consult-price">

              ₹{astrologer.charge}

              <small>
                /min
              </small>

            </div>


            {isAvailable ? (
              <>
                {/* =================================
                    SIDEBAR CHAT
                ================================= */}

                <button
                  type="button"
                  className="btn py-1 px-4 w-100 mb-2 btn-primary rounded-3"
                  onClick={handleChatClick}
                >
                  <span></span>
                  Chat now
                </button>

                {/* =================================
                    SIDEBAR CALL
                ================================= */}

                <button
                  type="button"
                  className="btn py-1 px-4 w-100 btn-primary rounded-3"
                  onClick={handleCallClick}
                >
                  <span></span>
                  Call now
                </button>
              </>
            ) : isBusy ? (
              <>
                <button
                  type="button"
                  className="btn py-1 px-4 w-100 mb-2 rounded-pill border"
                  style={actionButtonStyle}
                  onClick={handleChatClick}
                  title={actionButtonTitle}
                >
                  Join Chat Queue
                </button>

                <button
                  type="button"
                  className="btn py-1 px-4 w-100 rounded-pill border"
                  style={actionButtonStyle}
                  onClick={handleCallClick}
                  title={actionButtonTitle}
                >
                  Join Call Queue
                </button>
              </>
            ) : (
              <button
                type="button"
                className="btn py-1 px-4 w-100 rounded-pill border"
                style={actionButtonStyle}
                disabled
                title={actionButtonTitle}
              >
                {actionButtonLabel("Chat")}
              </button>
            )}


            <div className="consult-divider" />


            <div className="consult-feature">

              <span>
                ◇
              </span>

              <span>
                Verified astrologer
              </span>

            </div>


            <div className="consult-feature">

              <span>
                ◷
              </span>

              <span>
                Avg connect under 12s
              </span>

            </div>

          </div>

        </aside>

      </section>


      {/* =========================================
          CONSULTATION MODAL
      ========================================= */}

      <StartConsultationModal
        show={showConsultationModal}
        onClose={
          handleCloseConsultationModal
        }
        astrologer={{
          id: astrologer.id,
          name: astrologer.name,
          charge: astrologer.charge,

          /*
           * Profile API returns audioCallRate.
           * StartConsultationModal expects callRate.
           */
          callRate:
            astrologer.audioCallRate,
        }}
        medium={consultationMedium}
        onUnavailable={(reason) =>
          setLiveStatus(reason === "ASTROLOGER_BUSY" ? "BUSY" : "OFFLINE")
        }
      />

      {/* =========================================
          UNFOLLOW CONFIRMATION MODAL
      ========================================= */}

      {showUnfollowModal && (
        <div
          className="astro-unfollow-overlay"
          onClick={() =>
            !followLoading &&
            setShowUnfollowModal(false)
          }
        >

          <div
            className="astro-unfollow-modal"
            onClick={(event) =>
              event.stopPropagation()
            }
          >

            <h3>
              Unfollow
            </h3>

            <p>
              Are you sure you want to unfollow{" "}
              <strong>
                {astrologer.name}
              </strong>
              ?
            </p>


            <div className="astro-unfollow-actions">

              <button
                type="button"
                className="astro-cancel-button"
                onClick={() =>
                  setShowUnfollowModal(false)
                }
                disabled={followLoading}
              >
                Cancel
              </button>


              <button
                type="button"
                className="astro-unfollow-button"
                onClick={handleUnfollow}
                disabled={followLoading}
              >
                {followLoading
                  ? "Please wait..."
                  : "Unfollow"}
              </button>

            </div>

          </div>

        </div>
      )}

    </main>
  );
}