/* global React, Icon, useInView, useCountUp, fmt, useLivePulse, useTilt */
const { useEffect, useRef, useState, useMemo } = React;

/* ============ Animated SVG chart components ============ */

function VisitorInsightsChart({ width = 620, height = 150 }) {
  const [ref, inView] = useInView(0.1);
  const pad = { l: 30, r: 10, t: 10, b: 22 };
  const W = width - pad.l - pad.r;
  const H = height - pad.t - pad.b;
  const ymax = 1600;
  const active  = [820, 1100, 1350, 1480, 1420, 1550, 1480, 1350, 1100, 900, 750, 700];
  const total   = [780, 1050, 1280, 1420, 1360, 1490, 1400, 1280, 1020, 820, 680, 640];
  const retrn   = [520,  680,  920, 1100, 1140, 1220, 1180, 1080,  880, 700, 580, 540];
  const newU    = [210,  280,  330,  360,  340,  380,  360,  320,  260, 220, 190, 180];
  const labels  = ['Nov', '', 'Dec', '', 'Jan', '', 'Feb', '', 'Mar', '', 'Apr', ''];
  const n = active.length;
  const stepX = W / (n - 1);
  const smooth = (values) => {
    const pts = values.map((v, i) => ({ x: pad.l + i * stepX, y: pad.t + H - (v / ymax) * H }));
    let d = `M ${pts[0].x} ${pts[0].y}`;
    for (let i = 0; i < pts.length - 1; i++) {
      const p0 = pts[Math.max(0, i - 1)];
      const p1 = pts[i];
      const p2 = pts[i + 1];
      const p3 = pts[Math.min(pts.length - 1, i + 2)];
      d += ` C ${p1.x + (p2.x - p0.x) / 6} ${p1.y + (p2.y - p0.y) / 6}, ${p2.x - (p3.x - p1.x) / 6} ${p2.y - (p3.y - p1.y) / 6}, ${p2.x} ${p2.y}`;
    }
    return d;
  };
  const gridYs = [0, 400, 800, 1200, 1600];
  const series = [
    { vals: active, color: '#10B981', delay: 0.1 },
    { vals: total,  color: '#2F7BFF', delay: 0.3 },
    { vals: retrn,  color: '#EC4899', delay: 0.5 },
    { vals: newU,   color: '#8B5CF6', delay: 0.7 },
  ];
  return (
    <svg ref={ref} viewBox={`0 0 ${width} ${height}`} width="100%" height={height} style={{ display: 'block' }}>
      {gridYs.map((v, i) => {
        const y = pad.t + H - (v / ymax) * H;
        return (
          <g key={i}>
            <line x1={pad.l} x2={width - pad.r} y1={y} y2={y} stroke="#EDF0F7" strokeWidth="1"/>
            <text x={pad.l - 6} y={y + 3} textAnchor="end" fontSize="9" fill="#9AA3BD" fontFamily="JetBrains Mono">{v}</text>
          </g>
        );
      })}
      {labels.map((l, i) => l ? (
        <text key={i} x={pad.l + i * stepX} y={height - 6} textAnchor="middle" fontSize="9" fill="#9AA3BD" fontFamily="JetBrains Mono">{l}</text>
      ) : null)}
      {series.map((s, idx) => (
        <path
          key={idx}
          d={smooth(s.vals)}
          fill="none"
          stroke={s.color}
          strokeWidth="2"
          strokeLinecap="round"
          strokeLinejoin="round"
          style={{
            strokeDasharray: 2000,
            strokeDashoffset: inView ? 0 : 2000,
            transition: `stroke-dashoffset 2s cubic-bezier(.2,.8,.2,1) ${s.delay}s`,
          }}
        />
      ))}
      {series.map((s, idx) => {
        const last = s.vals[s.vals.length - 1];
        const x = pad.l + (s.vals.length - 1) * stepX;
        const y = pad.t + H - (last / ymax) * H;
        return inView ? (
          <g key={`d${idx}`} style={{ animation: `fadeIn .5s ease ${1.8 + idx * 0.1}s both` }}>
            <circle cx={x} cy={y} r="6" fill={s.color} opacity="0.2">
              <animate attributeName="r" values="3;8;3" dur="2.2s" repeatCount="indefinite"/>
              <animate attributeName="opacity" values="0.25;0;0.25" dur="2.2s" repeatCount="indefinite"/>
            </circle>
            <circle cx={x} cy={y} r="2.8" fill={s.color}/>
          </g>
        ) : null;
      })}
    </svg>
  );
}

