// (C) 2025-2026 GoodData Corporation
import { bucketAttribute, idRef, insightBucket, insightProperties, insightVisualizationUrl, newAttribute, } from "@gooddata/sdk-model";
import { BucketNames } from "@gooddata/sdk-ui";
import { createAttributeRef } from "./geoAttributeHelper.js";
import { ANALYTICAL_ENVIRONMENT, DASHBOARDS_ENVIRONMENT } from "../../../constants/properties.js";
import { sdkModelPropMetas, } from "../../../utils/embeddingCodeGenerator/index.js";
/**
 * Builds geo visualization configuration for both legacy and next-gen geo pushpin charts.
 *
 * @param params - Configuration parameters
 * @returns Complete geo chart configuration
 * @internal
 */
export function buildGeoVisualizationConfig({ options, supportedControls, colorMapping, environment, }) {
    const { config = {}, customVisualizationConfig = {} } = options;
    const { center, legend, viewport = {} } = supportedControls;
    const { isInEditMode, isExportMode } = config;
    // Build center configuration if provided
    const centerProp = center ? { center } : {};
    // Build legend configuration
    let legendProp = legend ? { legend } : {};
    if (environment === DASHBOARDS_ENVIRONMENT) {
        // In dashboards, use responsive legend with popup
        legendProp = {
            legend: {
                ...legend,
                responsive: "autoPositionWithPopup",
            },
        };
    }
    // Build viewport configuration with frozen state during edit/export
    const viewportProp = {
        viewport: {
            ...viewport,
            frozen: isInEditMode || isExportMode,
        },
    };
    // Determine cooperative gestures behavior
    const isKDInViewMode = environment !== ANALYTICAL_ENVIRONMENT && !isInEditMode;
    const cooperativeGestures = customVisualizationConfig?.cooperativeGestures === undefined
        ? isKDInViewMode
        : customVisualizationConfig.cooperativeGestures;
    // Merge all configuration
    const geoConfig = {
        ...supportedControls,
        ...config,
        ...centerProp,
        ...legendProp,
        ...viewportProp,
        ...customVisualizationConfig,
        separators: config.separators,
        colorPalette: config.colorPalette,
        mapboxToken: config.mapboxToken,
        colorMapping,
        cooperativeGestures,
    };
    return geoConfig;
}
const supportedGeoConfigProperties = new Set([
    "center",
    "colorMapping",
    "cooperativeGestures",
    "legend",
    "limit",
    "mapStyle",
    "selectedSegmentItems",
    "separators",
    "viewport",
    "points",
    "showLabels",
    "showLabels",
    "tooltipText",
]);
export function geoConfigFromInsight(insight, ctx) {
    const properties = insightProperties(insight);
    const controls = properties?.["controls"] ?? {};
    const withValuesFromContext = {
        ...controls,
        ...(ctx?.settings?.separators ? { separators: ctx?.settings?.separators } : {}),
    };
    const tooltipText = controls["tooltipText"];
    const configFromProperties = Object.fromEntries(Object.entries(withValuesFromContext).filter(([key, value]) => supportedGeoConfigProperties.has(key) && !(value === null || value === undefined)));
    const tooltipTextAttribute = typeof tooltipText === "string" ? buildTooltipTextAttribute(insight, tooltipText) : undefined;
    return {
        ...configFromProperties,
        ...(tooltipTextAttribute ? { tooltipText: tooltipTextAttribute } : {}),
    };
}
export function geoInsightConversion(propName, bucketName) {
    return {
        propName,
        propType: sdkModelPropMetas.Attribute.Single,
        itemAccessor(insight, ctx) {
            return getLocationAttributeFromInsight(insight, ctx, bucketName);
        },
    };
}
function getLocationAttributeFromInsight(insight, ctx, bucketName) {
    if (bucketName === BucketNames.AREA) {
        const bucket = insightBucket(insight, bucketName);
        return bucket && bucketAttribute(bucket);
    }
    if (bucketName === BucketNames.LOCATION &&
        !ctx?.backend?.capabilities.supportsSeparateLatitudeLongitudeLabels) {
        const bucket = insightBucket(insight, bucketName);
        return bucket ? bucketAttribute(bucket) : undefined;
    }
    else if (
    // dont rely on Latitude being already in bucket, take both lat and long from properties
    (bucketName === BucketNames.LATITUDE || bucketName === BucketNames.LONGITUDE) &&
        ctx?.backend?.capabilities.supportsSeparateLatitudeLongitudeLabels) {
        const properties = insightProperties(insight);
        const controls = properties?.["controls"] ?? {};
        const identifier = controls[bucketName];
        return newAttribute(idRef(identifier, "displayForm"), (a) => a.localId(`a_${identifier}`));
    }
    return undefined;
}
export function isGeoChart(insightDefinition) {
    const type = insightVisualizationUrl(insightDefinition).split(":")[1];
    return type === "pushpin";
}
function buildTooltipTextAttribute(insight, tooltipTextId) {
    const baseAttribute = getTooltipBaseAttribute(insight);
    if (!baseAttribute) {
        return undefined;
    }
    const ref = createAttributeRef(baseAttribute, tooltipTextId);
    return newAttribute(ref, (attribute) => attribute.localId("tooltipText_df"));
}
function getTooltipBaseAttribute(insight) {
    const areaBucket = insightBucket(insight, BucketNames.AREA);
    const areaAttribute = areaBucket && bucketAttribute(areaBucket);
    if (areaAttribute) {
        return areaAttribute;
    }
    const locationBucket = insightBucket(insight, BucketNames.LOCATION);
    return locationBucket && bucketAttribute(locationBucket);
}
//# sourceMappingURL=geoConfigBuilder.js.map