// desktop-screen-admin.jsx — Job Monitor / Admin screen for desktop

function AdminDesktop({ active = 'jobs', onNav = () => {}, ctx = {}, onReload = () => {}, topBarProps = {} } = {}) {
  const jobs = ctx.admin?.jobs || window.JOBS || [];
  const [kindFilter, setKindFilter] = React.useState('all');
  const audits = ctx.admin?.audits || [];
  const stats = ctx.admin?.stats || {};
  if (!ctx.user?.isAdmin && !ctx.admin) {
    return <DesktopEmpty active={active} onNav={onNav} ctx={ctx} title="Admin-Zugriff erforderlich" subtitle="Der Job-Monitor ist nur für Admin-Konten sichtbar." icon={<I.settings />} />;
  }
  const counts = {
    running: jobs.filter(j => j.status === 'running').length,
    queued: jobs.filter(j => j.status === 'queued').length,
    completed: jobs.filter(j => j.status === 'completed').length,
    failed: jobs.filter(j => j.status === 'failed' || j.status === 'skipped').length,
  };
  const visibleJobs = jobs.filter(j => kindFilter === 'all' || j.kind === kindFilter);

  return (
    <DesktopFrame url="app.immobot.de/admin/jobs">
      <Sidebar active={active} notifBadge={ctx.notifBadge || 0} onNav={onNav} user={ctx.user} taskLimit={ctx.taskLimit} />
      <main style={{ flex: 1, display: 'flex', flexDirection: 'column', minWidth: 0, background: 'var(--bg)' }}>
        <DTopBar
          crumb={['Verwaltung', 'Job-Monitor']}
          title="Job-Monitor"
          subtitle="Scraping- und KI-Analyse-Tasks · Live-Aktualisierung alle 800ms"
          actions={<>
	            <DChip tone="success" icon={<span style={{ width: 6, height: 6, borderRadius: 999, background: 'var(--success)' }} />}>Worker online</DChip>
	            <DButton kind="outline" icon={<I.refresh />} onClick={onReload}>Aktualisieren</DButton>
	            <DButton kind="primary" icon={<I.plus />} onClick={() => ctx.reset?.('searchBuilder')}>Job manuell starten</DButton>
	          </>}
	          {...topBarProps}
	        />

        <div className="desktop-scroll" style={{ flex: 1, overflowY: 'auto' }}>
          <div style={{ padding: '24px 32px 32px', display: 'flex', flexDirection: 'column', gap: 22 }}>
            {/* Stat strip */}
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14 }}>
              <DStat label="Laufend" value={counts.running} icon={<I.refresh />} delta="2,4s Ø Latenz" />
              <DStat label="In Warteschlange" value={counts.queued} icon={<I.calendar />} delta="nächster: 09:15" />
              <DStat label="Heute fertig" value={counts.completed + 14} icon={<I.check />} delta="+14 vs. gestern" trend="up" accent />
              <DStat label="Fehler / übersp." value={counts.failed} icon={<I.warn />} delta={counts.failed > 0 ? 'prüfen' : 'keine'} trend={counts.failed > 0 ? 'down' : null} />
            </div>

            {/* Two-col: Jobs table + debug console */}
            <div style={{ display: 'grid', gridTemplateColumns: '1.55fr 1fr', gap: 18, minHeight: 0 }}>
              {/* Jobs table */}
              <DCard padding={0}>
                <div style={{ padding: '14px 20px 12px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
	                  <h3 style={{ margin: 0, fontFamily: 'var(--font-display)', fontWeight: 500, fontSize: 20, letterSpacing: -0.01 }}>Aktive & geplante Jobs</h3>
	                  <div style={{ display: 'flex', gap: 6 }}>
	                    <SortChip active={kindFilter === 'all'} onClick={() => setKindFilter('all')}>Alle</SortChip>
	                    <SortChip active={kindFilter === 'scrape'} onClick={() => setKindFilter('scrape')}>Scrape</SortChip>
	                    <SortChip active={kindFilter === 'ai-eval'} onClick={() => setKindFilter('ai-eval')}>KI-Eval</SortChip>
	                  </div>
                </div>
                <div style={{
                  display: 'grid', gridTemplateColumns: '24px 1.6fr 1.4fr 1fr 1fr 1fr 24px',
                  fontSize: 10.5, fontWeight: 700, letterSpacing: 0.05, textTransform: 'uppercase',
                  color: 'var(--ink-muted)', padding: '8px 20px',
                  background: 'var(--surface-2)',
                  borderTop: '1px solid var(--border)', borderBottom: '1px solid var(--border)',
                }}>
                  <span />
                  <span>Job / Quelle</span>
                  <span>Suche</span>
                  <span>Fortschritt</span>
                  <span style={{ textAlign: 'right' }}>Items</span>
                  <span style={{ textAlign: 'right' }}>Gestartet</span>
                  <span />
                </div>
	                {visibleJobs.map((j, i) => <JobRowDesktop key={j.id} job={j} last={i === visibleJobs.length - 1} onOpen={() => {
	                  const searchId = j.taskId || j.task_id || j.searchId;
	                  if (searchId) ctx.navigate?.('results', { searchId });
	                }} />)}
	                {visibleJobs.length === 0 && (
	                  <div style={{ padding: '18px 20px', fontSize: 13, color: 'var(--ink-muted)' }}>Keine Jobs in diesem Filter.</div>
	                )}
	              </DCard>

              {/* Audit stream */}
              <DCard padding={0} style={{ display: 'flex', flexDirection: 'column' }}>
                <div style={{
                  padding: '14px 18px 12px', display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                  borderBottom: '1px solid var(--border)',
                }}>
                  <div>
                    <h3 style={{ margin: 0, fontFamily: 'var(--font-display)', fontWeight: 500, fontSize: 17, letterSpacing: -0.01 }}>Audit-Log</h3>
                    <div style={{ fontSize: 11, color: 'var(--ink-muted)', marginTop: 1 }}>letzte Systemereignisse</div>
                  </div>
                  <div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
                    <DChip tone={audits.some(a => a.need_attention) ? 'warn' : 'success'} icon={<span style={{ width: 5, height: 5, borderRadius: 999, background: 'currentColor' }} />}>
                      {audits.length} Einträge
                    </DChip>
                  </div>
                </div>

                <div style={{
                  flex: 1, background: '#15110C', padding: '14px 16px',
                  fontFamily: 'var(--font-mono)', fontSize: 11, lineHeight: 1.65, color: '#A9D2B5',
                  overflowY: 'auto', maxHeight: 420,
                }} className="desktop-scroll">
                  {audits.length === 0 ? (
                    <LogLine ts={new Date().toLocaleTimeString('de-DE', { hour: '2-digit', minute: '2-digit' })} kind="info">keine aktuellen Audit-Einträge</LogLine>
                  ) : audits.slice(0, 16).map(a => (
                    <LogLine key={a.id} ts={fmtDateTime(a.created_at)} kind={a.need_attention ? 'warn' : 'info'}>
                      {a.type}: {a.message}
                    </LogLine>
                  ))}
                </div>
              </DCard>
            </div>

            {/* Live backend totals */}
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 18 }}>
              <DCard padding={22}>
                <h3 style={{ margin: '0 0 14px', fontFamily: 'var(--font-display)', fontWeight: 500, fontSize: 17, letterSpacing: -0.01 }}>System-Zahlen</h3>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                  <AdminMetric label="Inserate gesamt" value={stats.ads_total} />
                  <AdminMetric label="Metadaten geladen" value={stats.ads_scraped} />
                  <AdminMetric label="KI-Bewertungen" value={stats.evaluations_total} />
                  <AdminMetric label="Benutzer" value={stats.users} />
                </div>
              </DCard>

              <DCard padding={22}>
                <h3 style={{ margin: '0 0 14px', fontFamily: 'var(--font-display)', fontWeight: 500, fontSize: 17, letterSpacing: -0.01 }}>Queue-Status</h3>
                <SourceHealth name="Offene Jobs" latency={stats.jobs_pending} successRate={null} status={stats.jobs_pending ? 'degraded' : 'ok'} />
                <SourceHealth name="Failed Jobs" latency={stats.jobs_failed} successRate={null} status={stats.jobs_failed ? 'degraded' : 'ok'} />
                <SourceHealth name="Aktive Suchen" latency={stats.active_tasks} successRate={null} status="ok" last />
              </DCard>
            </div>
          </div>
        </div>
      </main>
    </DesktopFrame>
  );
}

