// Lead detail drawer + sub-screens (Pipeline, Leads, Outreach, Sync, Storage, Log, Systems, Settings)

const { useState: uS2, useEffect: uE2, useMemo: uM2, useRef: uR2 } = React;

// ===== Lead Detail Drawer =====
function LeadDrawer({ lead, onClose }) {
  if (!lead) return null;
  const [tab, setTab] = uS2('overview');
  const tabs = [
    { id: 'overview', label: 'Übersicht' },
    { id: 'activity', label: 'Aktivität' },
    { id: 'audit',    label: 'Website Audit' },
    { id: 'outreach', label: 'Outreach' }
  ];
  return (
    <>
      <div className="drawer-overlay" onClick={onClose} />
      <div className="drawer">
        <div style={{ padding: '20px 24px 16px', borderBottom: '1px solid var(--border-1)' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12 }}>
            <div style={{ display: 'flex', gap: 14, alignItems: 'center', minWidth: 0 }}>
              <window.Avatar name={lead.company} size={48} />
              <div style={{ minWidth: 0 }}>
                <div style={{ fontSize: 18, fontWeight: 600, fontFamily: 'var(--font-display)', color: 'var(--text-1)', letterSpacing: '-0.01em' }}>{lead.company}</div>
                <div style={{ fontSize: 12, color: 'var(--text-3)', display: 'flex', alignItems: 'center', gap: 6, marginTop: 4 }}>
                  <window.Icons.globe size={11} />
                  {lead.web} · {lead.country} · {lead.industry}
                </div>
              </div>
            </div>
            <button className="btn-ghost btn" onClick={onClose} style={{ padding: 6 }}><window.Icons.close size={14} /></button>
          </div>
          <div style={{ display: 'flex', gap: 8, marginTop: 14, alignItems: 'center' }}>
            <window.ScoreChip score={lead.score} />
            <window.StatusPill status={lead.status} />
            <span className="pill pill-neutral"><window.Icons.users size={10} /> {lead.employees} MA</span>
            <span className="pill pill-neutral">{lead.revenue}</span>
            <span style={{ marginLeft: 'auto', fontSize: 11, color: 'var(--text-4)' }} className="mono">{lead.id}</span>
          </div>
        </div>

        <div style={{ display: 'flex', gap: 4, padding: '0 24px', borderBottom: '1px solid var(--border-1)' }}>
          {tabs.map(t => (
            <button key={t.id} onClick={() => setTab(t.id)} style={{
              padding: '10px 14px', background: 'none', border: 'none',
              color: tab === t.id ? 'var(--accent)' : 'var(--text-3)',
              fontSize: 12.5, fontWeight: 500, cursor: 'pointer',
              borderBottom: tab === t.id ? '2px solid var(--accent)' : '2px solid transparent',
              fontFamily: 'var(--font-ui)'
            }}>{t.label}</button>
          ))}
        </div>

        <div style={{ flex: 1, overflowY: 'auto', padding: 24 }}>
          {tab === 'overview' && (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
              <DrawerSection title="Hauptkontakt">
                <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: 12, background: 'var(--bg-2)', border: '1px solid var(--border-1)', borderRadius: 10 }}>
                  <window.Avatar name={lead.contact} size={40} />
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--text-1)' }}>{lead.contact}</div>
                    <div style={{ fontSize: 11.5, color: 'var(--text-3)', marginTop: 2 }}>{lead.title}</div>
                    <div style={{ fontSize: 11, color: 'var(--text-4)', marginTop: 4, fontFamily: 'var(--font-mono)' }}>{lead.email}</div>
                  </div>
                  <div style={{ display: 'flex', gap: 4 }}>
                    <button className="btn btn-ghost" style={{ padding: 7 }}><window.Icons.mail size={14} /></button>
                    <button className="btn btn-ghost" style={{ padding: 7 }}><window.Icons.linkedin size={14} /></button>
                    <button className="btn btn-ghost" style={{ padding: 7 }}><window.Icons.copy size={14} /></button>
                  </div>
                </div>
              </DrawerSection>

              <DrawerSection title="Score-Aufschlüsselung">
                <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                  {[
                    { label: 'Firmographic Match', value: 92 },
                    { label: 'Tech-Stack Fit',     value: 78 },
                    { label: 'Wachstumssignal',    value: 64 },
                    { label: 'Engagement',         value: lead.score },
                    { label: 'Ressourcen-Fit',     value: 56 }
                  ].map(s => (
                    <div key={s.label} style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: 11.5 }}>
                      <span style={{ width: 130, color: 'var(--text-3)' }}>{s.label}</span>
                      <div style={{ flex: 1, height: 6, background: 'var(--bg-3)', borderRadius: 3, overflow: 'hidden' }}>
                        <div style={{ width: `${s.value}%`, height: '100%', background: 'linear-gradient(90deg, var(--accent), #A78BFA)', borderRadius: 3 }} />
                      </div>
                      <span className="num" style={{ width: 30, textAlign: 'right', color: 'var(--text-1)' }}>{s.value}</span>
                    </div>
                  ))}
                </div>
              </DrawerSection>

              <DrawerSection title="Pipeline-Position">
                <div style={{ display: 'flex', alignItems: 'center', gap: 4, fontSize: 10.5 }}>
                  {window.VELUNA_DATA.pipeline.map((p, i) => {
                    const stages = ['import','staging','audit','scoring','queue','outreach','corteza'];
                    const statusOrder = { neu: 1, pruefung: 3, freigegeben: 4, angeschrieben: 5, genehmigt: 4, fehler: 6 };
                    const reached = i <= (statusOrder[lead.status] ?? 0);
                    return (
                      <React.Fragment key={p.id}>
                        <div style={{ flex: 1, textAlign: 'center' }}>
                          <div style={{
                            width: 32, height: 32, borderRadius: 8, margin: '0 auto',
                            background: reached ? `${p.color}1f` : 'var(--bg-3)',
                            border: `1px solid ${reached ? p.color : 'var(--border-1)'}`,
                            color: reached ? p.color : 'var(--text-4)',
                            display: 'flex', alignItems: 'center', justifyContent: 'center'
                          }}>
                            {React.createElement(window.Icons[p.icon], { size: 14 })}
                          </div>
                          <div style={{ marginTop: 4, color: reached ? 'var(--text-2)' : 'var(--text-4)', fontSize: 9.5 }}>{p.label}</div>
                        </div>
                        {i < window.VELUNA_DATA.pipeline.length - 1 && <div style={{ height: 1, flex: '0 0 8px', background: reached ? 'var(--accent)' : 'var(--border-2)', alignSelf: 'flex-start', marginTop: 16 }} />}
                      </React.Fragment>
                    );
                  })}
                </div>
              </DrawerSection>

              <DrawerSection title="Notizen">
                <div style={{ padding: 12, background: 'var(--bg-2)', border: '1px dashed var(--border-2)', borderRadius: 10, fontSize: 12, color: 'var(--text-3)' }}>
                  Keine Notizen vorhanden. <span style={{ color: 'var(--accent)', cursor: 'pointer' }}>Notiz hinzufügen +</span>
                </div>
              </DrawerSection>
            </div>
          )}
          {tab === 'activity' && (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 0 }}>
              {[
                { time: '10:24', type: 'info', text: `Lead aus ${lead.source} importiert` },
                { time: '10:23', type: 'success', text: `Website Audit abgeschlossen — Score ${lead.score}` },
                { time: '10:22', type: 'info', text: 'Kontaktdaten angereichert via Apollo.io' },
                { time: '10:20', type: 'violet', text: 'Cold-E-Mail Sequenz gestartet' },
                { time: 'Gestern', type: 'success', text: 'Domain validiert · MX-Record OK' }
              ].map((a, i) => (
                <div key={i} style={{ display: 'flex', gap: 12, paddingBottom: 14, position: 'relative' }}>
                  <div style={{ position: 'relative', flexShrink: 0 }}>
                    <div style={{ width: 10, height: 10, borderRadius: '50%', background: 'var(--accent)', marginTop: 4 }} />
                    {i < 4 && <div style={{ position: 'absolute', left: 4.5, top: 14, bottom: -14, width: 1, background: 'var(--border-2)' }} />}
                  </div>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 12, color: 'var(--text-1)' }}>{a.text}</div>
                    <div className="mono" style={{ fontSize: 10.5, color: 'var(--text-4)', marginTop: 2 }}>{a.time}</div>
                  </div>
                </div>
              ))}
            </div>
          )}
          {tab === 'audit' && (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              {[
                { label: 'Performance', value: 87, color: '#10B981' },
                { label: 'SEO',         value: 72, color: '#34D399' },
                { label: 'Accessibility', value: 64, color: '#F59E0B' },
                { label: 'Tech-Stack',  value: 91, color: '#A78BFA' },
                { label: 'Security',    value: 78, color: '#22D3EE' }
              ].map(a => (
                <div key={a.label} style={{ padding: 12, background: 'var(--bg-2)', border: '1px solid var(--border-1)', borderRadius: 10 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, marginBottom: 6 }}>
                    <span style={{ color: 'var(--text-2)' }}>{a.label}</span>
                    <span className="num" style={{ color: a.color, fontWeight: 600 }}>{a.value}/100</span>
                  </div>
                  <div style={{ height: 4, background: 'var(--bg-3)', borderRadius: 2, overflow: 'hidden' }}>
                    <div style={{ width: `${a.value}%`, height: '100%', background: a.color }} />
                  </div>
                </div>
              ))}
            </div>
          )}
          {tab === 'outreach' && (
            <div style={{ fontSize: 12.5, color: 'var(--text-3)', padding: 24, textAlign: 'center' }}>
              <window.Icons.send size={32} color="var(--text-4)" />
              <div style={{ marginTop: 12, color: 'var(--text-2)' }}>Noch keine Sequenzen gestartet</div>
              <button className="btn btn-primary" style={{ marginTop: 12 }}>Cold-E-Mail starten</button>
            </div>
          )}
        </div>

        <div style={{ padding: 16, borderTop: '1px solid var(--border-1)', display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
          <button className="btn">Verwerfen</button>
          <button className="btn">Snooze</button>
          <button className="btn btn-primary"><window.Icons.send size={13} /> Outreach starten</button>
        </div>
      </div>
    </>
  );
}