function TargetRealityChart({ width = 300, height = 120 }) {
  const [ref, inView] = useInView(0.1);
  const pad = { l: 22, r: 8, t: 8, b: 20 };
  const W = width - pad.l - pad.r;
  const H = height - pad.t - pad.b;
  const ymax = 200;
  const groups = [
    { name: 'Fb',  a: 88,  b: 150 },
    { name: 'Ig',  a: 140, b: 170 },
    { name: 'Tt',  a: 120, b: 165 },
    { name: 'Li',  a: 75,  b: 130 },
    { name: 'Web', a: 180, b: 155 },
  ];
  const groupW = W / groups.length;
  const barW = (groupW - 6) / 2;
  return (
    <svg ref={ref} viewBox={`0 0 ${width} ${height}`} width="100%" height={height}>
      <defs>
        <linearGradient id="bar-green" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="#10B981"/>
          <stop offset="100%" stopColor="#34D399"/>
        </linearGradient>
        <linearGradient id="bar-amber" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="#F59E0B"/>
          <stop offset="100%" stopColor="#FBBF24"/>
        </linearGradient>
      </defs>
      {[0, 50, 100, 150, 200].map((v) => {
        const y = pad.t + H - (v / ymax) * H;
        return <line key={v} x1={pad.l} x2={width - pad.r} y1={y} y2={y} stroke="#EDF0F7" strokeWidth="1"/>;
      })}
      {groups.map((g, i) => {
        const gx = pad.l + i * groupW + 3;
        const h1 = (g.a / ymax) * H;
        const h2 = (g.b / ymax) * H;
        return (
          <g key={g.name}>
            <rect x={gx} width={barW} y={pad.t + H - (inView ? h1 : 0)} height={inView ? h1 : 0}
              fill="url(#bar-green)" rx="2"
              style={{ transition: `height 1.1s cubic-bezier(.2,.8,.2,1) ${i * 0.07}s, y 1.1s cubic-bezier(.2,.8,.2,1) ${i * 0.07}s` }}/>
            <rect x={gx + barW + 3} width={barW} y={pad.t + H - (inView ? h2 : 0)} height={inView ? h2 : 0}
              fill="url(#bar-amber)" rx="2"
              style={{ transition: `height 1.1s cubic-bezier(.2,.8,.2,1) ${i * 0.07 + 0.1}s, y 1.1s cubic-bezier(.2,.8,.2,1) ${i * 0.07 + 0.1}s` }}/>
            <text x={gx + groupW / 2 - 3} y={height - 5} textAnchor="middle" fontSize="9" fill="#9AA3BD" fontFamily="JetBrains Mono">{g.name}</text>
          </g>
        );
      })}
    </svg>
  );
}

function ExpensesBarChart({ width = 320, height = 120 }) {
  const [ref, inView] = useInView(0.1);
  const pad = { l: 22, r: 8, t: 8, b: 20 };
  const W = width - pad.l - pad.r;
  const H = height - pad.t - pad.b;
  const ymax = 20;
  const months = [
    { m: 'Nov', p: 10, a: 12 },
    { m: 'Dec', p: 14, a: 13 },
    { m: 'Jan', p: 16, a: 17 },
    { m: 'Feb', p: 7,  a: 8  },
    { m: 'Mar', p: 12, a: 10 },
    { m: 'Apr', p: 9,  a: 11 },
  ];
  const groupW = W / months.length;
  const barW = (groupW - 5) / 2;
  return (
    <svg ref={ref} viewBox={`0 0 ${width} ${height}`} width="100%" height={height}>
      <defs>
        <linearGradient id="bar-blue" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="#60A5FA"/>
          <stop offset="100%" stopColor="#93C5FD"/>
        </linearGradient>
        <linearGradient id="bar-teal" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="#10B981"/>
          <stop offset="100%" stopColor="#34D399"/>
        </linearGradient>
      </defs>
      {[0, 5, 10, 15, 20].map((v) => {
        const y = pad.t + H - (v / ymax) * H;
        return (
          <g key={v}>
            <line x1={pad.l} x2={width - pad.r} y1={y} y2={y} stroke="#EDF0F7"/>
            <text x={pad.l - 4} y={y + 3} fontSize="8" textAnchor="end" fill="#9AA3BD" fontFamily="JetBrains Mono">{v}k</text>
          </g>
        );
      })}
      {months.map((g, i) => {
        const gx = pad.l + i * groupW + 3;
        const h1 = (g.p / ymax) * H;
        const h2 = (g.a / ymax) * H;
        return (
          <g key={g.m}>
            <rect x={gx} width={barW} y={pad.t + H - (inView ? h1 : 0)} height={inView ? h1 : 0}
              fill="url(#bar-blue)" rx="2"
              style={{ transition: `height 1.1s cubic-bezier(.2,.8,.2,1) ${i * 0.07}s, y 1.1s cubic-bezier(.2,.8,.2,1) ${i * 0.07}s` }}/>
            <rect x={gx + barW + 3} width={barW} y={pad.t + H - (inView ? h2 : 0)} height={inView ? h2 : 0}
              fill="url(#bar-teal)" rx="2"
              style={{ transition: `height 1.1s cubic-bezier(.2,.8,.2,1) ${i * 0.07 + 0.1}s, y 1.1s cubic-bezier(.2,.8,.2,1) ${i * 0.07 + 0.1}s` }}/>
            <text x={gx + groupW / 2 - 2} y={height - 5} textAnchor="middle" fontSize="8" fill="#9AA3BD" fontFamily="JetBrains Mono">{g.m}</text>
          </g>
        );
      })}
    </svg>
  );
}

