// Übersicht (Overview) screen sections

const { useState: uS1, useEffect: uE1, useRef: uR1, useMemo: uM1 } = React;

// ----- KPI Card -----
function KPICard({ kpi, sparkData, onClick, showSparkline }) {
  const Icon = window.Icons[kpi.icon] || window.Icons.dot;
  const trendUp = kpi.trendDir === 'up';
  const trendFlat = kpi.trendDir === 'flat';
  const TrendIcon = trendUp ? window.Icons.arrowup : (trendFlat ? window.Icons.dot : window.Icons.arrowdown);
  return (
    <div className="card" onClick={onClick} style={{ cursor: 'pointer', transition: 'transform 0.18s, border-color 0.18s' }}
         onMouseEnter={(e) => { e.currentTarget.style.borderColor = 'var(--border-3)'; e.currentTarget.style.transform = 'translateY(-2px)'; }}
         onMouseLeave={(e) => { e.currentTarget.style.borderColor = 'var(--border-1)'; e.currentTarget.style.transform = 'translateY(0)'; }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 8 }}>
        <div style={{
          width: 36, height: 36, borderRadius: 10,
          background: `${kpi.color}1f`, color: kpi.color,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          border: `1px solid ${kpi.color}33`
        }}>
          <Icon size={18} />
        </div>
        {showSparkline && (
          <window.Sparkline data={sparkData} color={kpi.color} width={70} height={26} />
        )}
      </div>
      <div style={{ marginTop: 12 }}>
        <div style={{ fontSize: 11.5, color: 'var(--text-3)', fontWeight: 500 }}>{kpi.label}</div>
        <div className="num" style={{ fontSize: 26, fontWeight: 600, color: 'var(--text-1)', marginTop: 4, lineHeight: 1 }}>
          {kpi.value.toLocaleString('de-DE')}
        </div>
        <div style={{ marginTop: 8, display: 'flex', alignItems: 'center', gap: 6 }}>
          <span className={`trend ${trendUp ? 'trend-up' : trendFlat ? 'trend-flat' : 'trend-down'}`}>
            <TrendIcon size={11} />
            {trendFlat ? '—' : `${trendUp ? '↗' : '↘'} ${Math.abs(kpi.delta)}%`}
          </span>
          <span style={{ fontSize: 11, color: 'var(--text-4)' }}>{kpi.deltaLabel}</span>
        </div>
      </div>
    </div>
  );
}