function DrawerSection({ title, children }) {
  return (
    <div>
      <div style={{ fontSize: 10.5, color: 'var(--text-4)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 600, marginBottom: 8 }}>{title}</div>
      {children}
    </div>
  );
}

// ===== Lead Pipeline screen =====
function PipelineScreen({ onLeadClick }) {
  const stages = window.VELUNA_DATA.pipeline;
  const allLeads = window.VELUNA_DATA.allLeads;
  const stageMap = { import: 'neu', staging: 'neu', audit: 'pruefung', scoring: 'pruefung', queue: 'pruefung', outreach: 'angeschrieben', corteza: 'genehmigt' };
  return (
    <div style={{ display: 'grid', gridTemplateColumns: `repeat(${stages.length}, minmax(200px, 1fr))`, gap: 12, height: '100%' }}>
      {stages.map((stage, si) => {
        const Icon = window.Icons[stage.icon];
        const stageLeads = allLeads.filter(l => l.status === stageMap[stage.id]).slice(0, 6 + si);
        return (
          <div key={stage.id} className="card" style={{ padding: 14, display: 'flex', flexDirection: 'column', minHeight: 0 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10 }}>
              <div style={{ width: 30, height: 30, borderRadius: 8, background: `${stage.color}1f`, color: stage.color, display: 'flex', alignItems: 'center', justifyContent: 'center', border: `1px solid ${stage.color}44` }}>
                <Icon size={14} />
              </div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--text-1)' }}>{stage.label}</div>
                <div className="num" style={{ fontSize: 10.5, color: 'var(--text-3)' }}>{stage.value} · {stage.pct}%</div>
              </div>
            </div>
            <div style={{ height: 3, background: 'var(--bg-3)', borderRadius: 2, marginBottom: 12 }}>
              <div style={{ width: `${stage.pct}%`, height: '100%', background: stage.color, borderRadius: 2 }} />
            </div>
            <div style={{ flex: 1, overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: 6 }}>
              {stageLeads.map(l => (
                <div key={l.id} onClick={() => onLeadClick(l)} style={{
                  padding: 10, background: 'var(--bg-2)', border: '1px solid var(--border-1)', borderRadius: 8,
                  cursor: 'pointer', transition: 'border-color 0.15s'
                }}
                onMouseEnter={(e) => e.currentTarget.style.borderColor = stage.color + '88'}
                onMouseLeave={(e) => e.currentTarget.style.borderColor = 'var(--border-1)'}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 6 }}>
                    <div style={{ fontSize: 11.5, fontWeight: 500, color: 'var(--text-1)', minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis' }}>{l.company}</div>
                    <window.ScoreChip score={l.score} />
                  </div>
                  <div style={{ fontSize: 10.5, color: 'var(--text-3)', marginTop: 4 }}>{l.contact}</div>
                  <div style={{ fontSize: 10, color: 'var(--text-4)', marginTop: 2, display: 'flex', justifyContent: 'space-between' }}>
                    <span>{l.source}</span>
                    <span className="mono">{l.updated}</span>
                  </div>
                </div>
              ))}
            </div>
          </div>
        );
      })}
    </div>
  );
}

// ===== Potenzielle Leads screen =====
function LeadsScreen({ onLeadClick }) {
  const allLeads = window.VELUNA_DATA.allLeads;
  const [filterStatus, setFilterStatus] = uS2('all');
  const [filterSource, setFilterSource] = uS2('all');
  const [search, setSearch]             = uS2('');
  const [sortBy, setSortBy]             = uS2('score');
  const [sortDir, setSortDir]           = uS2('desc');

  const filtered = uM2(() => {
    let r = allLeads;
    if (filterStatus !== 'all') r = r.filter(l => l.status === filterStatus);
    if (filterSource !== 'all') r = r.filter(l => l.source === filterSource);
    if (search) r = r.filter(l => l.company.toLowerCase().includes(search.toLowerCase()) || l.contact.toLowerCase().includes(search.toLowerCase()));
    r = [...r].sort((a, b) => {
      const av = a[sortBy], bv = b[sortBy];
      if (typeof av === 'number') return sortDir === 'asc' ? av - bv : bv - av;
      return sortDir === 'asc' ? String(av).localeCompare(bv) : String(bv).localeCompare(av);
    });
    return r;
  }, [filterStatus, filterSource, search, sortBy, sortDir]);

  const statuses = ['all', 'neu', 'pruefung', 'freigegeben', 'angeschrieben', 'genehmigt', 'fehler'];
  const sources = ['all', ...window.VELUNA_DATA.sources];

  function toggleSort(col) {
    if (sortBy === col) setSortDir(d => d === 'asc' ? 'desc' : 'asc');
    else { setSortBy(col); setSortDir('desc'); }
  }

  return (
    <div className="card" style={{ height: '100%', display: 'flex', flexDirection: 'column', padding: 0 }}>
      <div style={{ padding: 18, borderBottom: '1px solid var(--border-1)', display: 'flex', flexWrap: 'wrap', gap: 10, alignItems: 'center' }}>
        <div style={{ position: 'relative', minWidth: 240 }}>
          <span style={{ position: 'absolute', left: 10, top: '50%', transform: 'translateY(-50%)', color: 'var(--text-4)', display: 'inline-flex' }}><window.Icons.search size={14} /></span>
          <input value={search} onChange={(e) => setSearch(e.target.value)} placeholder="Unternehmen oder Kontakt suchen…" style={{
            background: 'var(--bg-2)', border: '1px solid var(--border-2)', borderRadius: 8,
            color: 'var(--text-1)', padding: '8px 12px 8px 32px', fontSize: 12.5, width: '100%',
            fontFamily: 'var(--font-ui)', outline: 'none'
          }} />
        </div>
        <Dropdown label="Status" value={filterStatus} onChange={setFilterStatus} options={statuses.map(s => ({ id: s, label: s === 'all' ? 'Alle Status' : (window.VELUNA_DATA.statusLabel[s] || s) }))} />
        <Dropdown label="Quelle" value={filterSource} onChange={setFilterSource} options={sources.map(s => ({ id: s, label: s === 'all' ? 'Alle Quellen' : s }))} />
        <span style={{ fontSize: 11.5, color: 'var(--text-3)', marginLeft: 'auto' }}>
          <span className="num">{filtered.length}</span> von <span className="num">{allLeads.length}</span> Leads
        </span>
        <button className="btn"><window.Icons.filter size={13} /> Mehr Filter</button>
        <button className="btn btn-primary"><window.Icons.plus size={13} /> Lead hinzufügen</button>
      </div>
      <div style={{ flex: 1, overflowY: 'auto' }}>
        <table className="tbl">
          <thead style={{ position: 'sticky', top: 0, background: 'var(--bg-1)', zIndex: 1 }}>
            <tr>
              <SortHeader col="company" label="Unternehmen" sortBy={sortBy} sortDir={sortDir} onSort={toggleSort} />
              <SortHeader col="contact" label="Kontakt"     sortBy={sortBy} sortDir={sortDir} onSort={toggleSort} />
              <th>Quelle</th>
              <SortHeader col="score" label="Score"         sortBy={sortBy} sortDir={sortDir} onSort={toggleSort} />
              <th>Status</th>
              <th>Industrie</th>
              <th>Mitarbeiter</th>
              <th>Umsatz</th>
              <th style={{ textAlign: 'right' }}>Akt.</th>
            </tr>
          </thead>
          <tbody>
            {filtered.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} />
                    <div>
                      <div style={{ color: 'var(--text-1)', fontWeight: 500 }}>{l.company}</div>
                      <div style={{ fontSize: 10.5, color: 'var(--text-4)' }}>{l.web}</div>
                    </div>
                  </div>
                </td>
                <td>
                  <div style={{ color: 'var(--text-1)', fontSize: 12 }}>{l.contact}</div>
                  <div style={{ fontSize: 10.5, color: 'var(--text-4)' }}>{l.title}</div>
                </td>
                <td>{l.source}</td>
                <td><window.ScoreChip score={l.score} /></td>
                <td><window.StatusPill status={l.status} /></td>
                <td>{l.industry}</td>
                <td className="num">{l.employees.toLocaleString('de-DE')}</td>
                <td>{l.revenue}</td>
                <td className="mono" style={{ textAlign: 'right', fontSize: 11, color: 'var(--text-3)' }}>{l.updated}</td>
              </tr>
            ))}
            {filtered.length === 0 && (
              <tr><td colSpan="9" style={{ padding: 48, textAlign: 'center', color: 'var(--text-3)' }}>Keine Leads für diese Filter gefunden</td></tr>
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function SortHeader({ col, label, sortBy, sortDir, onSort }) {
  const active = sortBy === col;
  return (
    <th onClick={() => onSort(col)} style={{ cursor: 'pointer', userSelect: 'none' }}>
      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, color: active ? 'var(--accent)' : 'var(--text-4)' }}>
        {label}
        {active && (sortDir === 'asc' ? <window.Icons.arrowup size={10} /> : <window.Icons.arrowdown size={10} />)}
      </span>
    </th>
  );
}