function ExpensesPie({ size = 110 }) {
  const [ref, inView] = useInView(0.1);
  const cx = size / 2, cy = size / 2, r = size / 2 - 6;
  const slices = [
    { name: 'Google Ads', v: 32.3, color: '#F59E0B' },
    { name: 'Facebook',   v: 16.1, color: '#60A5FA' },
    { name: 'Instagram',  v: 16.1, color: '#EC4899' },
    { name: 'TikTok',     v: 16.1, color: '#22D3EE' },
    { name: 'LinkedIn',   v: 16.1, color: '#8B5CF6' },
    { name: 'Other',      v:  3.3, color: '#CBD5E1' },
  ];
  let startAngle = -Math.PI / 2;
  const paths = slices.map((s) => {
    const angle = (s.v / 100) * Math.PI * 2;
    const endAngle = startAngle + angle;
    const x1 = cx + r * Math.cos(startAngle);
    const y1 = cy + r * Math.sin(startAngle);
    const x2 = cx + r * Math.cos(endAngle);
    const y2 = cy + r * Math.sin(endAngle);
    const largeArc = angle > Math.PI ? 1 : 0;
    const d = `M ${cx} ${cy} L ${x1} ${y1} A ${r} ${r} 0 ${largeArc} 1 ${x2} ${y2} Z`;
    startAngle = endAngle;
    return { d, color: s.color, name: s.name, v: s.v };
  });
  return (
    <div ref={ref} style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
      <svg viewBox={`0 0 ${size} ${size}`} width={size} height={size} style={{ flexShrink: 0 }}>
        <g style={{ transformOrigin: 'center', transform: inView ? 'scale(1) rotate(0deg)' : 'scale(0.5) rotate(-90deg)', transition: 'transform 1s cubic-bezier(.2,.8,.2,1)' }}>
          {paths.map((p, i) => (
            <path key={i} d={p.d} fill={p.color} stroke="#fff" strokeWidth="1.5"
              style={{ opacity: inView ? 1 : 0, transition: `opacity .3s ease ${0.8 + i * 0.08}s` }}/>
          ))}
        </g>
        <circle cx={cx} cy={cy} r={r * 0.55} fill="#fff"/>
        <text x={cx} y={cy - 2} textAnchor="middle" fontSize="8" fill="#9AA3BD" fontFamily="JetBrains Mono" letterSpacing="0.5">SPEND</text>
        <text x={cx} y={cy + 10} textAnchor="middle" fontSize="11" fontWeight="700" fill="#0B1033" fontFamily="JetBrains Mono">€3.1k</text>
      </svg>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '3px 10px', flex: 1 }}>
        {slices.map((s) => (
          <div key={s.name} style={{ display: 'flex', alignItems: 'center', gap: 5, fontSize: 9.5, color: 'var(--ink-soft)' }}>
            <span style={{ width: 7, height: 7, borderRadius: 2, background: s.color, flexShrink: 0 }}/>
            <span style={{ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{s.name}</span>
            <span style={{ fontFamily: 'var(--font-mono)', fontWeight: 600, color: 'var(--ink-2)' }}>{s.v}%</span>
          </div>
        ))}
      </div>
    </div>
  );
}

function Sparkline({ values, color, width = 60, height = 22 }) {
  const [ref, inView] = useInView(0.1);
  const min = Math.min(...values);
  const max = Math.max(...values);
  const range = max - min || 1;
  const pts = values.map((v, i) => {
    const x = (i / (values.length - 1)) * width;
    const y = height - 2 - ((v - min) / range) * (height - 4);
    return `${x},${y}`;
  }).join(' ');
  return (
    <svg ref={ref} viewBox={`0 0 ${width} ${height}`} width={width} height={height} style={{ display: 'block' }}>
      <polyline points={pts} fill="none" stroke={color} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"
        style={{ strokeDasharray: 200, strokeDashoffset: inView ? 0 : 200, transition: 'stroke-dashoffset 1.2s ease' }}/>
    </svg>
  );
}

/* AreaLineChart used in FeatureBento */
function AreaLineChart({ width = 620, height = 180 }) {
  const [ref, inView] = useInView(0.1);
  const pad = { l: 28, r: 12, t: 12, b: 24 };
  const W = width - pad.l - pad.r;
  const H = height - pad.t - pad.b;
  const ymax = 2500;
  const reachVals = [0, 200, 900, 600, 2100, 1900, 900, 700, 1400, 1300, 700, 500, 400, 500];
  const viewsVals = reachVals.map((v, i) => Math.round(v * 0.55 + (i % 3) * 15));
  const folVals = reachVals.map((v) => Math.round(v * 0.85 + 50));
  const n = reachVals.length;
  const stepX = W / (n - 1);
  const smooth = (values) => {
    const pts = values.map((v, i) => ({ x: pad.l + i * stepX, y: pad.t + H - (v / ymax) * H }));
    let d = `M ${pts[0].x} ${pts[0].y}`;
    for (let i = 0; i < pts.length - 1; i++) {
      const p0 = pts[Math.max(0, i - 1)];
      const p1 = pts[i];
      const p2 = pts[i + 1];
      const p3 = pts[Math.min(pts.length - 1, i + 2)];
      d += ` C ${p1.x + (p2.x - p0.x) / 6} ${p1.y + (p2.y - p0.y) / 6}, ${p2.x - (p3.x - p1.x) / 6} ${p2.y - (p3.y - p1.y) / 6}, ${p2.x} ${p2.y}`;
    }
    return d;
  };
  const area = (values) => {
    const path = smooth(values);
    return `${path} L ${pad.l + (n - 1) * stepX} ${pad.t + H} L ${pad.l} ${pad.t + H} Z`;
  };
  return (
    <svg ref={ref} viewBox={`0 0 ${width} ${height}`} width="100%" height={height}>
      <defs>
        <linearGradient id="area-pink" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="#EC4899" stopOpacity="0.35"/>
          <stop offset="100%" stopColor="#EC4899" stopOpacity="0"/>
        </linearGradient>
      </defs>
      {[0, 500, 1000, 1500, 2000, 2500].map((v) => {
        const y = pad.t + H - (v / ymax) * H;
        return (
          <g key={v}>
            <line x1={pad.l} x2={width - pad.r} y1={y} y2={y} stroke="#EDF0F7"/>
            <text x={pad.l - 4} y={y + 3} fontSize="9" textAnchor="end" fill="#9AA3BD" fontFamily="JetBrains Mono">{v}</text>
          </g>
        );
      })}
      <path d={area(folVals)} fill="url(#area-pink)" style={{ opacity: inView ? 1 : 0, transition: 'opacity 1.2s ease 0.3s' }}/>
      <path d={smooth(folVals)} fill="none" stroke="#EC4899" strokeWidth="2" style={{ strokeDasharray: 2000, strokeDashoffset: inView ? 0 : 2000, transition: 'stroke-dashoffset 2s ease 0.1s' }}/>
      <path d={smooth(reachVals)} fill="none" stroke="#10B981" strokeWidth="2" style={{ strokeDasharray: 2000, strokeDashoffset: inView ? 0 : 2000, transition: 'stroke-dashoffset 2s ease 0.3s' }}/>
      <path d={smooth(viewsVals)} fill="none" stroke="#2F7BFF" strokeWidth="1.8" style={{ strokeDasharray: 2000, strokeDashoffset: inView ? 0 : 2000, transition: 'stroke-dashoffset 2s ease 0.5s' }}/>
    </svg>
  );
}

