// Contacts / CRM — table view + kanban pipeline view
function Contacts() {
  const [view, setView] = React.useState('pipeline');
  const [selected, setSelected] = React.useState(null);

  return (
    <div>
      <div className="page-hd">
        <div className="page-hd-l">
          <div className="page-eyebrow">CRM · {CONTACTS.length} contacts · {CONTACTS.filter(c => c.stage !== 'nurture').length} active</div>
          <h1 className="page-title">Contacts</h1>
          <div className="page-sub">People your operators are talking to. Stages, scores, and last-touch tracked automatically.</div>
        </div>
        <div className="page-hd-r">
          <div className="segmented">
            <button className={view === 'pipeline' ? 'active' : ''} onClick={() => setView('pipeline')}>PIPELINE</button>
            <button className={view === 'table' ? 'active' : ''} onClick={() => setView('table')}>TABLE</button>
          </div>
          <button className="btn"><Icon.Filter className="icon"/>Filter</button>
          <button className="btn"><Icon.Plus className="icon"/>Import</button>
          <button className="btn primary"><Icon.Plus className="icon"/>Add contact</button>
        </div>
      </div>

      {view === 'pipeline' && <Pipeline onSelect={setSelected}/>}
      {view === 'table' && <ContactTable onSelect={setSelected}/>}

      {selected && <ContactDrawer contact={selected} onClose={() => setSelected(null)}/>}
    </div>
  );
}

