/* ============================================================
   Bizia — Analytics  (/app/analytics)  [lower priority]
   ============================================================ */
(function () {
  const { useState, useEffect } = React;
  const { Card, Badge, Button, Icon, PageHeader, MetricCard, Sparkline, AreaChart, BarChart, DonutChart, HBars, Segmented } = window;

  function AnalyticsPage() {
    const [a, setA] = useState(window.DATA.analytics);
    const [range, setRange] = useState('14d');
    // Hash-routed SPA — the ?project= query string lives inside
    // window.location.hash, not window.location.search (which is always
    // empty here). Reading .search silently fell back to a mock project.
    const projectId = new URLSearchParams(window.location.hash.split('?')[1] || '').get('project') || window.DATA.projects?.[0]?.id;

    useEffect(() => {
      if (!projectId) return;
      window.API.analytics.get(projectId, { range }).then(r => { if (r) setA(r); }).catch(() => {});
    }, [projectId, range]);

    return React.createElement('div', { className: 'bz-anim-up' },
      React.createElement(PageHeader, {
        icon: 'chart', title: 'Analytics',
        sub: 'See how people find and use your website. Built-in, privacy-friendly insights — no setup required.',
        actions: React.createElement(Segmented, { size: 'sm', value: range, onChange: setRange, options: [{ value: '7d', label: '7 days' }, { value: '14d', label: '14 days' }, { value: '30d', label: '30 days' }] }),
      }),
      // metrics
      React.createElement('div', { style: { display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(200px,1fr))', gap: 16, marginBottom: 16 } },
        React.createElement(MetricCard, { icon: 'eye', iconTone: 'primary', label: 'Visitors', value: window.fmt.k(a.visitors.total), delta: a.visitors.delta, deltaDir: 'up', spark: React.createElement(Sparkline, { data: a.visitors.series, color: 'var(--primary)', w: 999, h: 30 }) }),
        React.createElement(MetricCard, { icon: 'inbox', iconTone: 'secondary', label: 'Leads', value: a.leads.total, delta: a.leads.delta, deltaDir: 'up', spark: React.createElement(Sparkline, { data: a.leads.series, color: 'var(--secondary)', w: 999, h: 30 }) }),
        React.createElement(MetricCard, { icon: 'target', iconTone: 'accent', label: 'Conversion rate', value: a.conversion.total, delta: a.conversion.delta, deltaDir: 'up', spark: React.createElement(Sparkline, { data: a.conversion.series, color: 'var(--accent)', w: 999, h: 30 }) }),
        React.createElement(MetricCard, { icon: 'qr', iconTone: 'info', label: 'E-card scans', value: window.fmt.k(a.ecardScans.total), delta: a.ecardScans.delta, deltaDir: 'up', spark: React.createElement(Sparkline, { data: a.ecardScans.series, color: 'var(--info)', w: 999, h: 30 }) }),
      ),
      // visitors area
      React.createElement(Card, { pad: 22, style: { marginBottom: 16 } },
        React.createElement('div', { style: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16, flexWrap: 'wrap', gap: 10 } },
          React.createElement('div', null, React.createElement('h3', { style: { fontSize: 16, fontWeight: 650 } }, 'Visitors & leads'), React.createElement('p', { style: { fontSize: 13, color: 'var(--muted)', marginTop: 3 } }, 'Last 14 days')),
          React.createElement('div', { style: { display: 'flex', gap: 16 } },
            [['Visitors', 'var(--primary)'], ['Leads', 'var(--secondary)']].map((l, i) => React.createElement('div', { key: i, style: { display: 'flex', alignItems: 'center', gap: 6, fontSize: 12.5, color: 'var(--muted)' } }, React.createElement('span', { style: { width: 9, height: 9, borderRadius: 3, background: l[1] } }), l[0])))),
        React.createElement(AreaChart, { labels: a.labels, w: 880, h: 240, series: [{ name: 'Visitors', data: a.visitors.series }, { name: 'Leads', data: a.leads.series.map(x => x * 12) }], yFormat: (v) => v >= 1000 ? (v / 1000).toFixed(1) + 'k' : v }),
      ),
      // grid
      React.createElement('div', { style: { display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(300px,1fr))', gap: 16 } },
        React.createElement(Card, { pad: 22 }, React.createElement('h3', { style: { fontSize: 15.5, fontWeight: 650, marginBottom: 16 } }, 'Top pages'), React.createElement(HBars, { data: a.topPages, valueFormat: window.fmt.k })),
        React.createElement(Card, { pad: 22 },
          React.createElement('h3', { style: { fontSize: 15.5, fontWeight: 650, marginBottom: 16 } }, 'Traffic sources'),
          React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 22, flexWrap: 'wrap' } },
            React.createElement(DonutChart, { data: a.sources, size: 150, stroke: 24 }),
            React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 9, flex: 1, minWidth: 120 } },
              a.sources.map((s, i) => React.createElement('div', { key: i, style: { display: 'flex', alignItems: 'center', gap: 8, fontSize: 13 } },
                React.createElement('span', { style: { width: 9, height: 9, borderRadius: 3, background: s.color } }),
                React.createElement('span', { style: { flex: 1, color: 'var(--text-2)' } }, s.label),
                React.createElement('span', { style: { fontWeight: 650 } }, window.fmt.k(s.value)))))),
        ),
        React.createElement(Card, { pad: 22 }, React.createElement('h3', { style: { fontSize: 15.5, fontWeight: 650, marginBottom: 16 } }, 'Button clicks'), React.createElement(HBars, { data: a.buttonClicks, color: 'var(--secondary)' })),
        React.createElement(Card, { pad: 22 },
          React.createElement('h3', { style: { fontSize: 15.5, fontWeight: 650, marginBottom: 16 } }, 'Devices'),
          React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 22 } },
            React.createElement(DonutChart, { data: a.devices, size: 150, stroke: 24 }),
            React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 9, flex: 1 } },
              a.devices.map((s, i) => React.createElement('div', { key: i, style: { display: 'flex', alignItems: 'center', gap: 8, fontSize: 13 } },
                React.createElement('span', { style: { width: 9, height: 9, borderRadius: 3, background: s.color } }),
                React.createElement('span', { style: { flex: 1, color: 'var(--text-2)' } }, s.label),
                React.createElement('span', { style: { fontWeight: 650 } }, s.value + '%'))))),
        ),
      ),
      // session replay + AI recs
      React.createElement('div', { style: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginTop: 16 }, className: 'bz-an-bottom' },
        React.createElement(Card, { pad: 22 },
          React.createElement('div', { style: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14 } }, React.createElement('h3', { style: { fontSize: 15.5, fontWeight: 650 } }, 'Session replays'), React.createElement(Badge, { tone: 'neutral', size: 'sm' }, 'Beta')),
          React.createElement('div', { style: { height: 150, borderRadius: 'var(--r-md)', background: 'var(--surface-3)', backgroundImage: 'repeating-linear-gradient(135deg, var(--border-soft) 0 1px, transparent 1px 10px)', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 10, border: '1px dashed var(--border-strong)' } },
            React.createElement('div', { style: { width: 46, height: 46, borderRadius: 999, background: 'var(--surface)', boxShadow: 'var(--sh-md)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--primary)' } }, React.createElement(Icon, { name: 'play', size: 20 })),
            React.createElement('span', { style: { fontSize: 13, color: 'var(--muted)' } }, 'Watch how visitors use your site')),
          React.createElement(Button, { variant: 'outline', size: 'sm', full: true, icon: 'play', style: { marginTop: 12 }, onClick: () => window.toast({ title: 'Replays', desc: 'Mocked in prototype.', tone: 'info' }) }, 'View 24 replays'),
        ),
        React.createElement(Card, { pad: 22 },
          React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 8, marginBottom: 14 } }, React.createElement(window.BiziaMark, { size: 22 }), React.createElement('h3', { style: { fontSize: 15.5, fontWeight: 650 } }, 'Bizia recommendations')),
          React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 10 } },
            a.recommendations.map((r, i) => { const [bg, fg] = window.BZ_TONES[r.tone]; return React.createElement('div', { key: i, style: { display: 'flex', gap: 11, padding: 12, borderRadius: 'var(--r-md)', background: 'var(--surface-2)', border: '1px solid var(--border-soft)' } },
              React.createElement('div', { style: { width: 30, height: 30, borderRadius: 8, background: bg, color: fg, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 } }, React.createElement(Icon, { name: r.icon, size: 16 })),
              React.createElement('div', null, React.createElement('div', { style: { fontSize: 13, fontWeight: 650 } }, r.title), React.createElement('div', { style: { fontSize: 12.5, color: 'var(--muted)', marginTop: 2, lineHeight: 1.45 } }, r.text))); })),
        ),
      ),
      React.createElement('style', null, '@media(max-width:760px){.bz-an-bottom{grid-template-columns:1fr !important}}'),
    );
  }

  window.AnalyticsPage = AnalyticsPage;
})();
