// Dashboard. Welcome + stat cards + quick actions + recent posts grid.
function Dashboard({ user, org, data, onNavigate, onApprove }) {
  const { Button, Card, Badge, SectionHead } = window.UI;
  const I = window.Icons;
  const { SlideThumb } = window.Carousel;

  const posts = data.posts || [];
  const pending = posts.filter(p => p.status === 'pending');
  const stats = [
    { kicker: 'готовы', v: posts.filter(p => p.status === 'ready').length, sub: 'к публикации сейчас', icon: 'Check', tint: 'mint' },
    { kicker: 'ждут одобрения', v: pending.length, sub: 'нужен ваш ок', icon: 'ClockApprove', tint: 'peach' },
    { kicker: 'черновики', v: posts.filter(p => p.status === 'draft').length, sub: 'в работе', icon: 'Edit', tint: 'sky' },
    { kicker: 'источники', v: (data.sources || []).filter(s => s.enabled).length, sub: 'активны', icon: 'Plug', tint: 'lavender' },
  ];

  const hour = new Date().getHours();
  const greet = hour < 6 ? 'Доброй ночи' : hour < 12 ? 'Доброе утро' : hour < 18 ? 'Добрый день' : 'Добрый вечер';

  return (
    <div className="max-w-[1280px] mx-auto px-5 sm:px-8 py-8">
      {/* Hero */}
      <div className="relative flex flex-wrap items-end justify-between gap-6 mb-10">
        {/* decorative doodles */}
        <window.Doodles.Sparkle size={18} className="absolute -top-2 left-[180px] text-violet bob" />
        <window.Doodles.Sparkle size={12} className="absolute top-8 left-[420px] text-peach-ink bob-2 opacity-70" />
        <window.Doodles.DashedSwoosh w={100} h={28} className="absolute -top-3 right-[230px] text-ink-300 hidden md:block" />
        <window.Doodles.ThreeDots className="absolute bottom-1 left-[140px] text-ink-300 hidden md:block" />

        <div className="relative">
          <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-ink-500">{greet}, {user.name || user.email.split('@')[0]}</div>
          <h1 className="mt-2 text-[34px] sm:text-[42px] font-semibold tracking-tight leading-[1.05]" style={{ textWrap: 'balance' }}>
            Сегодня в <span className="relative inline-block">
              <span style={{ fontFamily: 'Instrument Serif, serif', fontStyle: 'italic', fontWeight: 400 }}>{org.name}</span>
              <window.Doodles.Scribble w={180} h={10} className="absolute -bottom-1 left-0 right-0 w-full text-violet opacity-80"/>
            </span>
          </h1>
          <p className="mt-2 text-[15px] text-ink-500 max-w-lg"><span className="hl-mark">42 свежих статьи</span> за сутки. 7 тем уже ждут вашего согласия.</p>
        </div>
        <div className="flex items-center gap-2">
          <Button variant="outline" icon={<I.Plus size={14}/>} onClick={() => onNavigate('ideas')}>Добавить идею</Button>
          <Button icon={<I.Sparkles size={14}/>} onClick={() => onNavigate('generate')}>Сгенерировать пост</Button>
        </div>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-3 mb-10">
        {stats.map((s, i) => {
          const Icon = I[s.icon];
          const tintBg = {
            mint: 'bg-mint-soft text-mint-ink',
            peach: 'bg-peach-soft text-peach-ink',
            sky: 'bg-sky-soft text-sky-ink',
            lavender: 'bg-lavender-soft text-lavender-ink',
            lemon: 'bg-lemon-soft text-lemon-ink',
            rose: 'bg-rose-soft text-rose-ink',
          }[s.tint] || 'bg-ink-100 text-ink-700';
          const cardTintBg = {
            mint: 'bg-mint-soft/40',
            peach: 'bg-peach-soft/50',
            sky: 'bg-sky-soft/40',
            lavender: 'bg-lavender-soft/50',
            lemon: 'bg-lemon-soft/50',
          }[s.tint] || 'bg-white';
          return (
            <div key={i} className={'relative rounded-2xl border border-ink-200 p-5 shadow-soft ' + cardTintBg}>
              <div className="flex items-center justify-between mb-3">
                <span className={'h-8 w-8 rounded-lg flex items-center justify-center ' + tintBg}><Icon size={14}/></span>
                <span className="text-[10.5px] font-semibold uppercase tracking-[0.16em] text-ink-500">{s.kicker}</span>
              </div>
              <div className="text-[34px] font-semibold tracking-tight tabular-nums leading-none">{s.v}</div>
              <div className="text-[12px] text-ink-500 mt-1">{s.sub}</div>
            </div>
          );
        })}
      </div>

      {/* Quick actions row */}
      <div className="grid md:grid-cols-3 gap-3 mb-10">
        <QuickAction icon={<I.Sparkles size={18}/>} title="Сгенерировать пост" sub="Из источников, идей или своей темы" onClick={() => onNavigate('generate')} tint="violet"/>
        <QuickAction icon={<I.Lightbulb size={18}/>} title="Добавить идею" sub="Текст, ссылка или голосовое" onClick={() => onNavigate('ideas')} tint="lemon"/>
        <QuickAction icon={<I.Plug size={18}/>} title="Подключить источник" sub="RSS, Telegram, сайт, файлы" onClick={() => onNavigate('sources')} tint="mint"/>
      </div>

      {/* Pending approval — only shown when there are pending posts */}
      {pending.length > 0 && (
        <div className="relative mb-10">
          <window.SparkleField count={4} color="oklch(0.6 0.13 70)" seed={5} className="rounded-3xl"/>
          <div className="flex items-center justify-between mb-4 gap-4 relative">
            <div className="flex items-center gap-3">
              <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-peach-ink inline-flex items-center gap-1.5">
                <I.ClockApprove size={13}/> ждут одобрения
              </div>
              <h2 className="text-[20px] sm:text-[24px] font-semibold tracking-tight">
                {pending.length} {pending.length === 1 ? 'пост готов к проверке' : 'постов готовы к проверке'}
              </h2>
            </div>
            <span className="text-[12.5px] text-ink-500">Авто-одобрение выключено</span>
          </div>

          <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-3 relative">
            {pending.map((p) => (
              <div key={p.id} className="rounded-2xl border border-peach-ink/15 bg-peach-soft/45 p-3 shadow-soft">
                <div className="flex gap-3">
                  <button onClick={() => onNavigate('preview', { postId: p.id })} className="shrink-0 rounded-xl overflow-hidden ring-1 ring-ink-200 hover:ring-ink-900 transition-all">
                    <div style={{ width: 92, height: 115 }}>
                      <SlideThumb cover={{ ...p.cover, title: p.title }} brand={org.brand} w={92} h={115}/>
                    </div>
                  </button>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-1.5 mb-1">
                      {window.NetworkChip && <window.NetworkChip net={p.network || 'ig'}/>}
                    </div>
                    <div className="text-[13.5px] font-semibold leading-snug" style={{ display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>{p.title}</div>
                    <div className="text-[11.5px] text-ink-500 mt-1 flex items-center gap-1"><I.ClockApprove size={11}/> публикация {p.approveAt || 'после одобрения'}</div>
                  </div>
                </div>
                <div className="mt-3 flex items-center gap-1.5">
                  <Button size="sm" icon={<I.Approve size={13} strokeWidth={2.5}/>} onClick={() => onApprove(p.id)} className="flex-1">Одобрить</Button>
                  <Button size="sm" variant="outline" icon={<I.Edit size={13}/>} onClick={() => onNavigate('preview', { postId: p.id })} className="flex-1">Изменить</Button>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Recent posts */}
      <SectionHead
        kicker="недавние"
        title="Последние карусели"
        sub="Кликните, чтобы открыть превью"
        right={<Button variant="ghost" size="sm" iconRight={<I.ChevronRight size={14}/>} onClick={() => onNavigate('posts')}>Все посты</Button>}
      />
      <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-4">
        {posts.filter(p => p.status !== 'pending').slice(0, 8).map((p) => (
          <button key={p.id} onClick={() => onNavigate('preview', { postId: p.id })} className="text-left group">
            <div className="rounded-2xl border border-ink-200 bg-white p-3 shadow-soft hover:shadow-card transition-all group-hover:-translate-y-0.5">
              <div className="flex items-center justify-center" style={{ aspectRatio: '4/5' }}>
                <div className="w-full h-full">
                  <SlideThumb cover={{ ...p.cover, title: p.title }} brand={org.brand} w="100%" h="100%"/>
                </div>
              </div>
              <div className="mt-3 flex items-center justify-between gap-2">
                <div className="min-w-0">
                  <div className="text-[13px] font-semibold truncate">{p.title}</div>
                  <div className="text-[11.5px] text-ink-500">{p.slides} слайдов · {p.date}</div>
                </div>
                <Badge variant={p.status}>
                  {p.status === 'ready' ? 'готов' : p.status === 'draft' ? 'черн.' : 'отпр.'}
                </Badge>
              </div>
            </div>
          </button>
        ))}
      </div>

      {/* Footer note */}
      <div className="relative mt-12 rounded-3xl border border-ink-200 bg-gradient-to-br from-paper to-sky-soft/40 p-6 sm:p-7 flex flex-wrap items-center justify-between gap-4 overflow-hidden">
        <window.Doodles.Burst size={48} className="absolute -top-3 -right-3 text-sky-ink/40 orbit-slow" color="oklch(0.42 0.16 240 / 0.4)"/>
        <window.Doodles.Constellation w={100} h={36} className="absolute bottom-4 right-32 text-ink-300 hidden md:block"/>
        <div className="relative">
          <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-sky-ink">Telegram-бот</div>
          <div className="text-[18px] font-semibold mt-1 tracking-tight">Получайте «пост готов» прямо в личку</div>
          <div className="text-[13px] text-ink-500 mt-1"><span className="font-mono">@omneee_bot</span> — подключите за 30 секунд.</div>
        </div>
        <Button variant="outline" icon={<I.Telegram size={14}/>} onClick={() => onNavigate('settings', { tab: 'telegram' })}>Подключить бота</Button>
      </div>
    </div>
  );
}

function QuickAction({ icon, title, sub, onClick, tint = 'violet' }) {
  const tintMap = {
    violet: { bg: 'bg-violet-soft/55', icon: 'bg-violet text-white', ring: 'hover:border-violet/30' },
    lemon:  { bg: 'bg-lemon-soft/55',  icon: 'bg-lemon-soft text-lemon-ink', ring: 'hover:border-lemon-ink/20' },
    mint:   { bg: 'bg-mint-soft/55',   icon: 'bg-mint-soft text-mint-ink',   ring: 'hover:border-mint-ink/20' },
    peach:  { bg: 'bg-peach-soft/55',  icon: 'bg-peach-soft text-peach-ink', ring: 'hover:border-peach-ink/20' },
    sky:    { bg: 'bg-sky-soft/55',    icon: 'bg-sky-soft text-sky-ink',     ring: 'hover:border-sky-ink/20' },
  }[tint] || { bg: 'bg-white', icon: 'bg-ink-100 text-ink-700', ring: 'hover:border-ink-300' };
  return (
    <button onClick={onClick} className={'relative text-left border border-ink-200 rounded-2xl p-5 transition-all group hover:-translate-y-0.5 hover:shadow-card ' + tintMap.bg + ' ' + tintMap.ring}>
      <window.Doodles.Sparkle size={10} className="absolute top-3 right-12 text-ink-400 opacity-60"/>
      <div className="flex items-start justify-between">
        <div className={'h-10 w-10 rounded-xl flex items-center justify-center ' + tintMap.icon}>
          {icon}
        </div>
        <window.Icons.Arrow size={16} className="text-ink-400 group-hover:text-ink-900 group-hover:translate-x-0.5 transition-all"/>
      </div>
      <div className="mt-4">
        <div className="text-[15.5px] font-semibold tracking-tight">{title}</div>
        <div className="text-[12.5px] text-ink-500 mt-1">{sub}</div>
      </div>
    </button>
  );
}

window.Screens = window.Screens || {};
window.Screens.Dashboard = Dashboard;