// ----- Pipeline overview -----
function PipelineOverview() {
  const data = window.VELUNA_DATA.pipeline;
  const [hover, setHover] = uS1(null);
  return (
    <div className="card" style={{ gridColumn: 'span 6' }}>
      <div className="card-header">
        <div className="card-title">
          <span className="card-num">1)</span> Lead Pipeline – Gesamtüberblick
        </div>
        <button className="card-link">Pipeline öffnen <window.Icons.chevright size={12} /></button>
      </div>
      <div style={{ position: 'relative', display: 'grid', gridTemplateColumns: `repeat(${data.length}, 1fr)`, gap: 4, alignItems: 'start', paddingTop: 8 }}>
        {/* Connector line */}
        <div style={{
          position: 'absolute', left: '7%', right: '7%', top: 36,
          height: 2, background: 'linear-gradient(90deg, transparent, var(--border-2) 10%, var(--border-2) 90%, transparent)',
          zIndex: 0
        }} />
        {data.map((node, i) => {
          const Icon = window.Icons[node.icon];
          const isHover = hover === i;
          return (
            <div key={node.id} className="pipe-node" onMouseEnter={() => setHover(i)} onMouseLeave={() => setHover(null)}
                 style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8, position: 'relative', zIndex: 1 }}>
              <div className="pipe-icon-wrap" style={{
                width: 56, height: 56, borderRadius: 16,
                background: `linear-gradient(135deg, ${node.color}33, ${node.color}11)`,
                border: `1px solid ${node.color}55`,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                color: node.color,
                boxShadow: isHover ? `0 8px 24px -8px ${node.color}` : 'none',
                transition: 'all 0.18s'
              }}>
                <Icon size={22} />
              </div>
              <div style={{ fontSize: 11, color: 'var(--text-3)', textAlign: 'center', minHeight: 28, lineHeight: 1.2 }}>{node.label}</div>
              <div className="num" style={{ fontSize: 20, fontWeight: 600, color: 'var(--text-1)' }}>{node.value.toLocaleString('de-DE')}</div>
              <div style={{ width: '80%', height: 4, background: 'rgba(148,163,184,0.08)', borderRadius: 2, overflow: 'hidden' }}>
                <div style={{ width: `${node.pct}%`, height: '100%', background: node.color, transition: 'width 0.6s ease' }} />
              </div>
              <div style={{ fontSize: 10, color: 'var(--text-4)' }} className="num">{node.pct}%</div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ----- Live activity feed -----
function LiveActivity({ paused }) {
  const baseFeed = window.VELUNA_DATA.liveActivities;
  const [feed, setFeed] = uS1(baseFeed.slice(0, 6));
  const idxRef = uR1(0);

  uE1(() => {
    if (paused) return;
    const iv = setInterval(() => {
      idxRef.current = (idxRef.current + 1) % baseFeed.length;
      const next = baseFeed[idxRef.current];
      const now = new Date();
      const t = `${String(now.getHours()).padStart(2,'0')}:${String(now.getMinutes()).padStart(2,'0')}:${String(now.getSeconds()).padStart(2,'0')}`;
      setFeed(prev => [{ ...next, time: t, _key: Date.now() }, ...prev.slice(0, 5)]);
    }, 3500);
    return () => clearInterval(iv);
  }, [paused]);

  const colorMap = { info: 'var(--accent)', success: 'var(--success)', warning: 'var(--warning)', danger: 'var(--danger)', violet: 'var(--violet)' };

  return (
    <div className="card" style={{ gridColumn: 'span 4', display: 'flex', flexDirection: 'column' }}>
      <div className="card-header">
        <div className="card-title">
          <span className="card-num">2)</span> Live Aktivität
          {!paused && <span className="pill-dot pulse" style={{ background: 'var(--success)', width: 6, height: 6, marginLeft: 4 }} />}
        </div>
        <span style={{ fontSize: 11, color: 'var(--text-4)' }}>{paused ? 'Pausiert' : 'Live'}</span>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 2, flex: 1, overflow: 'hidden' }}>
        {feed.map((a, i) => {
          const Icon = window.Icons[a.icon] || window.Icons.dot;
          const color = colorMap[a.type];
          return (
            <div key={a._key || i} className={i === 0 && !paused ? 'slide-in' : ''}
                 style={{ display: 'flex', gap: 10, padding: '8px 4px', borderBottom: i < feed.length - 1 ? '1px solid var(--border-1)' : 'none' }}>
              <div style={{
                width: 28, height: 28, borderRadius: 8, flexShrink: 0,
                background: `${color}1f`, color, border: `1px solid ${color}33`,
                display: 'flex', alignItems: 'center', justifyContent: 'center'
              }}>
                <Icon size={13} />
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', gap: 8 }}>
                  <span style={{ fontSize: 12, fontWeight: 500, color: 'var(--text-1)' }}>{a.title}</span>
                  <span className="mono" style={{ fontSize: 10.5, color: 'var(--text-4)', flexShrink: 0 }}>{a.time}</span>
                </div>
                <div style={{ fontSize: 11, color: 'var(--text-3)', marginTop: 2 }}>{a.detail}</div>
                {a.src && <div style={{ fontSize: 10.5, color: 'var(--text-4)', marginTop: 1 }}>{a.src}</div>}
              </div>
            </div>
          );
        })}
      </div>
      <button className="card-link" style={{ marginTop: 12 }}>Alle Aktivitäten anzeigen <window.Icons.chevright size={12} /></button>
    </div>
  );
}