function LogLine({ ts, kind, children, cursor }) {
  const c = kind === 'error' ? '#E07C74' : kind === 'warn' ? '#F4B04D' : '#A9D2B5';
  return (
    <div style={{ marginBottom: 2 }}>
      <span style={{ color: '#5B7B66' }}>[{ts}]</span>
      <span style={{ color: c }}> {kind === 'error' ? 'error: ' : kind === 'warn' ? 'warn: ' : ''}{children}</span>
      {cursor && <span style={{ color: '#A9D2B5', animation: 'blink 1s steps(2) infinite' }}>▌</span>}
    </div>
  );
}

function AdminMetric({ label, value }) {
  return (
    <div style={{ padding: 14, borderRadius: 10, background: 'var(--surface-2)' }}>
      <div style={{ fontSize: 10.5, color: 'var(--ink-muted)', textTransform: 'uppercase', letterSpacing: 0.05, fontWeight: 800 }}>{label}</div>
      <div style={{ marginTop: 6, fontFamily: 'var(--font-display)', fontSize: 28, fontWeight: 500 }}>{Number(value || 0).toLocaleString('de-DE')}</div>
    </div>
  );
}

function JobRowDesktop({ job, last, onOpen }) {
  const statusCfg = {
    running:   { c: 'var(--info)',    bg: 'var(--info-soft)',    label: 'läuft' },
    queued:    { c: 'var(--warn)',    bg: 'var(--warn-soft)',    label: 'wartet' },
    completed: { c: 'var(--success)', bg: 'var(--success-soft)', label: 'fertig' },
    failed:    { c: 'var(--danger)',  bg: 'var(--danger-soft)',  label: 'fehler' },
    skipped:   { c: 'var(--ink-muted)', bg: 'var(--surface-2)',  label: 'überspr.' },
  };
  const s = statusCfg[job.status] || statusCfg.queued;
  const startedAt = job.started || job.createdAt || null;
  return (
    <div style={{
      display: 'grid', gridTemplateColumns: '24px 1.6fr 1.4fr 1fr 1fr 1fr 24px',
      padding: '14px 20px', alignItems: 'center', fontSize: 13, gap: 8,
      borderBottom: last ? 'none' : '1px solid var(--border)',
    }}>
      <span style={{
        width: 8, height: 8, borderRadius: 999, background: s.c,
        boxShadow: job.status === 'running' ? `0 0 0 3px ${s.c}28` : 'none',
      }} />
      <div style={{ minWidth: 0 }}>
        <div style={{ fontSize: 13, fontWeight: 700, display: 'flex', alignItems: 'center', gap: 6 }}>
          <span style={{ color: 'var(--ink-muted)', display: 'inline-flex' }}>
            {job.kind === 'ai-eval' ? <I.spark style={{ width: 14, height: 14 }} /> : <I.refresh style={{ width: 14, height: 14 }} />}
          </span>
          {job.kind === 'ai-eval' ? 'KI-Eval' : 'Scrape'} · {job.target}
        </div>
        {job.error && (
          <div style={{ fontSize: 11, color: 'var(--danger)', fontFamily: 'var(--font-mono)', marginTop: 3 }}>
            {job.error}
          </div>
        )}
      </div>
      <div style={{ fontSize: 12.5, color: 'var(--ink-2)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
        {job.search}
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
        <DChip tone={job.status === 'running' ? 'info' : job.status === 'queued' ? 'warn' : job.status === 'completed' ? 'success' : job.status === 'failed' ? 'danger' : 'neutral'}>
          {s.label}
        </DChip>
        {job.status === 'running' && (
          <div style={{ flex: 1, height: 4, background: 'var(--surface-2)', borderRadius: 999, overflow: 'hidden' }}>
            <div style={{ width: `${job.progress}%`, height: '100%', background: s.c, borderRadius: 999 }} />
          </div>
        )}
      </div>
      <div style={{ textAlign: 'right', fontVariantNumeric: 'tabular-nums', fontSize: 12, color: 'var(--ink-2)' }}>{job.items}</div>
      <div style={{ textAlign: 'right', fontSize: 11.5, color: 'var(--ink-muted)', fontVariantNumeric: 'tabular-nums' }}>
        {!startedAt || startedAt === '—' ? '—' : new Date(startedAt).toLocaleTimeString('de-DE', { hour: '2-digit', minute: '2-digit' })}
      </div>
      <button type="button" onClick={onOpen} style={{
        background: 'transparent', border: 0, cursor: 'pointer',
        color: 'var(--ink-muted)', padding: 4, display: 'flex',
      }}><I.more style={{ width: 16, height: 16 }} /></button>
    </div>
  );
}

function SourceHealth({ name, latency, successRate, status, last }) {
  const stCfg = {
    ok:       { c: 'var(--success)', label: 'OK' },
    degraded: { c: 'var(--warn)',    label: 'Beeinträchtigt' },
    off:      { c: 'var(--ink-muted)', label: 'Aus' },
  };
  const s = stCfg[status];
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 12,
      padding: '11px 0',
      borderBottom: last ? 'none' : '1px solid var(--border)',
    }}>
      <span style={{
        width: 9, height: 9, borderRadius: 999, background: s.c, flexShrink: 0,
      }} />
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 13, fontWeight: 600 }}>{name}</div>
        <div style={{ fontSize: 11, color: 'var(--ink-muted)', marginTop: 2 }}>
          {successRate == null
            ? `${Number(latency || 0).toLocaleString('de-DE')} aktuell`
            : `${latency ? `${latency} ms Ø Latenz` : 'inaktiv'} · Erfolg ${successRate}%`}
        </div>
      </div>
      <span style={{ fontSize: 11, fontWeight: 600, color: s.c }}>{s.label}</span>
    </div>
  );
}

// blink keyframe for cursor
if (!document.getElementById('admin-css')) {
  const st = document.createElement('style');
  st.id = 'admin-css';
  st.textContent = '@keyframes blink { 50% { opacity: 0 } }';
  document.head.appendChild(st);
}

Object.assign(window, { AdminDesktop });
