// desktop-screen-dashboard.jsx — Dashboard screen for desktop

function DashboardDesktop({
  active = 'kauf',
  onNav = () => {},
  onOpenResults = () => {},
  onOpenDetail = () => {},
  onNewSearch = () => {},
  onOpenAdmin = () => {},
  ctx = {},
  searchQuery = '',
  topBarProps = {},
} = {}) {
  const listings = desktopListings(ctx);
  const searches = desktopSearches(ctx).filter(s => s.category === 'kauf');
  const [activeOnly, setActiveOnly] = React.useState(false);
  const [bestSort, setBestSort] = React.useState('score');
  const user = ctx.user || {};
  const scoredListings = listings.filter(l => l.aiScore);
  const avgScore = scoredListings.length ? Math.round(scoredListings.reduce((sum, l) => sum + Number(l.aiScore || 0), 0) / scoredListings.length) : '—';
  const recentActivity = desktopNotifications(ctx).slice(0, 4);
  const today = new Date().toLocaleDateString('de-DE', { day: '2-digit', month: 'long', year: 'numeric' });
  const visibleSearches = desktopFilterByQuery(searches, searchQuery).filter(s => !activeOnly || s.active);
  const firstVisibleSearch = visibleSearches[0] || searches[0];
  const bestDeals = desktopFilterByQuery(listings, searchQuery)
    .filter(l => l.type === 'kauf' && l.aiScore)
    .sort((a, b) => {
      if (bestSort === 'price') return Number(a.price || 0) - Number(b.price || 0);
      if (bestSort === 'newest') return new Date(b.posted || 0) - new Date(a.posted || 0);
      return Number(b.aiScore || 0) - Number(a.aiScore || 0);
    })
    .slice(0, 5);

  return (
    <DesktopFrame url="app.immobot.de/dashboard">
      <Sidebar active={active} notifBadge={ctx.notifBadge || 0} onNav={onNav} user={user} taskLimit={ctx.taskLimit} onNewSearch={onNewSearch} />
      <main style={{ flex: 1, display: 'flex', flexDirection: 'column', minWidth: 0, background: 'var(--bg)' }}>
        <DTopBar
          crumb={['Arbeitsbereich', 'Kaufen']}
          title={`Guten Tag, ${desktopFirstName(user)}`}
          subtitle={`Übersicht über Ihre Kauf-Suchen · ${today}`}
          actions={<>
            {user?.isAdmin && <DButton kind="outline" icon={<I.settings />} onClick={onOpenAdmin}>Jobs</DButton>}
            <DButton kind="primary" icon={<I.plus />} onClick={onNewSearch}>Neue Suche</DButton>
          </>}
          {...topBarProps}
        />

        <div className="desktop-scroll" style={{ flex: 1, overflowY: 'auto' }}>
          <div style={{ padding: '24px 32px 40px', display: 'flex', flexDirection: 'column', gap: 28 }}>

            {/* Stats row */}
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14 }}>
              <DStat label="Aktive Suchen" value={searches.filter(s => s.active).length} icon={<I.search />} delta={`${searches.length} insgesamt`} />
              <DStat label="Treffer gesamt" value={searches.reduce((s,x) => s+x.matches, 0)} icon={<I.grid />} delta="alle Plattformen" />
              <DStat label="Neu heute" value={`+${searches.reduce((s,x) => s+x.newToday, 0)}`} icon={<I.flame />} delta="seit Mitternacht" trend="up" accent />
              <DStat label="Ø KI-Score" value={avgScore} icon={<I.spark />} delta={scoredListings.length ? `${scoredListings.length} bewertet` : 'noch keine KI-Werte'} trend={scoredListings.length ? 'up' : null} />
            </div>

            {/* Two-column main grid */}
            <div style={{ display: 'grid', gridTemplateColumns: '1.55fr 1fr', gap: 18 }}>
              {/* Active searches table */}
              <DCard padding={0}>
                <div style={{ padding: '16px 20px 14px', display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between' }}>
                  <div>
                    <h2 style={{ margin: 0, fontFamily: 'var(--font-display)', fontWeight: 500, fontSize: 20, letterSpacing: -0.01 }}>Ihre Kauf-Suchen</h2>
                    <div style={{ fontSize: 12, color: 'var(--ink-muted)', marginTop: 2 }}>
                      {searches.filter(s => s.active).length} aktiv · {searches.length - searches.filter(s => s.active).length} pausiert
                    </div>
                  </div>
	                  <DButton kind={activeOnly ? 'primary' : 'ghost'} icon={<I.filter />} size="sm" onClick={() => setActiveOnly(v => !v)}>
	                    {activeOnly ? 'Aktive' : 'Filter'}
	                  </DButton>
	                </div>
                <div style={{
                  display: 'grid', gridTemplateColumns: '1.6fr 1fr 0.8fr 0.7fr 0.7fr 32px',
                  fontSize: 10.5, fontWeight: 700, letterSpacing: 0.06, textTransform: 'uppercase',
                  color: 'var(--ink-muted)', padding: '8px 20px 8px',
                  borderTop: '1px solid var(--border)', borderBottom: '1px solid var(--border)',
                  background: 'var(--surface-2)',
                }}>
                  <span>Suche</span>
                  <span>Lage & Budget</span>
                  <span style={{ textAlign: 'right' }}>Treffer</span>
                  <span style={{ textAlign: 'right' }}>Neu heute</span>
                  <span style={{ textAlign: 'right' }}>Letzter Lauf</span>
                  <span />
                </div>
                <div>
	                  {visibleSearches.map((s, i) => (
	                    <div key={s.id} onClick={() => onOpenResults(s.id)} style={{
                      display: 'grid', gridTemplateColumns: '1.6fr 1fr 0.8fr 0.7fr 0.7fr 32px',
                      padding: '14px 20px', alignItems: 'center', gap: 8,
	                      borderBottom: i < visibleSearches.length - 1 ? '1px solid var(--border)' : 'none',
                      fontSize: 13, cursor: 'pointer',
                    }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 10, minWidth: 0 }}>
                        <span style={{
                          width: 8, height: 8, borderRadius: 999,
                          background: s.active ? 'var(--success)' : 'var(--ink-faint)',
                          boxShadow: s.active ? '0 0 0 3px rgba(47,143,90,.18)' : 'none', flexShrink: 0,
                        }} />
                        <div style={{ minWidth: 0 }}>
                          <div style={{ fontSize: 13.5, fontWeight: 700, color: 'var(--ink)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{s.name}</div>
                          <div style={{ display: 'flex', gap: 5, marginTop: 4 }}>
                            {desktopSearchPlatforms(s).map(p => <DChip key={p} tone={p === 'immoscout24' ? 'success' : 'warn'}>{p === 'immoscout24' ? 'Scout24' : 'Kleinanz.'}</DChip>)}
                            {s.aiEnabled && <DChip tone="accent" icon={<I.spark />}>KI</DChip>}
                          </div>
                        </div>
                      </div>
                      <div style={{ fontSize: 12, color: 'var(--ink-2)' }}>
                        <div>{s.city} <span style={{ color: 'var(--ink-muted)' }}>+{s.radius}km</span></div>
                        <div style={{ color: 'var(--ink-muted)', marginTop: 2, fontFamily: 'var(--font-mono)', fontSize: 11 }}>
                          {fmtPriceShort(s.priceMin)}–{fmtPriceShort(s.priceMax)}
                        </div>
                      </div>
                      <div style={{ textAlign: 'right', fontFamily: 'var(--font-display)', fontSize: 18, fontWeight: 500, fontVariantNumeric: 'tabular-nums' }}>{s.matches}</div>
                      <div style={{ textAlign: 'right' }}>
                        {s.newToday > 0
                          ? <DChip tone="accent">+{s.newToday}</DChip>
                          : <span style={{ color: 'var(--ink-faint)', fontSize: 12 }}>—</span>
                        }
                      </div>
                      <div style={{ textAlign: 'right', fontSize: 11.5, color: 'var(--ink-muted)' }}>
                        {fmtRelative(s.lastRun)}
                      </div>
                      <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
                        <button type="button" style={{
                          background: 'transparent', border: 0, cursor: 'pointer',
                          color: 'var(--ink-muted)', padding: 4, display: 'flex',
                        }}><I.chevR style={{ width: 16, height: 16 }} /></button>
                      </div>
                    </div>
	                  ))}
	                  {visibleSearches.length === 0 && (
	                    <div style={{ padding: '18px 20px', fontSize: 13, color: 'var(--ink-muted)' }}>
	                      Keine Kauf-Suchen passen zur aktuellen Suche.
	                    </div>
	                  )}
	                </div>
              </DCard>

              {/* Right column */}
              <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
                {/* Daily-quota / system */}
                <DCard padding={18}>
                  <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: 14 }}>
                    <div>
                      <h3 style={{ margin: 0, fontSize: 14, fontWeight: 700, color: 'var(--ink)' }}>System</h3>
                      <div style={{ fontSize: 11.5, color: 'var(--ink-muted)', marginTop: 2 }}>Tageskontingent · zurückgesetzt 00:00 UTC</div>
                    </div>
                    <DChip tone="success" icon={<span style={{ width: 6, height: 6, borderRadius: 999, background: 'var(--success)' }} />}>aktiv</DChip>
                  </div>
                  <Quota label="KI-Bewertungen" used={desktopUsedQuota(ctx.taskLimit)} total={ctx.taskLimit?.max_evaluations_per_day || 100} color="var(--primary)" />
                  <Quota label="Aktive Suchen" used={ctx.taskLimit?.current_tasks || searches.filter(s => s.active).length} total={ctx.taskLimit?.max_tasks || Math.max(1, searches.length)} color="var(--info)" />
                  <Quota label="Push-Benachrichtigungen" used={ctx.notifications?.filter(n => !n.read).length || 0} total={Math.max(1, ctx.notifications?.length || 1)} color="var(--success)" />
                </DCard>

                {/* Recent activity */}
                <DCard padding={0}>
                  <div style={{ padding: '14px 18px 12px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                    <h3 style={{ margin: 0, fontSize: 14, fontWeight: 700 }}>Letzte Aktivität</h3>
	                    <button type="button" onClick={() => onNav('mitt')} style={{ background: 'none', border: 0, fontSize: 11.5, color: 'var(--ink-muted)', cursor: 'pointer', fontWeight: 600 }}>alle ansehen →</button>
                  </div>
                  <div style={{ borderTop: '1px solid var(--border)' }}>
                    {recentActivity.length === 0 ? (
                      <div style={{ padding: '18px', fontSize: 12.5, color: 'var(--ink-muted)', lineHeight: 1.5 }}>
                        Noch keine Aktivitäten.
                      </div>
                    ) : recentActivity.map((a, i) => (
                      <div key={i} style={{
                        display: 'flex', alignItems: 'center', gap: 10, padding: '11px 18px',
                        borderBottom: i < recentActivity.length - 1 ? '1px solid var(--border)' : 'none',
                      }}>
                        <span style={{
                          width: 28, height: 28, borderRadius: 8,
                          background: a.kind === 'ai-high' ? 'var(--primary-soft)' : a.kind === 'new-match' ? 'var(--info-soft)' : 'var(--surface-2)',
                          color: a.kind === 'ai-high' ? 'var(--primary)' : a.kind === 'new-match' ? 'var(--info)' : 'var(--ink-muted)',
                          display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
                        }}>{a.kind === 'ai-high' ? <I.spark style={{ width: 14, height: 14 }} /> : a.kind === 'new-match' ? <I.search style={{ width: 14, height: 14 }} /> : <I.shield style={{ width: 14, height: 14 }} />}</span>
                        <div style={{ flex: 1, minWidth: 0 }}>
                          <div style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--ink)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{a.title}</div>
                          <div style={{ fontSize: 11, color: 'var(--ink-muted)', marginTop: 1 }}>{fmtRelative(a.at)}</div>
                        </div>
                      </div>
                    ))}
                  </div>
                </DCard>
              </div>
            </div>

            {/* Best deals row */}
            <div>
              <DSectionHead
                title="Beste KI-Bewertungen"
                subtitle="Ihre Top-5 Inserate, sortiert nach Score"
                right={<div style={{ display: 'flex', gap: 8 }}>
	                  <DChip tone="neutral">Kauf</DChip>
	                  <DButton kind="ghost" size="sm" icon={<I.sort />} onClick={() => setBestSort(bestSort === 'score' ? 'price' : bestSort === 'price' ? 'newest' : 'score')}>
	                    {bestSort === 'score' ? 'Score' : bestSort === 'price' ? 'Preis' : 'Neueste'}
	                  </DButton>
	                  <DButton kind="outline" size="sm" onClick={() => firstVisibleSearch && onOpenResults(firstVisibleSearch.id)}>Alle Inserate →</DButton>
	                </div>}
              />
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 14 }}>
                {bestDeals.map(l => (
                  <BestDealCard key={l.id} listing={l} onTap={onOpenDetail} />
                ))}
              </div>
            </div>
          </div>
        </div>
      </main>
    </DesktopFrame>
  );
}