// ----- Leads table preview (Übersicht) -----
function LeadsPreview({ onLeadClick }) {
  const leads = window.VELUNA_DATA.allLeads.slice(0, 7);
  return (
    <div className="card" style={{ gridColumn: 'span 6' }}>
      <div className="card-header">
        <div className="card-title">
          <span className="card-num">3)</span> Potenzielle Leads
        </div>
        <button className="card-link">Alle Leads anzeigen <window.Icons.chevright size={12} /></button>
      </div>
      <table className="tbl">
        <thead>
          <tr>
            <th>Unternehmen</th><th>Website</th><th>Quelle</th><th>Score</th><th>Status</th><th style={{ textAlign: 'right' }}>Zuletzt akt.</th>
          </tr>
        </thead>
        <tbody>
          {leads.map(l => (
            <tr key={l.id} onClick={() => onLeadClick(l)}>
              <td>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                  <window.Avatar name={l.company} size={26} />
                  <span style={{ color: 'var(--text-1)', fontWeight: 500 }}>{l.company}</span>
                </div>
              </td>
              <td><span style={{ color: 'var(--text-3)' }}>{l.web}</span></td>
              <td><span style={{ color: 'var(--text-2)' }}>{l.source}</span></td>
              <td><window.ScoreChip score={l.score} /></td>
              <td><window.StatusPill status={l.status} /></td>
              <td className="mono" style={{ textAlign: 'right', fontSize: 11.5, color: 'var(--text-3)' }}>{l.updated}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

// ----- Outreach card -----
function OutreachCard() {
  const o = window.VELUNA_DATA.outreach;
  const stats = [
    { label: 'Gesendet',    value: o.sent,    color: '#22D3EE' },
    { label: 'Antworten',   value: o.replied, color: '#A78BFA' },
    { label: 'Meetings',    value: o.meetings,color: '#F472B6' },
    { label: 'Won',         value: o.won,     color: '#10B981' }
  ];
  const ChannelIcon = (ch) => ch === 'LinkedIn' ? window.Icons.linkedin : ch === 'E-Mail' ? window.Icons.mail : window.Icons.phone;
  const statusMap = {
    antwort_erh: { cls: 'pill-success', label: 'Antwort erhalten' },
    offen:       { cls: 'pill-warning', label: 'Offen' },
    gesendet:    { cls: 'pill-info',    label: 'Gesendet' },
    meeting:     { cls: 'pill-violet',  label: 'Meeting' },
    kein_kontakt:{ cls: 'pill-danger',  label: 'Kein Kontakt' }
  };
  return (
    <div className="card" style={{ gridColumn: 'span 4' }}>
      <div className="card-header">
        <div className="card-title">
          <span className="card-num">4)</span> Outreach &amp; Kommunikation
        </div>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 8, marginBottom: 14 }}>
        {stats.map(s => (
          <div key={s.label} style={{ background: 'var(--bg-3)', border: '1px solid var(--border-1)', borderRadius: 10, padding: '10px 8px', textAlign: 'center' }}>
            <div className="num" style={{ fontSize: 20, fontWeight: 600, color: s.color }}>{s.value}</div>
            <div style={{ fontSize: 10.5, color: 'var(--text-3)', marginTop: 2 }}>{s.label}</div>
          </div>
        ))}
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {o.funnel.map(f => <window.FunnelRow key={f.label} {...f} />)}
      </div>
      <div style={{ marginTop: 14, paddingTop: 10, borderTop: '1px solid var(--border-1)' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 0.8fr 1.1fr 1fr', gap: 8, fontSize: 10.5, color: 'var(--text-4)', textTransform: 'uppercase', letterSpacing: '0.04em', marginBottom: 4, padding: '0 4px' }}>
          <span>Kontakt</span><span>Kanal</span><span>Status</span><span>Nächster Schritt</span>
        </div>
        {o.contacts.slice(0, 5).map((c, i) => {
          const Ico = ChannelIcon(c.channel);
          const s = statusMap[c.status];
          return (
            <div key={i} style={{ display: 'grid', gridTemplateColumns: '1.4fr 0.8fr 1.1fr 1fr', gap: 8, alignItems: 'center', padding: '6px 4px', fontSize: 11.5, borderBottom: i < 4 ? '1px solid var(--border-1)' : 'none' }}>
              <span style={{ color: 'var(--text-1)' }}>{c.name}</span>
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, color: 'var(--text-3)' }}><Ico size={12} /> {c.channel}</span>
              <span><span className={`pill ${s.cls}`} style={{ fontSize: 10 }}><span className="pill-dot" />{s.label}</span></span>
              <span style={{ color: 'var(--text-2)', fontSize: 11 }}>{c.next}</span>
            </div>
          );
        })}
      </div>
      <button className="card-link" style={{ marginTop: 10 }}>Alle Outreach-Aktivitäten anzeigen <window.Icons.chevright size={12} /></button>
    </div>
  );
}

// ----- Systems card -----
function SystemsCard() {
  const sys = window.VELUNA_DATA.systems.slice(0, 5);
  return (
    <div className="card" style={{ gridColumn: 'span 4' }}>
      <div className="card-header">
        <div className="card-title">
          <span className="card-num">5)</span> Speicherung &amp; Systeme
        </div>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {sys.map(s => {
          const Icon = window.Icons[s.icon] || window.Icons.db;
          const cls = s.status === 'healthy' ? 'pill-success' : s.status === 'warning' ? 'pill-warning' : 'pill-danger';
          const lbl = s.status === 'healthy' ? 'Healthy' : s.status === 'warning' ? 'Wartet' : 'Fehler';
          return (
            <div key={s.name} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 12px', background: 'var(--bg-3)', border: '1px solid var(--border-1)', borderRadius: 10 }}>
              <div style={{ width: 32, height: 32, borderRadius: 8, background: `${s.color}1f`, color: s.color, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <Icon size={15} />
              </div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 12.5, fontWeight: 500, color: 'var(--text-1)' }}>{s.name}</div>
                <div style={{ fontSize: 10.5, color: 'var(--text-3)', marginTop: 1 }}>{s.detail}</div>
              </div>
              <span className={`pill ${cls}`} style={{ fontSize: 10.5 }}><span className="pill-dot pulse" />{lbl}</span>
            </div>
          );
        })}
      </div>
      {/* Mini topology */}
      <div style={{ marginTop: 14, padding: '12px', background: 'var(--bg-3)', border: '1px solid var(--border-1)', borderRadius: 10 }}>
        <div style={{ fontSize: 10.5, color: 'var(--text-4)', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 8 }}>Datenfluss</div>
        <svg width="100%" height="72" viewBox="0 0 280 72">
          <defs>
            <marker id="arr" markerWidth="6" markerHeight="6" refX="5" refY="3" orient="auto">
              <path d="M0,0 L6,3 L0,6" fill="var(--text-3)" />
            </marker>
          </defs>
          {[
            { x: 24, y: 36, label: 'Postgres', color: '#34D399' },
            { x: 96, y: 12, label: 'Activep.', color: '#A78BFA' },
            { x: 96, y: 60, label: 'Redis', color: '#F472B6' },
            { x: 184, y: 36, label: 'Corteza', color: '#22D3EE' },
            { x: 256, y: 36, label: 'listmonk', color: '#F59E0B' }
          ].map((n, i) => (
            <g key={i}>
              <circle cx={n.x} cy={n.y} r="14" fill={`${n.color}1f`} stroke={`${n.color}88`} strokeWidth="1" />
              <circle cx={n.x} cy={n.y} r="4" fill={n.color} />
              <text x={n.x} y={n.y + 26} textAnchor="middle" fontSize="9" fill="var(--text-3)">{n.label}</text>
            </g>
          ))}
          <path d="M38 32 L82 18" stroke="var(--text-3)" strokeWidth="1" strokeDasharray="2,2" markerEnd="url(#arr)" />
          <path d="M38 40 L82 56" stroke="var(--text-3)" strokeWidth="1" strokeDasharray="2,2" markerEnd="url(#arr)" />
          <path d="M110 18 L170 32" stroke="var(--text-3)" strokeWidth="1" strokeDasharray="2,2" markerEnd="url(#arr)" />
          <path d="M110 56 L170 40" stroke="var(--text-3)" strokeWidth="1" strokeDasharray="2,2" markerEnd="url(#arr)" />
          <path d="M198 36 L242 36" stroke="var(--text-3)" strokeWidth="1" strokeDasharray="2,2" markerEnd="url(#arr)" />
        </svg>
      </div>
    </div>
  );
}

