/* Google Maps JS API loader — loads once, returns a promise resolving to
   window.google.maps. Uses APP_CONFIG.gmapKey. */
window.GMap = (function () {
    var promise = null;

    function load() {
        if (promise) return promise;
        promise = new Promise(function (resolve, reject) {
            if (window.google && window.google.maps) { resolve(window.google.maps); return; }
            var key = (window.APP_CONFIG && window.APP_CONFIG.gmapKey) || '';
            window.__gmapReady = function () { resolve(window.google.maps); };
            var s = document.createElement('script');
            s.src = 'https://maps.googleapis.com/maps/api/js?key=' + encodeURIComponent(key) +
                '&v=weekly&callback=__gmapReady&loading=async';
            s.async = true;
            s.onerror = function () { reject(new Error('Google Maps yüklənmədi')); };
            document.head.appendChild(s);
        });
        return promise;
    }

    // status → marker colour (shared by all maps)
    function colorFor(o) {
        return o.DueDayDifference < 0 ? '#d24a50' : (o.DebtAmount > 0 ? '#cf861f' : '#0f9d7f');
    }
    function dotIcon(gmaps, color) {
        return { path: gmaps.SymbolPath.CIRCLE, scale: 7, fillColor: color, fillOpacity: 1, strokeColor: '#ffffff', strokeWeight: 2 };
    }

    // brand-teal cluster bubbles (instead of the default blue)
    function clusterRenderer(gmaps) {
        return {
            render: function (cluster) {
                var count = cluster.count, position = cluster.position;
                var r = count < 10 ? 18 : (count < 50 ? 22 : 27);
                var svg = '<svg xmlns="http://www.w3.org/2000/svg" width="' + (r * 2) + '" height="' + (r * 2) + '">' +
                    '<circle cx="' + r + '" cy="' + r + '" r="' + (r - 3) + '" fill="#0f7061" fill-opacity="0.92" stroke="#ffffff" stroke-width="2"/></svg>';
                return new gmaps.Marker({
                    position: position,
                    icon: { url: 'data:image/svg+xml;base64,' + btoa(svg), scaledSize: new gmaps.Size(r * 2, r * 2), anchor: new gmaps.Point(r, r) },
                    label: { text: String(count), color: '#ffffff', fontSize: '12px', fontWeight: '700' },
                    zIndex: 1000 + count
                });
            }
        };
    }

    return { load: load, colorFor: colorFor, dotIcon: dotIcon, clusterRenderer: clusterRenderer };
})();
