// Analytics screen — KPIs, charts, per-post table.
// Hand-rolled SVG line/bar charts (no external lib).
const { useState: useStateAn, useMemo: useMemoAn } = React;

function fmt(n) {
  if (n >= 1000000) return (n / 1000000).toFixed(1) + 'M';
  if (n >= 1000) return (n / 1000).toFixed(1) + 'K';
  return String(n);
}

function LineSpark({ data = [], color = '#0F0F0F', height = 80, width = 280 }) {
  if (!data.length) return null;
  const max = Math.max(...data, 1);
  const min = Math.min(...data, 0);
  const span = Math.max(1, max - min);
  const stepX = width / (data.length - 1 || 1);
  const pts = data.map((v, i) => [i * stepX, height - ((v - min) / span) * (height - 10) - 5]);
  const d = pts.map((p, i) => (i === 0 ? `M${p[0]},${p[1]}` : `L${p[0]},${p[1]}`)).join(' ');
  const area = d + ` L${width},${height} L0,${height} Z`;
  return (
    <svg viewBox={`0 0 ${width} ${height}`} className="w-full h-auto block">
      <defs>
        <linearGradient id={'grad-' + color.replace('#', '')} x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor={color} stopOpacity="0.18"/>
          <stop offset="100%" stopColor={color} stopOpacity="0"/>
        </linearGradient>
      </defs>
      <path d={area} fill={`url(#grad-${color.replace('#', '')})`}/>
      <path d={d} fill="none" stroke={color} strokeWidth="1.8" strokeLinejoin="round" strokeLinecap="round"/>
      {pts.map((p, i) => i === pts.length - 1 && (
        <circle key={i} cx={p[0]} cy={p[1]} r="3.2" fill="white" stroke={color} strokeWidth="1.8"/>
      ))}
    </svg>
  );
}

function BarSeries({ data = [], color = '#0F0F0F', height = 80, width = 280 }) {
  if (!data.length) return null;
  const max = Math.max(...data, 1);
  const bw = width / data.length;
  const gap = Math.min(4, bw * 0.25);
  return (
    <svg viewBox={`0 0 ${width} ${height}`} className="w-full h-auto block">
      {data.map((v, i) => {
        const h = (v / max) * (height - 6);
        return <rect key={i} x={i * bw + gap / 2} y={height - h} width={bw - gap} height={h} fill={color} opacity={i === data.length - 1 ? 1 : 0.55} rx="1.5"/>;
      })}
    </svg>
  );
}