// ----- Sync status card -----
function SyncCard({ onDrilldown }) {
  const s = window.VELUNA_DATA.syncStatus;
  return (
    <div className="card" style={{ gridColumn: 'span 4' }}>
      <div className="card-header">
        <div className="card-title">
          <span className="card-num">6)</span> Sync-Status
        </div>
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 18 }}>
        <window.RingChart value={s.success} total={s.total} size={130} thickness={11} color="var(--success)">
          <div className="num" style={{ fontSize: 28, fontWeight: 600 }}>{s.total}</div>
          <div style={{ fontSize: 10.5, color: 'var(--text-3)' }}>Gesamt</div>
        </window.RingChart>
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 8 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12 }}>
            <span style={{ width: 10, height: 10, borderRadius: '50%', background: 'var(--success)' }} />
            <span style={{ color: 'var(--text-2)' }}>Erfolgreich</span>
            <span className="num" style={{ marginLeft: 'auto', color: 'var(--text-1)', fontWeight: 600 }}>{s.success}</span>
            <span className="num" style={{ color: 'var(--text-3)', fontSize: 11 }}>({s.successPct}%)</span>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12 }}>
            <span style={{ width: 10, height: 10, borderRadius: '50%', background: 'var(--danger)' }} />
            <span style={{ color: 'var(--text-2)' }}>Fehler</span>
            <span className="num" style={{ marginLeft: 'auto', color: 'var(--text-1)', fontWeight: 600 }}>{s.failed}</span>
            <span className="num" style={{ color: 'var(--text-3)', fontSize: 11 }}>({s.failedPct}%)</span>
          </div>
        </div>
      </div>
      <div style={{ marginTop: 14 }}>
        <div style={{ fontSize: 10.5, color: 'var(--text-4)', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 6 }}>Fehlergründe</div>
        {s.reasons.map(r => (
          <div key={r.label} style={{ display: 'grid', gridTemplateColumns: '1fr auto auto', gap: 10, padding: '5px 0', fontSize: 11.5, borderBottom: '1px solid var(--border-1)' }}>
            <span style={{ color: 'var(--text-2)' }}>{r.label}</span>
            <span className="num" style={{ color: 'var(--text-1)', fontWeight: 500 }}>{r.count}</span>
            <span className="num" style={{ color: 'var(--text-3)', minWidth: 42, textAlign: 'right' }}>({r.pct}%)</span>
          </div>
        ))}
      </div>
      <button className="card-link" style={{ marginTop: 10 }} onClick={onDrilldown}>Sync-Details anzeigen <window.Icons.chevright size={12} /></button>
    </div>
  );
}