function SparklineOld({ values, color, width = 60, height = 22 }) {
  const [ref, inView] = useInView(0.1);
  const min = Math.min(...values);
  const max = Math.max(...values);
  const range = max - min || 1;
  const pts = values.map((v, i) => {
    const x = (i / (values.length - 1)) * width;
    const y = height - 2 - ((v - min) / range) * (height - 4);
    return `${x},${y}`;
  }).join(' ');
  return (
    <svg ref={ref} viewBox={`0 0 ${width} ${height}`} width={width} height={height} style={{ display: 'block' }}>
      <polyline points={pts} fill="none" stroke={color} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"
        style={{ strokeDasharray: 200, strokeDashoffset: inView ? 0 : 200, transition: 'stroke-dashoffset 1.2s ease' }}/>
    </svg>
  );
}

/* ============ Dashboard sidebar ============ */
function Sidebar() {
  return (
    <aside className="db-sidebar">
      <div className="db-sidebar-logo">
        <div className="mark">
          <svg viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
            <path d="M4 18V8M10 18V4M16 18v-8M22 18v-5"/>
          </svg>
        </div>
        <div>
          <div className="name">MarkFlow</div>
          <div className="tag">ANALYTICS</div>
        </div>
      </div>
      <div className="db-nav-item active"><Icon name="dashboard" size={14}/> Dashboard</div>
      <div className="db-nav-item expanded"><Icon name="chart" size={14}/> Analytics <span className="chev"><Icon name="chevron" size={12}/></span></div>
      <div className="db-nav-item sub">Web</div>
      <div className="db-nav-item sub">Social media</div>
      <div className="db-section-label">MANAGEMENT</div>
      <div className="db-nav-item"><Icon name="edit" size={14}/> Content Plan</div>
      <div className="db-nav-item"><Icon name="bolt" size={14}/> Create Campaign</div>
      <div className="db-nav-item"><Icon name="wallet" size={14}/> Budget</div>
      <div className="db-nav-item"><Icon name="layers" size={14}/> Landing Pages</div>
      <div className="db-section-label">STRATEGY</div>
      <div className="db-nav-item"><Icon name="sparkle" size={14}/> Improvements</div>
      <div className="db-nav-item"><Icon name="brand" size={14}/> Ad channels</div>
      <div className="db-nav-item"><Icon name="results" size={14}/> Results</div>
    </aside>
  );
}

/* ============ Socials tiles ============ */
function SocialTile({ brand, handle, reach, eng, color, bg, spark, delay }) {
  const [ref, inView] = useInView(0.1);
  return (
    <div ref={ref} className="db-social-tile" style={{ opacity: inView ? 1 : 0, transform: inView ? 'translateY(0)' : 'translateY(8px)', transition: `all .5s ease ${delay || 0}s` }}>
      <div className="db-social-head">
        <div className="db-social-logo" style={{ background: bg, color }}>
          <Icon name={brand} size={13}/>
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div className="db-social-name">{brand === 'instagram' ? 'Instagram' : brand === 'facebook' ? 'Facebook' : brand === 'tiktok' ? 'TikTok' : 'LinkedIn'}</div>
          <div className="db-social-handle">{handle}</div>
        </div>
        <Sparkline values={spark} color={color} width={50} height={20}/>
      </div>
      <div className="db-social-nums">
        <div>
          <div className="k">REACH</div>
          <div className="v">{reach}</div>
        </div>
        <div>
          <div className="k">ENG</div>
          <div className="v" style={{ color: 'var(--emerald)' }}>{eng}</div>
        </div>
      </div>
    </div>
  );
}