function Dropdown({ label, value, onChange, options }) {
  const [open, setOpen] = uS2(false);
  const sel = options.find(o => o.id === value) || options[0];
  return (
    <div style={{ position: 'relative' }}>
      <button className="btn" onClick={() => setOpen(o => !o)}>
        <span style={{ color: 'var(--text-4)' }}>{label}:</span> <span style={{ color: 'var(--text-1)' }}>{sel.label}</span> <window.Icons.chevdown size={12} />
      </button>
      {open && (
        <>
          <div onClick={() => setOpen(false)} style={{ position: 'fixed', inset: 0, zIndex: 10 }} />
          <div style={{ position: 'absolute', left: 0, top: 'calc(100% + 4px)', background: 'var(--bg-3)', border: '1px solid var(--border-2)', borderRadius: 10, padding: 4, zIndex: 11, minWidth: 180, boxShadow: '0 12px 32px rgba(0,0,0,0.4)', maxHeight: 280, overflowY: 'auto' }}>
            {options.map(o => (
              <button key={o.id} onClick={() => { onChange(o.id); setOpen(false); }} style={{
                display: 'block', width: '100%', padding: '7px 10px', border: 'none',
                background: o.id === value ? 'var(--accent-soft)' : 'transparent',
                color: o.id === value ? 'var(--accent)' : 'var(--text-2)',
                fontSize: 12, borderRadius: 6, cursor: 'pointer', textAlign: 'left', fontFamily: 'var(--font-ui)'
              }}>{o.label}</button>
            ))}
          </div>
        </>
      )}
    </div>
  );
}

window.LeadDrawer = LeadDrawer;
window.PipelineScreen = PipelineScreen;
window.LeadsScreen = LeadsScreen;
