llmApp.directive('bsImageSelect', ['customFileUploaderService', '$timeout','PLUGIN_PATHS', function (customFileUploaderService, $timeout,PLUGIN_PATHS) {
    return {
        restrict: 'E',
        templateUrl: PLUGIN_PATHS.WEBAPP +'bs-image-select.html',
        scope: {
            config: '=',
            configProperty: '@',
            labelText: '@',
            onImageSelected: '&?'
        },
        link: function (scope, element) {
            // State management
            scope.availableImages = [];
            scope.isLoading = false;
            scope.selectedImageName = null;
            scope.canScrollLeft = false;
            scope.canScrollRight = false;
            scope.scrollDots = [];

            scope.shouldShowSelector = function() {
                const themeName = getThemeName();

                // Don't show for default customization
                if (!themeName || themeName === 'Default customization') {
                    return false;
                }

                // Don't show if no images available (and not loading)
                if (!scope.isLoading && scope.availableImages.length === 0) {
                    return false;
                }

                return true;
            };

            // Get theme name helper
            function getThemeName() {
                return scope.config?.custom_theme_name || 'Default customization';
            }

            // Carousel navigation functions
            scope.scrollLeft = function() {
                const carousel = element.find('#imageCarousel')[0];
                if (carousel) {
                    carousel.scrollLeft -= 120; // Scroll by approximately one item width
                    $timeout(function() {
                        updateScrollButtons();
                        updateScrollDots();
                    }, 100);
                }
            };

            scope.scrollRight = function() {
                const carousel = element.find('#imageCarousel')[0];
                if (carousel) {
                    carousel.scrollLeft += 120; // Scroll by approximately one item width
                    $timeout(function() {
                        updateScrollButtons();
                        updateScrollDots();
                    }, 100);
                }
            };

            function updateScrollButtons() {
                const carousel = element.find('#imageCarousel')[0];
                if (!carousel) return;

                scope.canScrollLeft = carousel.scrollLeft > 0;
                scope.canScrollRight = carousel.scrollLeft < (carousel.scrollWidth - carousel.clientWidth);
            }

            function updateScrollDots() {
                const carousel = element.find('#imageCarousel')[0];
                if (!carousel || scope.availableImages.length <= 4) {
                    scope.scrollDots = [];
                    return;
                }

                const scrollLeft = carousel.scrollLeft;
                const scrollWidth = carousel.scrollWidth;
                const clientWidth = carousel.clientWidth;
                const maxScrollLeft = scrollWidth - clientWidth;

                if (maxScrollLeft <= 0) {
                    scope.scrollDots = [];
                    return;
                }

                // Simple approach: divide scroll area into 3-5 segments based on content
                const numDots = Math.min(5, Math.max(3, Math.ceil(scope.availableImages.length / 3)));
                const segmentSize = maxScrollLeft / (numDots - 1);

                // Find which segment we're in
                let activeDotIndex = 0;
                for (let i = 0; i < numDots; i++) {
                    const segmentStart = i * segmentSize;
                    const segmentEnd = (i + 1) * segmentSize;

                    if (scrollLeft >= segmentStart && (scrollLeft < segmentEnd || i === numDots - 1)) {
                        activeDotIndex = i;
                        break;
                    }
                }

                // Create dots
                scope.scrollDots = [];
                for (let i = 0; i < numDots; i++) {
                    scope.scrollDots.push({
                        active: i === activeDotIndex,
                        index: i
                    });
                }
            }

            // Refresh available images based on current theme
            function refreshAvailableImages(silent = false) {
                const themeName = getThemeName();
                if (!themeName || themeName === 'Default customization') {
                    scope.availableImages = [];
                    scope.isLoading = false;
                    return;
                }

                // Only show loading spinner if not a silent refresh
                if (!silent) {
                    scope.isLoading = true;
                }

                customFileUploaderService.fetchUploadedFiles('LOCAL_STATIC')
                    .then(response => {
                        const allFilesForTheme = customFileUploaderService.getAllFilesForTheme(response.data, themeName);

                        // Filter only image files from the images folder
                        const newImages = allFilesForTheme
                            .filter(file => {
                                // Check if file is in images folder and is an image
                                const pathParts = file.path.split('/');
                                const isInImagesFolder = pathParts.length >= 4 &&
                                    pathParts[0] === 'answers' &&
                                    pathParts[1] === themeName &&
                                    pathParts[2] === 'images';

                                return isInImagesFolder && customFileUploaderService.isImageFileByName(file.name);
                            })
                            .map(file => ({
                                name: file.name,
                                url: `${window.location.origin}/local/static/${file.path}?v=${new Date().getTime()}`,
                                path: file.path
                            }));

                        // Update images
                        scope.availableImages = newImages;

                        $timeout(function() {
                            updateScrollButtons();
                            updateScrollDots();
                        }, 100);
                    })
                    .catch(error => {

                        scope.availableImages = [];
                    })
                    .finally(() => {
                        scope.isLoading = false;
                    });
            }



            // Select an image
            scope.selectImage = function(image) {
                scope.selectedImageName = image.name;
                scope.config[scope.configProperty] = image.name;

                // Notify parent component if callback provided
                if (scope.onImageSelected) {
                    scope.onImageSelected({
                        selectedImage: image,
                        configProperty: scope.configProperty
                    });
                }
            };

            // Check if an image is currently selected
            scope.isImageSelected = function(image) {
                const currentValue = scope.config[scope.configProperty];
                return currentValue === image.name;
            };

            // Initialize
            function initialize() {
                refreshAvailableImages();

                // Set initial selection based on config
                const currentValue = scope.config[scope.configProperty];
                if (currentValue) {
                    scope.selectedImageName = currentValue;
                }

                // Add scroll event listener
                $timeout(function() {
                    const carousel = element.find('#imageCarousel')[0];
                    if (carousel) {
                        carousel.addEventListener('scroll', function() {
                            scope.$apply(function() {
                                updateScrollButtons();
                                updateScrollDots();
                            });
                        });
                    }
                }, 500);
            }

            // Watch for theme changes
            scope.$watch('config.custom_theme_name', function(newTheme, oldTheme) {
                if (newTheme !== oldTheme) {
                    refreshAvailableImages();
                }
            });

            // Update the event listener to use silent refresh for smoother UX
            scope.$on('refreshImageSelector', function(event, data) {

                // Only refresh if this relates to our theme or if it's a general refresh
                const currentTheme = getThemeName();
                if (!data.themeName || data.themeName === currentTheme) {

                    // Add a small delay to ensure the file system has updated
                    $timeout(function() {
                        refreshAvailableImages(true); // Silent refresh
                    }, 500);
                }
            });



            // Also refresh when folder is created (existing listener can be enhanced)
            scope.$on('folderRefreshRequested', function() {

                $timeout(function() {
                    refreshAvailableImages();
                }, 1000); // Longer delay for folder creation
            });


            initialize();
        }
    };
}]);