function Pipeline({ onSelect }) {
  return (
    <div style={{ padding: '20px 24px', height: 'calc(100vh - 52px - 160px - 26px)', overflow: 'auto' }}>
      <div style={{ display: 'grid', gridTemplateColumns: `repeat(${STAGES.length}, minmax(240px, 1fr))`, gap: 12, minHeight: '100%' }}>
        {STAGES.map(stage => {
          const items = CONTACTS.filter(c => c.stage === stage.id);
          const totalValue = items.reduce((s, i) => s + i.value, 0);
          return (
            <div key={stage.id} className="panel" style={{ display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
              <div style={{ padding: '12px 14px', borderBottom: '1px solid var(--border)', display: 'flex', flexDirection: 'column', gap: 4, background: stage.color }}>
                <div className="row" style={{ justifyContent: 'space-between' }}>
                  <span style={{ fontSize: 12, fontWeight: 500 }}>{stage.name}</span>
                  <span className="mono dim" style={{ fontSize: 10 }}>{items.length}</span>
                </div>
                <span className="mono" style={{ fontSize: 10, color: 'var(--text-faint)' }}>£{(totalValue / 1000).toFixed(0)}k pipeline</span>
              </div>
              <div style={{ padding: 10, display: 'flex', flexDirection: 'column', gap: 8, flex: 1, overflowY: 'auto' }}>
                {items.map(c => (
                  <div key={c.id} onClick={() => onSelect(c)} style={{
                    padding: 12,
                    background: 'rgba(0, 0, 0, 0.25)',
                    border: '1px solid var(--border)',
                    borderRadius: 'var(--radius)',
                    cursor: 'pointer',
                    transition: 'all 0.15s',
                    display: 'flex', flexDirection: 'column', gap: 8,
                  }}>
                    <div className="row" style={{ justifyContent: 'space-between', alignItems: 'flex-start' }}>
                      <div>
                        <div style={{ fontSize: 12, fontWeight: 500 }}>{c.name}</div>
                        <div className="dim" style={{ fontSize: 11 }}>{c.title} · {c.co}</div>
                      </div>
                      <div style={{
                        padding: '2px 6px',
                        background: c.score >= 90 ? 'rgba(75, 232, 255, 0.12)' : c.score >= 75 ? 'rgba(139, 107, 255, 0.12)' : 'rgba(255, 255, 255, 0.04)',
                        border: `1px solid ${c.score >= 90 ? 'rgba(75, 232, 255, 0.3)' : c.score >= 75 ? 'rgba(139, 107, 255, 0.3)' : 'var(--border)'}`,
                        borderRadius: 4,
                        fontFamily: 'var(--font-mono)',
                        fontSize: 10,
                        color: c.score >= 90 ? 'var(--cyan)' : c.score >= 75 ? 'var(--violet)' : 'var(--text-dim)',
                      }}>{c.score}</div>
                    </div>
                    <div className="row" style={{ justifyContent: 'space-between' }}>
                      <span className="mono" style={{ fontSize: 10, color: 'var(--text-faint)' }}>£{(c.value / 1000).toFixed(0)}k · {c.lastTouch}</span>
                      <span className="mono gradient-text" style={{ fontSize: 10, fontWeight: 600 }}>{c.src.toUpperCase()}</span>
                    </div>
                  </div>
                ))}
                {items.length === 0 && (
                  <div style={{
                    padding: 20,
                    textAlign: 'center',
                    fontSize: 11,
                    color: 'var(--text-faint)',
                    border: '1px dashed var(--border)',
                    borderRadius: 'var(--radius)',
                  }}>No contacts</div>
                )}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function ContactTable({ onSelect }) {
  return (
    <div style={{ padding: 24 }}>
      <div className="panel">
        <table className="dem">
          <thead>
            <tr>
              <th>Name</th><th>Company</th><th>Stage</th><th>Score</th><th>Value</th><th>Sourced by</th><th>Last touch</th><th></th>
            </tr>
          </thead>
          <tbody>
            {CONTACTS.map(c => (
              <tr key={c.id} onClick={() => onSelect(c)}>
                <td>
                  <div className="row">
                    <div style={{ width: 26, height: 26, borderRadius: '50%', background: 'linear-gradient(135deg, rgba(139, 107, 255, 0.3), rgba(75, 232, 255, 0.2))', border: '1px solid var(--border)', display: 'grid', placeItems: 'center', fontSize: 10, fontFamily: 'var(--font-mono)', fontWeight: 600 }}>{c.avatar}</div>
                    <div>
                      <div>{c.name}</div>
                      <div className="dim mono" style={{ fontSize: 10 }}>{c.email}</div>
                    </div>
                  </div>
                </td>
                <td>
                  <div>{c.co}</div>
                  <div className="dim" style={{ fontSize: 11 }}>{c.title}</div>
                </td>
                <td>
                  <span style={{
                    padding: '2px 8px',
                    background: STAGES.find(s => s.id === c.stage)?.color,
                    borderRadius: 4,
                    fontSize: 10,
                    fontFamily: 'var(--font-mono)',
                    textTransform: 'uppercase',
                    letterSpacing: '0.06em',
                  }}>{STAGES.find(s => s.id === c.stage)?.name}</span>
                </td>
                <td className="num">
                  <span style={{
                    color: c.score >= 90 ? 'var(--cyan)' : c.score >= 75 ? 'var(--violet)' : 'var(--text-dim)',
                  }}>{c.score}</span>
                </td>
                <td className="num">£{(c.value / 1000).toFixed(0)}k</td>
                <td><span className="mono gradient-text" style={{ fontSize: 11, fontWeight: 600 }}>{c.src.toUpperCase()}</span></td>
                <td className="dim mono" style={{ fontSize: 11 }}>{c.lastTouch}</td>
                <td><Icon.ChevronR style={{ width: 14, height: 14, color: 'var(--text-faint)' }}/></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function ContactDrawer({ contact, onClose }) {
  return (
    <React.Fragment>
      <div className="drawer-backdrop" onClick={onClose}/>
      <aside className="drawer">
        <div className="drawer-hd">
          <div style={{ width: 56, height: 56, borderRadius: 14, background: 'linear-gradient(135deg, rgba(139, 107, 255, 0.3), rgba(75, 232, 255, 0.2))', border: '1px solid rgba(139, 107, 255, 0.3)', display: 'grid', placeItems: 'center', fontSize: 18, fontFamily: 'var(--font-mono)', fontWeight: 600 }}>{contact.avatar}</div>
          <div style={{ flex: 1 }}>
            <h2 className="serif" style={{ margin: 0, fontSize: 26, fontStyle: 'italic' }}>{contact.name}</h2>
            <div className="dim" style={{ fontSize: 13 }}>{contact.title} · {contact.co}</div>
            <div className="row" style={{ gap: 8, marginTop: 6 }}>
              <span className="tag" style={{ background: STAGES.find(s => s.id === contact.stage)?.color, borderColor: 'rgba(139, 107, 255, 0.3)' }}>{STAGES.find(s => s.id === contact.stage)?.name}</span>
              <span className="tag">Score {contact.score}</span>
            </div>
          </div>
          <button className="icon-btn close" onClick={onClose}><Icon.X/></button>
        </div>
        <div className="drawer-body" style={{ display: 'flex', flexDirection: 'column', gap: 22 }}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
            <DrawerStat label="DEAL VALUE" val={`£${(contact.value/1000).toFixed(0)}k`} hi/>
            <DrawerStat label="SOURCED BY" val={contact.src}/>
            <DrawerStat label="LAST TOUCH" val={contact.lastTouch}/>
            <DrawerStat label="EMAIL" val={contact.email}/>
          </div>
          <div>
            <div className="mono faint" style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.12em', marginBottom: 10 }}>Activity timeline</div>
            <div className="panel">
              {[
                { t: '2m ago', dot: 'ok', actor: contact.src, msg: 'sent', obj: '"Re: demo confirmation"' },
                { t: '15m ago', dot: 'cool', actor: 'Vesta', msg: 'qualified · score', obj: `£${contact.score}` },
                { t: '1h ago', dot: 'ok', actor: 'Atlas', msg: 'replied to', obj: 'cold email seq #3' },
                { t: '4h ago', dot: 'cool', actor: 'Nyx', msg: 'enriched profile', obj: 'linkedin matched' },
                { t: '1d ago', dot: 'ok', actor: 'Form', msg: 'submitted', obj: '/demo-request' },
              ].map((f, i, arr) => (
                <div key={i} className="feed-item">
                  <span className="feed-time mono">{f.t}</span>
                  <span className={`feed-dot ${f.dot}`}/>
                  <span className="feed-msg"><span className="actor">{f.actor}</span> {f.msg} <span className="obj">{f.obj}</span></span>
                </div>
              ))}
            </div>
          </div>
          <div className="row" style={{ gap: 8 }}>
            <button className="btn primary">Send message</button>
            <button className="btn">Book meeting</button>
            <button className="btn">Add to sequence</button>
          </div>
        </div>
      </aside>
    </React.Fragment>
  );
}

window.Contacts = Contacts;
