"use client";

import { useMemo, useState } from "react";
import { richTextToPlain } from "@/features/opportunities/forms/richTextToPlain";

interface OptionalPanelSource {
  title_ar?: string | null;
  title_en?: string | null;
  description_ar?: string | null;
  description_en?: string | null;
  latitude?: number | string | null;
  longitude?: number | string | null;
}

/**
 * The three panels that are each a *second* way to answer a question the form
 * already asks once: an English title, an English description, and a pinned
 * map location instead of a pasted link.
 *
 * Each stays off screen until asked for. `null` means "the organizer hasn't
 * decided", which lets a panel follow the record — open when editing something
 * that already carries the second answer, closed otherwise. Once they click
 * either way, their choice wins for the rest of the session.
 *
 * The "already carries it" test is the subtle part. An opportunity published
 * without opening the English panel stores the **Arabic** text in both columns,
 * so a non-empty `title_en` is not evidence that anyone wrote English. Treating
 * it as such would re-open the panel on every edit and show Arabic text in a
 * field labelled English. Only a genuinely *different* value counts.
 */
export function useOptionalFormPanels(opportunityData?: OptionalPanelSource | null) {
  const [englishTitleToggle, setEnglishTitleToggle] = useState<boolean | null>(null);
  const [englishDescriptionToggle, setEnglishDescriptionToggle] = useState<
    boolean | null
  >(null);
  const [mapPickerToggle, setMapPickerToggle] = useState<boolean | null>(null);

  const hasDistinctEnglishTitle = useMemo(() => {
    const arabic = (opportunityData?.title_ar || "").trim();
    const english = (opportunityData?.title_en || "").trim();
    return english !== "" && english !== arabic;
  }, [opportunityData?.title_ar, opportunityData?.title_en]);

  const hasDistinctEnglishDescription = useMemo(() => {
    const arabic = (opportunityData?.description_ar || "").trim();
    const english = (opportunityData?.description_en || "").trim();
    return richTextToPlain(english) !== "" && english !== arabic;
  }, [opportunityData?.description_ar, opportunityData?.description_en]);

  const hasStoredMapLocation = Boolean(
    opportunityData?.latitude && opportunityData?.longitude
  );

  return {
    /** What the initial-values builder needs to decide whether to prefill. */
    hasDistinctEnglishTitle,
    hasDistinctEnglishDescription,

    showEnglishTitle: englishTitleToggle ?? hasDistinctEnglishTitle,
    showEnglishDescription:
      englishDescriptionToggle ?? hasDistinctEnglishDescription,
    showMapPicker: mapPickerToggle ?? hasStoredMapLocation,

    setEnglishTitleToggle,
    setEnglishDescriptionToggle,
    setMapPickerToggle,
  };
}