function Quota({ label, used, total, color }) {
  const pct = (used / total) * 100;
  return (
    <div style={{ marginBottom: 12 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11.5, marginBottom: 5 }}>
        <span style={{ color: 'var(--ink-muted)', fontWeight: 500 }}>{label}</span>
        <span style={{ fontWeight: 700, color: 'var(--ink)', fontVariantNumeric: 'tabular-nums' }}>
          {used.toLocaleString('de-DE')}<span style={{ color: 'var(--ink-faint)', fontWeight: 500 }}> / {total.toLocaleString('de-DE')}</span>
        </span>
      </div>
      <div style={{ height: 5, background: 'var(--surface-2)', borderRadius: 999, overflow: 'hidden' }}>
        <div style={{ width: `${pct}%`, height: '100%', background: color, borderRadius: 999 }} />
      </div>
    </div>
  );
}

function BestDealCard({ listing, onTap }) {
  const photos = desktopPhotos(listing);
  return (
    <div onClick={() => onTap && onTap(listing.id)} style={{
      background: 'var(--surface)', border: '1px solid var(--border)',
      borderRadius: 12, overflow: 'hidden', cursor: 'pointer',
    }}>
      <div className="photo" style={{
        height: 130, backgroundImage: `url(${photos[0]})`,
        position: 'relative',
      }}>
        <div style={{
          position: 'absolute', top: 8, left: 8, display: 'flex', gap: 4,
        }}>
          <PlatformBadge platform={listing.platform} />
        </div>
        <div style={{ position: 'absolute', top: 8, right: 8 }}>
          <DScorePill score={listing.aiScore} size={32} />
        </div>
      </div>
      <div style={{ padding: '11px 13px 13px' }}>
        <div style={{ fontFamily: 'var(--font-display)', fontSize: 18, fontWeight: 500, letterSpacing: -0.01 }}>
          {fmtPriceShort(listing.price)}
        </div>
        <div style={{
          fontSize: 12.5, fontWeight: 600, marginTop: 2, color: 'var(--ink)',
          overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
        }}>{listing.title}</div>
        <div style={{ fontSize: 11, color: 'var(--ink-muted)', marginTop: 4, display: 'flex', alignItems: 'center', gap: 3 }}>
          <I.pin style={{ width: 11, height: 11 }} /> {listing.district}, {listing.city}
        </div>
        <div style={{ display: 'flex', gap: 9, marginTop: 8, fontSize: 11, color: 'var(--ink-2)' }}>
          <span>{fmtArea(listing.area)}</span>
          <span style={{ color: 'var(--border-strong)' }}>·</span>
          <span>{listing.rooms} Zi.</span>
          <span style={{ color: 'var(--border-strong)' }}>·</span>
          <span>{listing.baujahr}</span>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { DashboardDesktop });