/* ============ Main hero dashboard ============ */
function HeroDashboardSkeleton() {
  // Lightweight placeholder rendered during the blur-in phase. Same layout shell,
  // but no SVG charts, no live counters, no animating hooks, no ticking effects.
  const rows = 4, cols = 6;
  const blockIdx = Array.from({ length: rows * cols }, (_, i) => i);
  return (
    <div className="hero-dashboard hero-dashboard-skeleton" aria-hidden="true">
      <div className="dashboard-shell">
        <Sidebar/>
        <div className="db-main">
          <div className="db-topbar">
            <span>Marketing Overview</span>
            <div className="right">
              <div className="sk-bubble"/>
              <div className="sk-bubble"/>
              <div className="sk-bubble"/>
            </div>
          </div>
          <div className="db-content db-skeleton-grid">
            {blockIdx.map(i => <div key={i} className="sk-card" style={{ gridColumn: i % 6 < 4 ? 'span 2' : 'span 3' }}/>)}
          </div>
        </div>
      </div>
    </div>
  );
}

function HeroDashboard() {
  // useTilt disabled for hero dashboard — the mouse-move rotateX/rotateY was triggering
  // re-composites on every pointer move, causing frame drops during scroll+hover.
  const tiltRef = useRef(null);
  const active24 = useLivePulse(53, { jitter: 0.06, periodMs: 3500 });
  const active7 = useLivePulse(439, { jitter: 0.03, periodMs: 4200 });
  const active28 = useLivePulse(1561, { jitter: 0.015, periodMs: 5200 });
  const [active24Ref, active24Val] = useCountUp(active24, { duration: 1200 });
  const [active7Ref, active7Val] = useCountUp(active7, { duration: 1400 });
  const [active28Ref, active28Val] = useCountUp(active28, { duration: 1800 });
  const [totalRef, totalVal] = useCountUp(1104, { duration: 1800 });
  const [eRateRef, eRateVal] = useCountUp(0.6, { duration: 1400, decimals: 2 });
  const [reachRef, reachVal] = useCountUp(8541, { duration: 1600 });
  const [spendRef, spendVal] = useCountUp(3120, { duration: 1400 });

  const [channelsRef, channelsInView] = useInView(0.1);
  const channels = [
    { name: 'Organic search', pct: 64.6, grad: 'linear-gradient(90deg, #2F7BFF, #7AB8FF)' },
    { name: 'Direct', pct: 31.1, grad: 'linear-gradient(90deg, #10B981, #86EFAC)' },
    { name: 'Referral', pct: 2.4, grad: 'linear-gradient(90deg, #8B5CF6, #D8B4FE)' },
  ];

  const channelPerf = [
    { icon: 'instagram', name: 'Instagram',  reach: '8,509',  eng: '54.2%', spend: '—',     color: '#EC4899' },
    { icon: 'facebook',  name: 'Facebook',   reach: '32',     eng: '3.1%',  spend: '—',     color: '#2F7BFF' },
    { icon: 'globe',     name: 'Web (GA4)',  reach: '856',    eng: '—',     spend: '—',     color: '#10B981' },
    { icon: 'brand',     name: 'Meta Ads',   reach: '21,279', eng: '0.25%', spend: '€19.91', color: '#8B5CF6' },
  ];

  const aiInsights = [
    { icon: 'warn',      tone: 'warn',     text: 'Instagram engagement 54.2% — unusually high', sub: 'Verify data · industry avg 1-5%' },
    { icon: 'lightbulb', tone: 'info',     text: 'Instagram reach 265.9× higher than Facebook',  sub: 'Large content volume on IG' },
    { icon: 'checkCircle', tone: 'success',  text: 'Bounce rate 42.8% — below industry avg',       sub: 'Industry avg 55-65%' },
    { icon: 'bolt',     tone: 'accent',   text: 'CPC €0.27 — below industry avg',               sub: '75 clicks, avg €0.50-2.00' },
  ];

  return (
    <div className="hero-dashboard" ref={tiltRef}>
      <div className="dashboard-shell">
        <Sidebar/>

        <div className="db-main">
          <div className="db-topbar">
            <span>Marketing Overview</span>
            <div className="right">
              <div className="icon-bubble"><Icon name="sparkle" size={13}/></div>
              <div className="db-avatar">O</div>
              <span style={{ fontSize: 12, opacity: 0.8, lineHeight: 1.2 }}>
                oskars<br/><span style={{ fontSize: 10, opacity: 0.6 }}>Admin</span>
              </span>
            </div>
          </div>

          <div className="db-content">
           <div className="db-content-inner">
            {/* Header with chips */}
            <div className="db-card db-header-card">
              <div>
                <div className="eyebrow-chip" style={{ color: 'var(--emerald)' }}>● LIVE OVERVIEW</div>
                <div className="title">SPAR Latvija</div>
                <div className="meta">
                  <span>📍 Cross-channel</span>
                  <span>•</span>
                  <span>Updated Apr 20, 17:52 UTC</span>
                </div>
              </div>
              <div className="chips">
                <span className="chip chip-blue">Today</span>
                <span className="chip chip-active">Last 7 Days</span>
                <span className="chip chip-neutral">Last 28 Days</span>
              </div>
            </div>

            {/* KPI strip */}
            <div className="db-kpi-strip">
              <div className="db-kpi">
                <div className="kpi-icon" style={{ background: '#EEF1FA', color: '#6C5CE7' }}><Icon name="users" size={12}/></div>
                <div>
                  <div className="kpi-k">TOTAL REACH</div>
                  <div className="kpi-v" ref={reachRef}>{fmt(reachVal)}</div>
                  <div className="kpi-s">All channels</div>
                </div>
              </div>
              <div className="db-kpi">
                <div className="kpi-icon" style={{ background: '#E9F7EF', color: '#10B981' }}><Icon name="globe" size={12}/></div>
                <div>
                  <div className="kpi-k">WEB TRAFFIC</div>
                  <div className="kpi-v">856</div>
                  <div className="kpi-s">GA4 · 30d</div>
                </div>
              </div>
              <div className="db-kpi">
                <div className="kpi-icon" style={{ background: '#FFF4E0', color: '#F59E0B' }}><Icon name="wallet" size={12}/></div>
                <div>
                  <div className="kpi-k">AD SPEND</div>
                  <div className="kpi-v" ref={spendRef}>€{fmt(spendVal)}</div>
                  <div className="kpi-s">Meta + Google</div>
                </div>
              </div>
              <div className="db-kpi">
                <div className="kpi-icon" style={{ background: '#E8F0FF', color: '#2F7BFF' }}><Icon name="bars" size={12}/></div>
                <div>
                  <div className="kpi-k">RESULTS</div>
                  <div className="kpi-v">4,691</div>
                  <div className="kpi-s">Clicks + interact.</div>
                </div>
              </div>
              <div className="db-kpi">
                <div className="kpi-icon" style={{ background: '#FFE7F0', color: '#EC4899' }}><Icon name="heart" size={12}/></div>
                <div>
                  <div className="kpi-k">ENG. RATE</div>
                  <div className="kpi-v" ref={eRateRef}>{eRateVal}%</div>
                  <div className="kpi-s">Site-wide</div>
                </div>
              </div>
            </div>

            {/* Visitor insights (big chart) + Audience stats side */}
            <div className="db-row db-row-2a">
              <div className="db-card db-chart-card">
                <div className="title">
                  <span>Visitor Insights <span style={{ fontSize: 10, fontWeight: 500, color: 'var(--muted)', marginLeft: 6 }}>Last 6 months</span></span>
                  <span className="dropdown">Last 6 months ▾</span>
                </div>
                <VisitorInsightsChart/>
                <div className="db-chart-legend">
                  <span><span className="dot" style={{ background: '#10B981' }}/>Active</span>
                  <span><span className="dot" style={{ background: '#2F7BFF' }}/>Total</span>
                  <span><span className="dot" style={{ background: '#EC4899' }}/>Returning</span>
                  <span><span className="dot" style={{ background: '#8B5CF6' }}/>New</span>
                </div>
              </div>

              <div className="db-card">
                <div className="db-stat-label"><Icon name="users" size={11}/> AUDIENCE</div>
                <div className="db-audience-col">
                  <div className="item">
                    <div className="k">Active (24h)</div>
                    <div className="v" ref={active24Ref}>{fmt(active24Val)}</div>
                    <div className="sub">New users <b style={{ color: 'var(--ink)' }}>39</b></div>
                  </div>
                  <div className="item">
                    <div className="k">Active (7d)</div>
                    <div className="v" ref={active7Ref}>{fmt(active7Val)}</div>
                  </div>
                  <div className="item">
                    <div className="k">Active (28d)</div>
                    <div className="v blue" ref={active28Ref}>{fmt(active28Val)}</div>
                  </div>
                  <div className="db-audience-highlight">
                    <div>
                      <div style={{ fontSize: 9, color: 'var(--emerald)', fontWeight: 600 }}>Mar total users</div>
                      <div style={{ fontFamily: 'var(--font-display)', fontSize: 18, fontWeight: 700 }} ref={totalRef}>{fmt(totalVal)}</div>
                    </div>
                    <div style={{ textAlign: 'right' }}>
                      <div style={{ fontSize: 10, color: 'var(--emerald)', fontWeight: 700 }}>↑ +5.3%</div>
                      <div style={{ fontSize: 9, color: 'var(--muted)' }}>vs Feb</div>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            {/* Row 3: Origin + Target + Devices */}
            <div className="db-row db-row-3eq">
              <div className="db-card" ref={channelsRef}>
                <div className="db-card-title">
                  <span>Origin of Engagement</span>
                  <div style={{ width: 22, height: 22, borderRadius: 6, background: '#EEF1FA', display: 'grid', placeItems: 'center', color: 'var(--blue)' }}>
                    <Icon name="bars" size={12}/>
                  </div>
                </div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 9, marginTop: 6 }}>
                  {channels.map((c, i) => (
                    <div key={c.name}>
                      <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11, marginBottom: 2 }}>
                        <span style={{ color: 'var(--ink)', fontWeight: 600 }}>{c.name}</span>
                        <span style={{ fontFamily: 'var(--font-mono)', fontWeight: 600, color: 'var(--ink-2)' }}>{c.pct}%</span>
                      </div>
                      <div style={{ height: 4, background: '#EDF0F7', borderRadius: 3, overflow: 'hidden' }}>
                        <div style={{ height: '100%', background: c.grad, width: channelsInView ? `${c.pct}%` : 0, transition: `width 1.5s cubic-bezier(.2,.8,.2,1) ${i * 0.15}s`, borderRadius: 3 }}/>
                      </div>
                    </div>
                  ))}
                </div>
              </div>

              <div className="db-card">
                <div className="db-card-title">
                  <span>Target vs Reality</span>
                  <span style={{ fontSize: 9, color: 'var(--muted)' }}>per month</span>
                </div>
                <TargetRealityChart/>
                <div style={{ display: 'flex', gap: 10, fontSize: 9, color: 'var(--muted)', marginTop: 4 }}>
                  <span><span style={{ display: 'inline-block', width: 7, height: 7, borderRadius: 2, background: '#10B981', marginRight: 3 }}/>Reality 8.8k</span>
                  <span><span style={{ display: 'inline-block', width: 7, height: 7, borderRadius: 2, background: '#F59E0B', marginRight: 3 }}/>Target 12.1k</span>
                </div>
              </div>

              <div className="db-card">
                <div className="db-card-title">
                  <span>Devices</span>
                  <span style={{ fontSize: 9, color: 'var(--muted)' }}>30d</span>
                </div>
                <div className="db-device-row">
                  <div className="device-icon blue"><Icon name="mobile" size={12}/></div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11, fontWeight: 600 }}>
                      <span>Mobile</span>
                      <span style={{ fontFamily: 'var(--font-mono)' }}>51.8%</span>
                    </div>
                    <div style={{ height: 3, background: '#EDF0F7', borderRadius: 2, marginTop: 3 }}>
                      <div style={{ width: channelsInView ? '51.8%' : 0, height: '100%', background: 'linear-gradient(90deg,#2F7BFF,#7AB8FF)', borderRadius: 2, transition: 'width 1.2s ease' }}/>
                    </div>
                  </div>
                </div>
                <div className="db-device-row">
                  <div className="device-icon green"><Icon name="desktop" size={12}/></div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11, fontWeight: 600 }}>
                      <span>Desktop</span>
                      <span style={{ fontFamily: 'var(--font-mono)' }}>47.0%</span>
                    </div>
                    <div style={{ height: 3, background: '#EDF0F7', borderRadius: 2, marginTop: 3 }}>
                      <div style={{ width: channelsInView ? '47%' : 0, height: '100%', background: 'linear-gradient(90deg,#10B981,#86EFAC)', borderRadius: 2, transition: 'width 1.2s ease .1s' }}/>
                    </div>
                  </div>
                </div>
                <div className="db-device-row">
                  <div className="device-icon amber"><Icon name="tablet" size={12}/></div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11, fontWeight: 600 }}>
                      <span>Tablet</span>
                      <span style={{ fontFamily: 'var(--font-mono)' }}>1.3%</span>
                    </div>
                    <div style={{ height: 3, background: '#EDF0F7', borderRadius: 2, marginTop: 3 }}>
                      <div style={{ width: channelsInView ? '1.3%' : 0, height: '100%', background: 'linear-gradient(90deg,#F59E0B,#FBBF24)', borderRadius: 2, transition: 'width 1.2s ease .2s' }}/>
                    </div>
                  </div>
                </div>
                <div style={{ paddingTop: 8, marginTop: 4, borderTop: '1px solid #EDF0F7', display: 'flex', justifyContent: 'space-between', fontSize: 10 }}>
                  <span style={{ color: 'var(--muted)' }}>Avg session</span>
                  <span style={{ fontFamily: 'var(--font-mono)', fontWeight: 700, color: 'var(--ink-2)' }}>1:35</span>
                </div>
                <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 10, marginTop: 2 }}>
                  <span style={{ color: 'var(--muted)' }}>Bounce rate</span>
                  <span style={{ fontFamily: 'var(--font-mono)', fontWeight: 700, color: 'var(--amber)' }}>42.8%</span>
                </div>
              </div>
            </div>

            {/* Row 4: Social tiles */}
            <div className="db-row db-row-4eq">
              <SocialTile brand="instagram" handle="@sparlatvija" reach="8,509" eng="54.2%" color="#EC4899" bg="#FFE7F0" spark={[20, 45, 30, 60, 80, 70, 95]} delay={0}/>
              <SocialTile brand="facebook"  handle="SPAR Latvija" reach="32"    eng="3.1%"  color="#2F7BFF" bg="#E8F0FF" spark={[40, 35, 45, 30, 50, 42, 38]} delay={0.1}/>
              <SocialTile brand="tiktok"    handle="@sparlatvija" reach="2.4k"  eng="12.8%" color="#0B1033" bg="#E5E7EB" spark={[10, 25, 22, 40, 55, 48, 62]} delay={0.2}/>
              <SocialTile brand="linkedin"  handle="SPAR Latvija" reach="184"   eng="2.4%"  color="#0A66C2" bg="#E5EEF8" spark={[15, 18, 22, 20, 28, 24, 30]} delay={0.3}/>
            </div>

            {/* Row 5: Budget + Expenses pie + MarkAI */}
            <div className="db-row db-row-3b">
              <div className="db-card">
                <div className="db-card-title">
                  <span>Budget · April</span>
                  <span style={{ fontSize: 9, color: 'var(--muted)' }}>Forecast</span>
                </div>
                <div className="db-budget-grid">
                  <div className="budget-cell pink">
                    <div className="l">PLANNED</div>
                    <div className="v">€40k</div>
                  </div>
                  <div className="budget-cell cream">
                    <div className="l">ACTUAL</div>
                    <div className="v">€33.2k</div>
                  </div>
                  <div className="budget-cell mint">
                    <div className="l">REMAINING</div>
                    <div className="v">€6.8k</div>
                  </div>
                  <div className="budget-cell lilac">
                    <div className="l">DAILY</div>
                    <div className="v">€500</div>
                  </div>
                </div>
                <div className="db-card-subtitle">Expenses by month</div>
                <ExpensesBarChart/>
              </div>

              <div className="db-card">
                <div className="db-card-title">
                  <span>Expenses by channel</span>
                  <span style={{ fontSize: 9, color: 'var(--muted)' }}>30d</span>
                </div>
                <ExpensesPie/>
                <div className="db-card-subtitle" style={{ marginTop: 10 }}>Google Reviews</div>
                <div style={{ display: 'flex', alignItems: 'baseline', gap: 10 }}>
                  <div style={{ fontFamily: 'var(--font-display)', fontSize: 22, fontWeight: 800, color: 'var(--ink-2)' }}>300</div>
                  <div style={{ fontSize: 10, color: 'var(--emerald)', fontWeight: 700, background: '#E9F7EF', padding: '2px 6px', borderRadius: 4 }}>+12% 30d</div>
                </div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 4 }}>
                  <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--ink)' }}>4.8</div>
                  <div style={{ display: 'flex', gap: 1 }}>
                    {[0,0,0,0,0].map((_, i) => <Icon key={i} name="star" size={10}/>)}
                  </div>
                  <div style={{ fontSize: 9, color: 'var(--muted)', marginLeft: 'auto' }}>635 total</div>
                </div>
              </div>

              <div className="db-card db-ai-card">
                <div className="db-ai-head">
                  <div className="db-ai-avatar">🧠</div>
                  <div>
                    <div className="db-ai-title">MarkAI</div>
                    <div className="db-ai-sub">Your marketing guru</div>
                  </div>
                  <div className="db-ai-badge">4 new</div>
                </div>
                <div className="db-ai-list">
                  {aiInsights.map((x, i) => (
                    <div key={i} className={`db-ai-item tone-${x.tone}`} style={{ animationDelay: `${i * 0.15}s` }}>
                      <div className="ai-icon"><Icon name={x.icon} size={12}/></div>
                      <div style={{ minWidth: 0, flex: 1 }}>
                        <div className="ai-text">{x.text}</div>
                        <div className="ai-sub">{x.sub}</div>
                      </div>
                    </div>
                  ))}
                </div>
                <div className="db-ai-input">
                  <Icon name="sparkle" size={11}/>
                  <span>Ask MarkAI…</span>
                </div>
              </div>
            </div>

            {/* Row 6: Channel performance table */}
            <div className="db-card">
              <div className="db-card-title">
                <span>Channel Performance</span>
                <span style={{ fontSize: 10, color: 'var(--emerald)', background: '#E9F7EF', padding: '2px 8px', borderRadius: 4, fontWeight: 700 }}>5 Channels</span>
              </div>
              <div className="db-table">
                <div className="db-table-head">
                  <div>Channel</div>
                  <div className="num">Reach</div>
                  <div className="num">Eng %</div>
                  <div className="num">Spend</div>
                  <div className="num">Trend</div>
                </div>
                {channelPerf.map((c, i) => (
                  <div key={c.name} className="db-table-row" style={{ animationDelay: `${i * 0.08}s` }}>
                    <div className="ch-name">
                      <div className="ch-dot" style={{ background: c.color }}><Icon name={c.icon} size={11}/></div>
                      <span>{c.name}</span>
                    </div>
                    <div className="num mono">{c.reach}</div>
                    <div className="num mono" style={{ color: c.eng === '—' ? 'var(--muted)' : 'var(--emerald)' }}>{c.eng}</div>
                    <div className="num mono">{c.spend}</div>
                    <div className="num"><Sparkline values={[10 + i*2, 22, 18, 30, 25 + i*3, 35, 42]} color={c.color} width={52} height={18}/></div>
                  </div>
                ))}
              </div>
            </div>

           </div>
          </div>
        </div>
      </div>

      {/* Floating chips */}
      <div className="float-chip fc-a violet">
        <div className="icon"><Icon name="wand" size={18}/></div>
        <div className="body">
          <div className="title">AI generated 12 posts</div>
          <div className="sub">Ready to schedule</div>
        </div>
      </div>
      <div className="float-chip fc-b emerald">
        <div className="icon"><Icon name="trend" size={18}/></div>
        <div className="body">
          <div className="title">Engagement <b style={{ color: 'var(--emerald)' }}>+54.2%</b></div>
          <div className="sub">vs industry avg</div>
        </div>
      </div>
      <div className="float-chip fc-c amber">
        <div className="icon"><Icon name="bell" size={16}/></div>
        <div className="body">
          <div className="title">Strategy ready</div>
          <div className="sub">MarkAI · just now</div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { HeroDashboard, VisitorInsightsChart, TargetRealityChart, ExpensesBarChart, ExpensesPie, Sparkline, AreaLineChart });