function Analytics({ org, analytics, onOpenPost }) {
  const { Button, Card, Badge, Pill, SectionHead } = window.UI;
  const I = window.Icons;

  const [metric, setMetric] = useStateAn('reach'); // reach | impressions | clicks | comments
  const [range, setRange] = useStateAn('14d');
  const [net, setNet] = useStateAn('all');

  const METRICS = [
    { id: 'reach', label: 'Охват', icon: 'Eye', tint: 'lavender' },
    { id: 'impressions', label: 'Показы', icon: 'Layers', tint: 'sky' },
    { id: 'clicks', label: 'Клики', icon: 'Link', tint: 'peach' },
    { id: 'comments', label: 'Комментарии', icon: 'Text', tint: 'mint' },
  ];
  const tintBg = {
    lavender: 'bg-lavender-soft text-lavender-ink',
    sky: 'bg-sky-soft text-sky-ink',
    peach: 'bg-peach-soft text-peach-ink',
    mint: 'bg-mint-soft text-mint-ink',
  };
  const tintCard = {
    lavender: 'bg-lavender-soft/40',
    sky: 'bg-sky-soft/40',
    peach: 'bg-peach-soft/45',
    mint: 'bg-mint-soft/40',
  };
  const colors = { reach: 'oklch(0.52 0.22 285)', impressions: 'oklch(0.45 0.16 240)', clicks: 'oklch(0.55 0.16 50)', comments: 'oklch(0.50 0.14 165)' };

  const filteredPosts = useMemoAn(() => {
    if (!analytics) return [];
    if (net === 'all') return analytics.posts;
    return analytics.posts.filter(p => p.network === net || p.network === 'both');
  }, [analytics, net]);

  if (!analytics) {
    return (
      <div className="max-w-[1280px] mx-auto px-5 sm:px-8 py-8">
        <SectionHead kicker="аналитика" title="Пока пусто" sub="Опубликуйте хотя бы один пост — сюда подтянется статистика."/>
      </div>
    );
  }

  return (
    <div className="max-w-[1280px] mx-auto px-5 sm:px-8 py-8">
      <SectionHead
        kicker="аналитика · сегодня"
        title={'Что происходит у ' + org.name}
        sub="Охват, показы, клики и комментарии по последним постам. Данные обновляются раз в час."
        right={
          <div className="flex items-center gap-1.5">
            {['7d', '14d', '30d'].map((r) => <Pill key={r} active={range === r} onClick={() => setRange(r)}>{r === '7d' ? '7 дней' : r === '14d' ? '14 дней' : '30 дней'}</Pill>)}
          </div>
        }
      />

      {/* KPI cards */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-3 mb-6">
        {METRICS.map((m) => {
          const Icon = I[m.icon];
          const value = analytics.total[m.id] || 0;
          const series = analytics.series[m.id] || [];
          const last = series[series.length - 1] || 0;
          const prev = series[series.length - 2] || last;
          const delta = prev ? Math.round((last - prev) / prev * 100) : 0;
          const active = metric === m.id;
          return (
            <button key={m.id} onClick={() => setMetric(m.id)} className={'relative text-left rounded-2xl border p-4 transition-all overflow-hidden ' + (active ? 'border-ink-900 shadow-card -translate-y-0.5 bg-white' : 'border-ink-200 shadow-soft hover:-translate-y-0.5 hover:shadow-card ' + tintCard[m.tint])}>
              <div className="flex items-center justify-between mb-2.5">
                <span className={'h-8 w-8 rounded-lg flex items-center justify-center ' + tintBg[m.tint]}><Icon size={14}/></span>
                <span className={'inline-flex items-center gap-0.5 text-[11px] font-semibold ' + (delta >= 0 ? 'text-emerald-700' : 'text-red-600')}>
                  {delta >= 0 ? <I.TrendUp size={12}/> : <I.TrendDown size={12}/>}
                  {Math.abs(delta)}%
                </span>
              </div>
              <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-ink-500">{m.label}</div>
              <div className="text-[28px] font-semibold tracking-tight tabular-nums leading-none mt-1">{fmt(value)}</div>
              <div className="text-[11px] text-ink-500 mt-0.5">сегодня {fmt(last)}</div>
              <div className="mt-3 -mx-1">
                <LineSpark data={series} color={colors[m.id]} height={36} width={240}/>
              </div>
            </button>
          );
        })}
      </div>

      {/* Big chart */}
      <Card className="p-5 mb-6">
        <div className="flex flex-wrap items-end justify-between gap-3 mb-4">
          <div>
            <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-ink-500">{METRICS.find(x => x.id === metric).label} · 14 дней</div>
            <div className="text-[28px] font-semibold tracking-tight tabular-nums leading-none mt-1">{fmt(analytics.total[metric])}</div>
          </div>
          <div className="flex items-center gap-1.5">
            {['all', 'ig', 'tg'].map((n) => (
              <Pill key={n} active={net === n} onClick={() => setNet(n)}>
                {n === 'all' ? 'Все' : n === 'ig' ? <span className="inline-flex items-center gap-1.5"><I.Instagram size={12}/> Instagram</span> : <span className="inline-flex items-center gap-1.5"><I.Telegram size={12}/> Telegram</span>}
              </Pill>
            ))}
          </div>
        </div>
        <div className="h-[220px] flex items-end">
          <LineSpark data={analytics.series[metric]} color={colors[metric]} height={220} width={1100}/>
        </div>
        <div className="mt-3 flex items-center justify-between text-[10.5px] font-mono text-ink-500">
          {Array.from({ length: 8 }).map((_, i) => (
            <span key={i}>{(14 - i * 2)} дн</span>
          ))}
        </div>
      </Card>

      {/* Per-post table */}
      <Card className="overflow-hidden">
        <div className="px-5 py-4 border-b border-ink-200 flex items-center justify-between">
          <div>
            <div className="text-[14px] font-semibold">По постам</div>
            <div className="text-[11.5px] text-ink-500">Сортировка: по охвату · сегодня</div>
          </div>
          <div className="hidden sm:flex items-center gap-1.5 text-[12px] text-ink-500">
            <I.Filter size={12}/> {net === 'all' ? 'все сети' : net.toUpperCase()}
          </div>
        </div>

        {/* desktop table */}
        <div className="hidden md:block">
          <div className="grid grid-cols-[44px_1.6fr_repeat(6,1fr)_36px] gap-3 px-5 py-2.5 text-[11px] font-semibold uppercase tracking-[0.14em] text-ink-500 border-b border-ink-200 bg-paper">
            <span/>
            <span>Пост</span>
            <span className="text-right">Охват</span>
            <span className="text-right">Показы</span>
            <span className="text-right">Клики</span>
            <span className="text-right">CTR</span>
            <span className="text-right">Комм.</span>
            <span className="text-right">Сохр.</span>
            <span/>
          </div>
          {filteredPosts.map((p, i) => (
            <button key={p.id} onClick={() => onOpenPost(p.id)} className={'w-full grid grid-cols-[44px_1.6fr_repeat(6,1fr)_36px] gap-3 px-5 py-3.5 items-center text-left hover:bg-ink-50 transition-colors ' + (i > 0 ? 'border-t border-ink-200' : '')}>
              <div style={{ width: 36, height: 45 }}>
                <window.Carousel.SlideThumb cover={{ ...p.cover, title: p.title }} brand={org.brand} w={36} h={45}/>
              </div>
              <div className="min-w-0">
                <div className="text-[13.5px] font-semibold truncate">{p.title}</div>
                <div className="flex items-center gap-1.5 mt-0.5 text-[11px] text-ink-500">
                  <NetworkChip net={p.network}/>
                </div>
              </div>
              <div className="text-right tabular-nums text-[13.5px] font-medium">{fmt(p.reach)}</div>
              <div className="text-right tabular-nums text-[13.5px]">{fmt(p.impressions)}</div>
              <div className="text-right tabular-nums text-[13.5px]">{fmt(p.clicks)}</div>
              <div className="text-right tabular-nums text-[13.5px] text-ink-500">{p.ctr}%</div>
              <div className="text-right tabular-nums text-[13.5px]">{p.comments}</div>
              <div className="text-right tabular-nums text-[13.5px]">{p.saves}</div>
              <I.ChevronRight size={14} className="text-ink-400 justify-self-end"/>
            </button>
          ))}
        </div>

        {/* mobile cards */}
        <div className="md:hidden divide-y divide-ink-200">
          {filteredPosts.map((p) => (
            <button key={p.id} onClick={() => onOpenPost(p.id)} className="w-full flex items-center gap-3 px-4 py-3 text-left hover:bg-ink-50">
              <div style={{ width: 44, height: 55 }}>
                <window.Carousel.SlideThumb cover={{ ...p.cover, title: p.title }} brand={org.brand} w={44} h={55}/>
              </div>
              <div className="flex-1 min-w-0">
                <div className="text-[13px] font-semibold truncate">{p.title}</div>
                <div className="grid grid-cols-4 gap-1 mt-1 text-[11px] text-ink-500 tabular-nums">
                  <span><I.Eye size={10} className="inline mr-0.5"/>{fmt(p.reach)}</span>
                  <span><I.Layers size={10} className="inline mr-0.5"/>{fmt(p.impressions)}</span>
                  <span><I.Text size={10} className="inline mr-0.5"/>{p.comments}</span>
                  <span><I.Bookmark size={10} className="inline mr-0.5"/>{p.saves}</span>
                </div>
              </div>
            </button>
          ))}
        </div>
      </Card>
    </div>
  );
}

function NetworkChip({ net }) {
  const I = window.Icons;
  if (net === 'both') {
    return (
      <span className="inline-flex items-center gap-1">
        <span className="inline-flex items-center justify-center h-4 w-4 rounded text-white" style={{ background: 'linear-gradient(45deg,#feda75,#fa7e1e,#d62976,#962fbf,#4f5bd5)' }}><I.Instagram size={9}/></span>
        <span className="inline-flex items-center justify-center h-4 w-4 rounded text-white bg-[#229ED9]"><I.Telegram size={9}/></span>
      </span>
    );
  }
  if (net === 'ig') return <span className="inline-flex items-center gap-1"><span className="inline-flex items-center justify-center h-4 w-4 rounded text-white" style={{ background: 'linear-gradient(45deg,#feda75,#fa7e1e,#d62976,#962fbf,#4f5bd5)' }}><I.Instagram size={9}/></span><span>Instagram</span></span>;
  return <span className="inline-flex items-center gap-1"><span className="inline-flex items-center justify-center h-4 w-4 rounded text-white bg-[#229ED9]"><I.Telegram size={9}/></span><span>Telegram</span></span>;
}

window.Screens = window.Screens || {};
window.Screens.Analytics = Analytics;
window.NetworkChip = NetworkChip;
