(function(){
  "use strict";

  function parse(el, attr){
    try { return JSON.parse(el.getAttribute(attr) || '{}'); } catch(e){ return {}; }
  }

  function isDarkCanvas(canvas){
    try {
      return !!(canvas && canvas.closest && canvas.closest('.itp-page-itp-analytics .itp-card, .itp-page-itp-dashboard .itp-card:not(.itp-country-map-card)'));
    } catch(e){ return false; }
  }

  function setup(c){
    var r = window.devicePixelRatio || 1;
    var rect = c.getBoundingClientRect();
    var w = Math.max(300, rect.width || 300);
    var h = Math.max(180, rect.height || 220);
    c.width = w * r;
    c.height = h * r;
    var ctx = c.getContext('2d');
    ctx.setTransform(r,0,0,r,0,0);
    return {ctx:ctx,w:w,h:h};
  }

  function tooltip(){
    var el = document.querySelector('.itp-chart-tip');
    if(!el){
      el = document.createElement('div');
      el.className = 'itp-chart-tip';
      document.body.appendChild(el);
    }
    return el;
  }

  function showTip(e, html){
    var t = tooltip();
    t.innerHTML = html;
    t.style.left = (e.clientX + 14) + 'px';
    t.style.top = (e.clientY + 14) + 'px';
    t.classList.add('show');
  }

  function hideTip(){
    var t = document.querySelector('.itp-chart-tip');
    if(t) t.classList.remove('show');
  }

  function roundedRect(ctx,x,y,w,h,r){
    var rr = Math.min(r, Math.abs(w)/2, Math.abs(h)/2);
    ctx.beginPath();
    ctx.moveTo(x+rr,y);
    ctx.arcTo(x+w,y,x+w,y+h,rr);
    ctx.arcTo(x+w,y+h,x,y+h,rr);
    ctx.arcTo(x,y+h,x,y,rr);
    ctx.arcTo(x,y,x+w,y,rr);
    ctx.closePath();
  }

  function line(canvas,data){
    var s = setup(canvas), ctx = s.ctx, w = s.w, h = s.h, pad = 44;
    var dark = isDarkCanvas(canvas);
    var labels = data.labels || [], visits = data.visits || [], clicks = data.clicks || [];
    var max = Math.max.apply(null, [1].concat(visits, clicks));
    ctx.clearRect(0,0,w,h);
    ctx.font = '12px system-ui';
    ctx.lineWidth = 1;
    ctx.strokeStyle = dark ? 'rgba(196,220,244,.18)' : '#dce8f2';
    for(var i=0;i<4;i++){
      var yy = pad + (h-pad*2)*i/3;
      ctx.beginPath(); ctx.moveTo(pad,yy); ctx.lineTo(w-pad,yy); ctx.stroke();
    }

    function points(arr){
      return arr.map(function(v,i){
        return {
          x: pad + (w-pad*2)*(i/(Math.max(1,arr.length-1))),
          y: h-pad-((h-pad*2)*(v/max)),
          v: v
        };
      });
    }

    function draw(arr,color,fill){
      var pts = points(arr);
      ctx.strokeStyle = color;
      ctx.lineWidth = 5;
      ctx.lineCap = 'round';
      ctx.lineJoin = 'round';
      ctx.beginPath();
      pts.forEach(function(p,i){ if(i===0) ctx.moveTo(p.x,p.y); else ctx.lineTo(p.x,p.y); });
      ctx.stroke();

      if(fill){
        ctx.lineTo(pts[pts.length-1].x,h-pad);
        ctx.lineTo(pts[0].x,h-pad);
        ctx.closePath();
        var g = ctx.createLinearGradient(0,pad,0,h-pad);
        g.addColorStop(0, fill);
        g.addColorStop(1, dark ? 'rgba(8,20,37,0)' : 'rgba(255,255,255,0)');
        ctx.fillStyle = g;
        ctx.fill();
      }

      pts.forEach(function(p){
        ctx.fillStyle = dark ? '#081525' : '#fff';
        ctx.strokeStyle = color;
        ctx.lineWidth = 4;
        ctx.beginPath(); ctx.arc(p.x,p.y,5,0,Math.PI*2); ctx.fill(); ctx.stroke();
      });
      return pts;
    }

    var visitPts = draw(visits,'#20cfe1','rgba(32,207,225,.18)');
    var clickPts = draw(clicks,'#6d35e8',null);

    ctx.fillStyle = dark ? '#9fb6ce' : '#536b82';
    ctx.textAlign = 'center';
    labels.forEach(function(l,i){
      var x = pad + (w-pad*2)*(i/(Math.max(1,labels.length-1)));
      ctx.fillText(l,x,h-12);
    });

    canvas.onmousemove = function(e){
      var r = canvas.getBoundingClientRect();
      var x = e.clientX - r.left;
      var idx = Math.round((x-pad)/(w-pad*2)*(labels.length-1));
      idx = Math.max(0, Math.min(labels.length-1, idx));
      var p = visitPts[idx] || {x:0};
      ctx.save();
      window.ITPDrawCharts.__redraw = true;
      showTip(e, '<strong>'+ (labels[idx] || '') +'</strong><span>Visits: '+(visits[idx]||0)+'</span><span>Clicks: '+(clicks[idx]||0)+'</span>');
      ctx.restore();
    };
    canvas.onmouseleave = hideTip;
  }

  function bar(canvas,data){
    var s = setup(canvas), ctx = s.ctx, w = s.w, h = s.h, pad = 38;
    var dark = isDarkCanvas(canvas);
    var items = [
      ['Valid', data.valid || 0, '#45c981'],
      ['Engaged', data.engaged || 0, '#20cfe1'],
      ['Low intent', data.low_intent || 0, '#f4d35e'],
      ['Risk', (data.suspicious||0)+(data.bot_like||0)+(data.repeated||0), '#f87171']
    ];
    var max = Math.max.apply(null, [1].concat(items.map(function(i){return i[1];})));
    ctx.clearRect(0,0,w,h);
    ctx.font = '13px system-ui';
    var cell = (w-pad*2)/items.length;
    var bw = Math.max(36, cell - 22);
    items.forEach(function(it,i){
      var x = pad + i*cell + 10;
      var bh = Math.max(0, (h-pad*2)*(it[1]/max));
      var y = h - pad - bh;
      ctx.fillStyle = it[2];
      roundedRect(ctx,x,y,bw,bh || 4,10);
      ctx.fill();
      ctx.fillStyle = dark ? '#eaf8ff' : '#071528';
      ctx.font = '800 14px system-ui';
      ctx.fillText(it[1],x,y-8);
      ctx.font = '12px system-ui';
      ctx.fillStyle = dark ? '#9fb6ce' : '#536b82';
      ctx.fillText(it[0],x,h-12);
    });
    canvas.onmousemove = function(e){
      var r = canvas.getBoundingClientRect();
      var x = e.clientX - r.left;
      var idx = Math.floor((x-pad)/cell);
      if(items[idx]) showTip(e, '<strong>'+items[idx][0]+'</strong><span>'+items[idx][1]+' sessions</span>');
    };
    canvas.onmouseleave = hideTip;
  }

  function stacks(){
    document.querySelectorAll('[data-itp-quality]').forEach(function(el){
      var q = parse(el,'data-itp-quality');
      var total = (q.valid||0)+(q.engaged||0)+(q.low_intent||0)+(q.suspicious||0)+(q.bot_like||0)+(q.repeated||0);
      if(!total){ el.innerHTML='<i class="valid" style="width:100%"></i>'; return; }
      var sus = (q.suspicious||0)+(q.bot_like||0)+(q.repeated||0);
      el.innerHTML = '<i class="valid" style="width:'+((q.valid||0)/total*100)+'%"></i><i class="engaged" style="width:'+((q.engaged||0)/total*100)+'%"></i><i class="low" style="width:'+((q.low_intent||0)/total*100)+'%"></i><i class="sus" style="width:'+(sus/total*100)+'%"></i>';
    });
  }



  function countryMaps(){
    if(!window.jsVectorMap) return;
    var coords = {
      US:[37.0902,-95.7129], CA:[56.1304,-106.3468], MX:[23.6345,-102.5528], BR:[-14.235,-51.9253], AR:[-38.4161,-63.6167], CL:[-35.6751,-71.543], CO:[4.5709,-74.2973], PE:[-9.19,-75.0152], VE:[6.4238,-66.5897], UY:[-32.5228,-55.7658], PY:[-23.4425,-58.4438], BO:[-16.2902,-63.5887], EC:[-1.8312,-78.1834],
      GB:[55.3781,-3.436], IE:[53.1424,-7.6921], FR:[46.2276,2.2137], ES:[40.4637,-3.7492], PT:[39.3999,-8.2245], DE:[51.1657,10.4515], NL:[52.1326,5.2913], BE:[50.5039,4.4699], CH:[46.8182,8.2275], IT:[41.8719,12.5674], AT:[47.5162,14.5501], SE:[60.1282,18.6435], NO:[60.472,8.4689], DK:[56.2639,9.5018], FI:[61.9241,25.7482], PL:[51.9194,19.1451], CZ:[49.8175,15.473], GR:[39.0742,21.8243], TR:[38.9637,35.2433], UA:[48.3794,31.1656], RU:[61.524,105.3188],
      AE:[23.4241,53.8478], SA:[23.8859,45.0792], QA:[25.3548,51.1839], IL:[31.0461,34.8516], EG:[26.8206,30.8025], ZA:[-30.5595,22.9375], NG:[9.082,8.6753], KE:[-0.0236,37.9062], MA:[31.7917,-7.0926],
      IN:[20.5937,78.9629], CN:[35.8617,104.1954], JP:[36.2048,138.2529], KR:[35.9078,127.7669], SG:[1.3521,103.8198], HK:[22.3193,114.1694], ID:[-0.7893,113.9213], MY:[4.2105,101.9758], TH:[15.87,100.9925], VN:[14.0583,108.2772], PH:[12.8797,121.774], PK:[30.3753,69.3451], BD:[23.685,90.3563],
      AU:[-25.2744,133.7751], NZ:[-40.9006,174.886]
    };
    document.querySelectorAll('[data-itp-country-map]').forEach(function(el, idx){
      if(el.__itpMapInit) return;
      var data = parse(el, 'data-itp-country-map') || {};
      var values = data.values || {};
      var labels = data.labels || {};
      var legend = data.legend || [];
      var markers = [];
      Object.keys(values).forEach(function(code){
        if(!coords[code]) return;
        markers.push({ name: (labels[code] || code) + ' · ' + values[code] + ' events', coords: coords[code] });
      });
      var selectorId = el.getAttribute('id');
      if(!selectorId){ selectorId = 'itp-jvm-map-' + idx + '-' + Math.random().toString(36).slice(2,7); el.setAttribute('id', selectorId); }
      try{
        el.__itpMapInit = new jsVectorMap({
          selector: '#' + selectorId,
          map: 'world',
          backgroundColor: 'transparent',
          zoomButtons: true,
          draggable: true,
          zoomOnScroll: false,
          regionStyle: {
            initial: { fill: '#dcecf7', stroke: '#ffffff', strokeWidth: 0.8, fillOpacity: 1 },
            hover: { fill: '#8ddff0', cursor: 'pointer' },
            selected: { fill: '#20cfe1' }
          },
          markerStyle: {
            initial: { r: 7, fill: '#23d5dc', stroke: '#ffffff', strokeWidth: 2, fillOpacity: 1 },
            hover: { fill: '#6d35e8', stroke: '#ffffff', cursor: 'pointer' }
          },
          markers: markers,
          series: { regions: [{ attribute: 'fill', scale: ['#dbeafe', '#22d3ee'], values: values, normalizeFunction: 'polynomial' }] },
          onRegionTooltipShow: function(event, tooltip, code){
            var count = values[code] || 0;
            var name = labels[code] || code;
            if(count){ tooltip.text(name + ' · ' + count + ' events'); }
          },
          onMarkerTooltipShow: function(event, tooltip, index){
            var m = markers[index];
            if(m && m.name){ tooltip.text(m.name); }
          }
        });
        if(!markers.length && legend.length === 0){ el.classList.add('itp-jvm-empty'); }
      } catch(e){
        el.innerHTML = '<div class="itp-empty-mini">Map could not be loaded. Check the local jsVectorMap files.</div>';
      }
    });
  }


  function saasLine(canvas, data){
    var s = setup(canvas), ctx = s.ctx, w = s.w, h = s.h, pad = 42;
    var labels = data.labels || [], visits = data.visits || [], clicks = data.clicks || [];
    if(!labels.length){ labels = ['Now']; visits = [0]; clicks = [0]; }
    var riskTotal = parseFloat(canvas.getAttribute('data-itp-saas-risk') || '0') || 0;
    var risk = labels.map(function(_, i){ return Math.max(0, Math.round(riskTotal * (0.38 + ((i % 3) * 0.13)))); });
    var max = Math.max.apply(null, [1].concat(visits, clicks, risk));
    var progress = canvas.__itpSaasProgress;
    if(progress == null){ progress = 0; canvas.__itpSaasProgress = 0; }
    ctx.clearRect(0,0,w,h);

    var bg = ctx.createLinearGradient(0,0,w,h);
    bg.addColorStop(0,'rgba(34,211,238,.055)');
    bg.addColorStop(.55,'rgba(124,58,237,.045)');
    bg.addColorStop(1,'rgba(255,255,255,.018)');
    ctx.fillStyle = bg;
    roundedRect(ctx,0,0,w,h,18);
    ctx.fill();

    ctx.save();
    ctx.beginPath();
    roundedRect(ctx,0,0,w,h,18);
    ctx.clip();
    ctx.strokeStyle = 'rgba(218,237,255,.10)';
    ctx.lineWidth = 1;
    ctx.font = '11px system-ui';
    ctx.fillStyle = 'rgba(202,220,237,.56)';
    for(var i=0;i<5;i++){
      var yy = pad + (h-pad*1.7)*i/4;
      ctx.beginPath(); ctx.moveTo(pad, yy); ctx.lineTo(w-pad, yy); ctx.stroke();
      var pct = Math.round((1 - i/4) * max);
      ctx.fillText(String(pct), 14, yy + 4);
    }
    for(var v=0; v<labels.length; v++){
      var xx = pad + (w-pad*2)*(v/(Math.max(1,labels.length-1)));
      ctx.strokeStyle = 'rgba(218,237,255,.055)';
      ctx.beginPath(); ctx.moveTo(xx,pad); ctx.lineTo(xx,h-pad); ctx.stroke();
    }

    function pts(arr){
      return arr.map(function(val,i){ return {x: pad + (w-pad*2)*(i/(Math.max(1,arr.length-1))), y: h-pad-((h-pad*1.9)*(val/max)), v: val}; });
    }
    function drawSeries(arr, color, fillTop, width){
      var p = pts(arr), clipW = pad + (w-pad*2)*progress;
      ctx.save();
      ctx.beginPath(); ctx.rect(0,0,clipW,h); ctx.clip();
      if(fillTop){
        ctx.beginPath();
        p.forEach(function(pt,i){ if(i===0) ctx.moveTo(pt.x,pt.y); else ctx.lineTo(pt.x,pt.y); });
        ctx.lineTo(p[p.length-1].x,h-pad); ctx.lineTo(p[0].x,h-pad); ctx.closePath();
        var fg = ctx.createLinearGradient(0,pad,0,h-pad);
        fg.addColorStop(0,fillTop); fg.addColorStop(1,'rgba(255,255,255,0)');
        ctx.fillStyle = fg; ctx.fill();
      }
      ctx.strokeStyle = color; ctx.lineWidth = width || 4; ctx.lineCap = 'round'; ctx.lineJoin = 'round';
      ctx.shadowColor = color; ctx.shadowBlur = 14;
      ctx.beginPath();
      p.forEach(function(pt,i){ if(i===0) ctx.moveTo(pt.x,pt.y); else ctx.lineTo(pt.x,pt.y); });
      ctx.stroke();
      ctx.shadowBlur = 0;
      p.forEach(function(pt){
        if(pt.x > clipW + 3) return;
        ctx.fillStyle = '#0b1422'; ctx.strokeStyle = color; ctx.lineWidth = 3;
        ctx.beginPath(); ctx.arc(pt.x,pt.y,5,0,Math.PI*2); ctx.fill(); ctx.stroke();
      });
      ctx.restore();
      return p;
    }
    var vPts = drawSeries(visits, '#22d3ee', 'rgba(34,211,238,.24)', 4.6);
    drawSeries(clicks, '#8b5cf6', 'rgba(139,92,246,.10)', 3.8);
    drawSeries(risk, '#fb7185', null, 2.4);

    ctx.shadowBlur = 0;
    ctx.fillStyle = 'rgba(202,220,237,.65)';
    ctx.textAlign = 'center';
    ctx.font = '11px system-ui';
    labels.forEach(function(l,i){
      if(labels.length > 9 && i % Math.ceil(labels.length/7) !== 0 && i !== labels.length-1) return;
      var x = pad + (w-pad*2)*(i/(Math.max(1,labels.length-1)));
      ctx.fillText(l, x, h-13);
    });
    ctx.restore();

    canvas.onmousemove = function(e){
      var r = canvas.getBoundingClientRect();
      var x = e.clientX - r.left;
      var idx = Math.round((x-pad)/(w-pad*2)*(labels.length-1));
      idx = Math.max(0, Math.min(labels.length-1, idx));
      showTip(e, '<strong>'+ (labels[idx] || '') +'</strong><span>Visits: '+(visits[idx]||0)+'</span><span>Clicks: '+(clicks[idx]||0)+'</span><span>Risk pressure: '+(risk[idx]||0)+'</span>');
    };
    canvas.onmouseleave = hideTip;

    if(canvas.__itpSaasAnimated) return;
    canvas.__itpSaasAnimated = true;
    var start = performance.now();
    function anim(now){
      var t = Math.min(1, (now - start) / 900);
      canvas.__itpSaasProgress = 1 - Math.pow(1 - t, 3);
      saasLine(canvas, data);
      if(t < 1) requestAnimationFrame(anim);
    }
    requestAnimationFrame(anim);
  }

  window.ITPDrawCharts = function(){
    document.querySelectorAll('[data-itp-line]').forEach(function(c){ line(c,parse(c,'data-itp-line')); });
    document.querySelectorAll('[data-itp-bar]').forEach(function(c){ bar(c,parse(c,'data-itp-bar')); });
    document.querySelectorAll('[data-itp-saas-line]').forEach(function(c){ saasLine(c,parse(c,'data-itp-saas-line')); });
    stacks();
    countryMaps();
  };

  document.addEventListener('DOMContentLoaded', window.ITPDrawCharts);
  window.addEventListener('resize', function(){
    clearTimeout(window.__itpChartTimer);
    window.__itpChartTimer = setTimeout(window.ITPDrawCharts, 160);
  });
})();