// ----- Warnings card -----
function WarningsCard({ warnings, onDismiss }) {
  return (
    <div className="card" style={{ gridColumn: 'span 4' }}>
      <div className="card-header">
        <div className="card-title">
          <span className="card-num">7)</span> Warnungen / Blocker
          <span className="pill pill-danger" style={{ fontSize: 10 }}>{warnings.length}</span>
        </div>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {warnings.length === 0 && (
          <div style={{ padding: 24, textAlign: 'center', color: 'var(--text-3)', fontSize: 12.5 }}>
            <window.Icons.check size={28} color="var(--success)" />
            <div style={{ marginTop: 8 }}>Keine aktiven Warnungen</div>
          </div>
        )}
        {warnings.map(w => {
          const color = w.level === 'danger' ? 'var(--danger)' : 'var(--warning)';
          return (
            <div key={w.id} style={{
              display: 'flex', gap: 10, padding: 12,
              background: w.level === 'danger' ? 'var(--danger-soft)' : 'var(--warning-soft)',
              border: `1px solid ${color}33`,
              borderRadius: 10, position: 'relative'
            }}>
              <div style={{ color, flexShrink: 0 }}><window.Icons.alert size={16} /></div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', gap: 8 }}>
                  <span style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--text-1)' }}>{w.title}</span>
                  <span className="mono" style={{ fontSize: 10.5, color: 'var(--text-4)', flexShrink: 0 }}>{w.time}</span>
                </div>
                <div style={{ fontSize: 11.5, color: 'var(--text-2)', marginTop: 4, lineHeight: 1.5 }}>{w.body}</div>
              </div>
              <button onClick={() => onDismiss(w.id)} className="btn-ghost btn" style={{ padding: 4, alignSelf: 'flex-start' }} title="Verwerfen">
                <window.Icons.close size={12} />
              </button>
            </div>
          );
        })}
      </div>
      <button className="card-link" style={{ marginTop: 10 }}>Alle Warnungen anzeigen <window.Icons.chevright size={12} /></button>
    </div>
  );
}

window.KPICard = KPICard;
window.PipelineOverview = PipelineOverview;
window.LiveActivity = LiveActivity;
window.LeadsPreview = LeadsPreview;
window.OutreachCard = OutreachCard;
window.SystemsCard = SystemsCard;
window.SyncCard = SyncCard;
window.WarningsCard = WarningsCard;
