User: # Inputs

## Current File
Here is the file I'm looking at. It might be truncated from above and below and, if so, is centered around my cursor.
```src/components/CultureCockpit.tsx
import {
  Dimension_Enum,
  useGetQuestionnairesQuery,
  useGetSecondRecentQuestionnaireQuery,
  useLatestQuestionnaireQuery,
} from "api/graphql_ch_admin_user";
import { useGetSpheresQuery } from "api/graphql_user";
import dayjs from "dayjs";
import useTranslation from "lang/useTranslation";
import _ from "lodash";
import { useRouter } from "next/router";
import { useCallback, useMemo, useState } from "react";
import { useCultureCockpitFilters } from "src/hooks/useCultureCockpitFilters";
import useCurrentChannelStore from "src/store/useCurrentChannelStore";
import { calc_zwopr_score, color_perception, generateChartData, spheres_overview } from "src/utils/cultureCockpitMock";
import CircularProgressBar from "./CircularProgressBar";
import Information from "./common/Information";
import CultureCockpitComparison from "./CultureCockpitComparison";
import CultureCockpitCustomComparison from "./CultureCockpitCustomComparison";
import CultureCockpitProjection from "./CultureCockpitProjection";
import CultureCockpitQuestionnaireComparison from "./CultureCockpitQuestionnaireComparison";
import DashboardNewTablePosts from "./dashboard/DashboardNewTablePosts";
import SpherePolarChart from "./SpherePolarChart";
import LoaderDots from "./utils/LoaderDots";

function CultureCockpit() {
  const { t } = useTranslation();
  const router = useRouter();
  const { sphere_id: query_sphere_id } = router?.query;
  const currentChannel = useCurrentChannelStore((state) => state.currentChannel);
  const [resultLatestQuestionnaire] = useLatestQuestionnaireQuery({
    variables: {
      channel_id: currentChannel?.channel?.id,
    },
    pause: !currentChannel?.channel?.id,
  });
  const [resultSecondRecentQuestionnaire] = useGetSecondRecentQuestionnaireQuery({
    variables: { channel_id: currentChannel?.channel?.id },
    pause: !currentChannel?.channel?.id,
  });
  const [resultGetQuestionnaires] = useGetQuestionnairesQuery({
    variables: { channel_id: currentChannel?.channel?.id },
    pause: !currentChannel?.channel?.id,
  });

  const dataLatestQuestionnaire = resultLatestQuestionnaire.data?.questionnaire;
  const loadingLatestQuestionnaire = resultLatestQuestionnaire.fetching;
  const errorLatestQuestionnaire = !!resultLatestQuestionnaire.error;

  const dataSecondRecentQuestionnaire = resultSecondRecentQuestionnaire.data?.questionnaire;
  const loadingSecondRecentQuestionnaire = resultSecondRecentQuestionnaire.fetching;
  const errorSecondRecentQuestionnaire = !!resultSecondRecentQuestionnaire.error;

  const dataGetQuestionnaires = resultGetQuestionnaires.data?.questionnaire;
  const loadingGetQuestionnaires = resultGetQuestionnaires.fetching;
  const errorGetQuestionnaires = !!resultGetQuestionnaires.error;

  const [resultGetSpheres] = useGetSpheresQuery({
    variables: { channel_id: currentChannel?.channel?.id },
    pause: !currentChannel?.channel?.id,
  });
  const dataGetSpheres = resultGetSpheres.data?.sphere;
  const data_spheres = useMemo(() => {
    if (dataGetSpheres) {
      const filtered =
        dataGetSpheres
          ?.filter((sphere) => sphere?.shapes?.some((shape) => shape?.enabled))
          .map((sphere) => ({ value: sphere.id, label: sphere.name })) ?? [];
      filtered.unshift(spheres_overview);

      return filtered;
    } else {
      return [spheres_overview];
    }
  }, [dataGetSpheres]);
  const loadingGetSpheres = resultGetSpheres.fetching;
  const errorGetSpheres = resultGetSpheres.error;

  const [selectedShape, setSelectedShape] = useState("");

  const {
    selected_sphere,
    current_filter,
    handleSphereDropdownFilter,
    is_custom_filter,
    compare_filter,
    custom_filter_date,
    handleClearFilters,
    handleCurrentFilterDropdown,
    handleCompareFilterDropdown,
    handleCustomFilterDate,
  } = useCultureCockpitFilters({
    data_spheres,
    dataGetQuestionnaires,
  });

  const handleSelectedShape = useCallback(
    (shape_id: string) => {
      if (shape_id === selectedShape) {
        setSelectedShape("");
      } else {
        setSelectedShape(shape_id);
      }
    },
    [selectedShape]
  );

  const culture_score = useMemo(() => {
    /*
     *
     * Calculation of Zwopr Score (left of polar chart), polar chart generation and shape average (number in the middle of polar chart)
     * Zwopr score is the average of an average; first you take averages of each sphere's shape perceptions then you take the average of them
     * Polar chart is visual display of the latest questionnaire results. Each displayed with its dimensions; Perception, Accessibility and Importance
     */

    if (!dataLatestQuestionnaire || !dataLatestQuestionnaire.length || Array.isArray(query_sphere_id))
      return {
        score: 0,
        chartData: [
          {
            labels: [""],
            datasets: [
              {
                label: "",
                backgroundColor: color_perception,
                borderColor: color_perception,
                borderWidth: 0,
                data: [0],
                spacing: 160,
              },
            ],
          },
        ],
        zwopr_score: 0,
      };

    const data = dataLatestQuestionnaire?.[0]?.questionnaire_results?.filter((d) => d.shape?.enabled);

    const perception_answers = data.filter((answer) => answer.dimension === Dimension_Enum.P && answer?.shape?.enabled);
    const sort_shape_code = _.sortBy(perception_answers, (answer) => answer?.shape?.code);
    const group_spheres = _.groupBy(sort_shape_code, "sphere_id");

    const zwopr_score = calc_zwopr_score(dataLatestQuestionnaire?.[0]?.questionnaire_results);

    let zwopr_score_difference;

    if (dataSecondRecentQuestionnaire && dataSecondRecentQuestionnaire?.length) {
      const previous_zwopr_score = calc_zwopr_score(dataSecondRecentQuestionnaire?.[0]?.questionnaire_results);

      if (zwopr_score > previous_zwopr_score) {
        zwopr_score_difference = (zwopr_score - previous_zwopr_score).toFixed(1);
        zwopr_score_difference = "+" + zwopr_score_difference;
      } else if (zwopr_score < previous_zwopr_score) {
        zwopr_score_difference = (previous_zwopr_score - zwopr_score).toFixed(1);
        zwopr_score_difference = "-" + zwopr_score_difference;
      } else {
        zwopr_score_difference = "";
      }
    }

    if (!selected_sphere?.value) {
      // meaning this is spheres_overview, show zwopr score

      const extract_labels = _.mapValues(group_spheres, (group) => {
        const uniqueNames = _.uniq(group.map((item) => item?.sphere?.name));
        return uniqueNames[0];
      });
      const labels = Object.values(extract_labels);

      const chartData = generateChartData(labels, data, selected_sphere?.value);

      return { score: zwopr_score, chartData, zwopr_score, zwopr_score_difference };
    } else {
      // meaning different sphere is selected

      const selected_sphere_filtered = data.filter(
        (result) => result.dimension === Dimension_Enum.P && result.sphere_id === selected_sphere?.value
      );
      const avg = Number(_.meanBy(selected_sphere_filtered, "value").toFixed(1)) ?? 0;

      const sort_shape_code = _.sortBy(selected_sphere_filtered, (answer) => answer?.shape?.code);
      const labels = sort_shape_code?.map((shapes) => shapes?.shape?.name);

      const chartData = generateChartData(labels, data, selected_sphere?.value);

      return { score: avg, chartData, zwopr_score, zwopr_score_difference };
    }
  }, [dataLatestQuestionnaire, dataSecondRecentQuestionnaire, query_sphere_id, selected_sphere?.value]);

  const loading = loadingGetSpheres || loadingLatestQuestionnaire || loadingSecondRecentQuestionnaire;
  const error = !!errorGetSpheres || !!errorLatestQuestionnaire || !!errorSecondRecentQuestionnaire;
  const data = !!dataGetSpheres && !!dataLatestQuestionnaire;
  const data_length = !!dataGetSpheres?.length && !!dataLatestQuestionnaire?.length;

  // Function to format dates to fit custom_filter_date format.
  const formatDateRange = (date: string | Date, startOrEnd: 'start' | 'end') => {
    return dayjs(date)[startOrEnd === 'start' ? 'startOf' : 'endOf']('month').toISOString();
  };

  return (
    <div className="pt-14 px-10 space-y-4">
      <div className="flex flex-col pb-6   w-fit items-end">
        <div className="text-3xl font-bold ">{t("SettingsScreen.CultureCockpit.title")}</div>
        <p className="text-xs font-bold text-gray-500">BETA</p>
      </div>
      <div className="w-fit">
        {dataGetQuestionnaires && dataGetQuestionnaires?.length ? (
          <CultureCockpitComparison
            questionnaires={dataGetQuestionnaires}
            compareFilter={compare_filter}
            handleClearFilters={handleClearFilters}
            is_custom_filter={is_custom_filter}
            current_filter={current_filter}
            custom_filter_date={custom_filter_date}
            handleCurrentFilterDropdown={handleCurrentFilterDropdown}
            handleCompareFilterDropdown={handleCompareFilterDropdown}
            handleCustomFilterDate={handleCustomFilterDate}
          />
        ) : null}
      </div>
      <div className="flex flex-col md:flex-row gap-x-5 max-w-7xl">
        {!loading && error ? (
          <Information text={t("SettingsScreen.CultureCockpit.get_questionnaire_error")} variant="danger" />
        ) : null}
        {loading ? (
          <div
            className="w-full min-h-[32rem]  
          flex flex-col justify-center items-center">
            <LoaderDots dark />
          </div>
        ) : null}
        {!loading && !error && data && !data_length ? (
          <Information text={t("SettingsScreen.CultureCockpit.no_questionnaire_found")} variant="info" />
        ) : null}
        {!loading && !error && data && data_length ? (
          <>
            <CircularProgressBar
              percentage={culture_score.zwopr_score / 10}
              from={0}
              to={culture_score.zwopr_score ?? 0}
              difference={culture_score?.zwopr_score_difference}
            />
            <SpherePolarChart
              culture_score={culture_score.score ?? 0}
              selected_dropdown_label={selected_sphere?.label ?? ""}
              selected_dropdown_sphere_id={selected_sphere?.value}
              onSelectDropdown={(val) => handleSphereDropdownFilter(val)}
              dropdown_options={data_spheres}
              chartData={culture_score.chartData}
            />
          </>
        ) : null}
      </div>

      <div className="border border-limegreen p-4 rounded bg-white max-w-7xl shadow-sm">
        {current_filter && dataGetQuestionnaires ? (
          is_custom_filter ? (
            <CultureCockpitCustomComparison
              current_filter={current_filter}
              questionnaires={dataGetQuestionnaires}
              spheres={dataGetSpheres}
              channel_id={currentChannel?.channel?.id}
              selected_dropdown_sphere_id={selected_sphere?.value}
              custom_filter_date={custom_filter_date}
            />
          ) : (
            <CultureCockpitQuestionnaireComparison
              compareFilter={compare_filter}
              current_filter={current_filter}
              questionnaires={dataGetQuestionnaires}
              spheres={dataGetSpheres}
              channel_id={currentChannel?.channel?.id}
              selected_dropdown_sphere_id={selected_sphere?.value}
            />
          )
        ) : (
          <CultureCockpitProjection
            channel_id={currentChannel?.channel?.id}
            questionnaire_results={dataLatestQuestionnaire?.[0]?.questionnaire_results}
            questionnaire_uploaded_at={dayjs(dataLatestQuestionnaire?.[0]?.created_at).startOf("day")}
            spheres={dataGetSpheres}
            selectedShape={selectedShape}
            handleSelectedShape={handleSelectedShape}
            selected_dropdown_sphere_id={selected_sphere?.value}
          />
        )}
        {selected_sphere?.value ? (
          <div className="grid w-full border border-limegreen relative rounded-sm">
            <DashboardNewTablePosts
              calendarActive={false}
              // @ts-expect-error
              currentDateNew={{
                startDate: dayjs().startOf("year").toISOString(),
                endDate: dayjs().toISOString(),
              }}
              loading={false}
              condition={{
                channel_id: { _eq: currentChannel?.channel?.id },
                sphere_id: { _eq: selected_sphere?.value }, //Filter posts based on Sphere.
                published_at: {
                  _gte: custom_filter_date ? formatDateRange(custom_filter_date.startDate, 'start') : undefined, //Filter data based on Custom Date.
                  _lte: custom_filter_date ? formatDateRange(custom_filter_date.endDate, 'end') : undefined,
                }, 
              }}
            />
          </div>
        ) : null}
      </div>

      <div className="h-16"></div>
    </div>
  );
}

export default CultureCockpit;


```


User: ```typescript:src/components/CultureCockpit.tsx
  const handleSelectedShape = useCallback(
    (shape_id: string) => {
      if (shape_id === selectedShape) {
        setSelectedShape("");
      } else {
        setSelectedShape(shape_id);
      }
    },
    [selectedShape]
  );
```


In this, how can I display the posts based on the shape_id that has been selected?
Assistant: