/* global React, Icon, Avatar, StageChip, SourceChip, TemperatureDot, ChannelBadge, ChannelIcon, fmtAED */
const { useState, useEffect, useMemo } = React;

function _initials(name) {
  if (!name) return '?';
  const parts = String(name).replace(/[._@-]/g, ' ').split(/\s+/).filter(Boolean);
  if (!parts.length) return name.slice(0, 2).toUpperCase();
  if (parts.length === 1) return parts[0].slice(0, 2).toUpperCase();
  return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase();
}
function _color(s) {
  const palette = ['#22c55e', '#3b82f6', '#a855f7', '#f97316', '#eab308', '#ec4899', '#06b6d4', '#84cc16'];
  let h = 0;
  for (let i = 0; i < (s || '').length; i++) h = ((h << 5) - h) + s.charCodeAt(i);
  return palette[Math.abs(h) % palette.length];
}
function _relTime(iso) {
  if (!iso) return '—';
  const d = new Date(iso);
  const diff = (Date.now() - d.getTime()) / 1000;
  if (diff < 60) return 'now';
  if (diff < 3600) return `${Math.round(diff / 60)}m`;
  if (diff < 86400) return `${Math.round(diff / 3600)}h`;
  if (diff < 86400 * 7) return `${Math.round(diff / 86400)}d`;
  return d.toLocaleDateString();
}

/* ============================================================
   CONTACTS LIST (data table)
   ============================================================ */

function Contacts({ goto }) {
  const [search, setSearch] = useState('');
  const [contacts, setContacts] = useState(null);
  const [error, setError] = useState(null);

  useEffect(() => {
    fetch('/api/contacts?limit=500', { credentials: 'include' })
      .then((r) => r.ok ? r.json() : Promise.reject(r.statusText))
      .then((d) => setContacts(d.items || []))
      .catch((e) => setError(String(e)));
  }, []);

  const filtered = useMemo(() => {
    if (!contacts) return [];
    const q = search.toLowerCase();
    if (!q) return contacts;
    return contacts.filter((c) =>
      (c.name || '').toLowerCase().includes(q) ||
      (c.company || '').toLowerCase().includes(q) ||
      (c.email || '').toLowerCase().includes(q) ||
      (c.linkedin_url || '').toLowerCase().includes(q)
    );
  }, [contacts, search]);

  const total = contacts ? contacts.length : 0;

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%', overflow: 'hidden' }}>
      <div className="page-header">
        <div className="page-header-left">
          <div className="page-eyebrow">CRM</div>
          <h1 className="page-title">Contacts</h1>
          <div className="page-subtitle">{total} contacts</div>
        </div>
        <div className="page-header-right">
          <button className="btn" disabled style={{ opacity: 0.5 }}><Icon name="upload" size={12} /> Import</button>
          <button className="btn btn-primary" disabled style={{ opacity: 0.5 }}><Icon name="plus" size={12} /> New contact</button>
        </div>
      </div>

      <div style={{ padding: '10px 28px', borderBottom: '1px solid var(--divider)', display: 'flex', alignItems: 'center', gap: 10 }}>
        <div style={{ flex: 1, display: 'flex', alignItems: 'center', gap: 8, padding: '6px 10px', border: '1px solid var(--divider)', background: 'var(--surface)', maxWidth: 360 }}>
          <Icon name="search" size={13} style={{ color: 'var(--text-dim)' }} />
          <input className="input" style={{ background:'transparent', border:'none', padding: 0 }} placeholder="Search by name, company, email…" value={search} onChange={e => setSearch(e.target.value)} />
        </div>
        <span style={{ marginLeft: 'auto', fontSize: 11, color: 'var(--text-dim)' }} className="mono">{filtered.length} of {total}</span>
      </div>

      <div style={{ flex: 1, overflow: 'auto' }}>
        {contacts === null && !error && (
          <div style={{ padding: 60, textAlign: 'center', color: 'var(--text-dim)', fontSize: 12 }}>Loading…</div>
        )}
        {error && (
          <div style={{ padding: 60, textAlign: 'center', color: 'var(--red)', fontSize: 12 }}>Failed to load contacts: {error}</div>
        )}
        {contacts && contacts.length === 0 && (
          <div style={{ padding: 60, textAlign: 'center', color: 'var(--text-dim)', fontSize: 12, lineHeight: 1.6 }}>
            No contacts yet. They appear automatically when someone messages you on LinkedIn / WhatsApp / Email.
          </div>
        )}
        {contacts && contacts.length > 0 && (
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12 }}>
            <thead style={{ position: 'sticky', top: 0, background: 'var(--bg)', zIndex: 1 }}>
              <tr style={{ borderBottom: '1px solid var(--divider)' }}>
                <th style={thStyle}>Name</th>
                <th style={thStyle}>Company</th>
                <th style={thStyle}>Title</th>
                <th style={thStyle}>Source</th>
                <th style={thStyle}>Temp</th>
                <th style={thStyle}>Stage</th>
                <th style={thStyle}>Created</th>
                <th style={thStyle}>Channels</th>
              </tr>
            </thead>
            <tbody>
              {filtered.map((c) => {
                const channelKinds = [
                  c.linkedin_url ? 'linkedin' : null,
                  c.whatsapp_number ? 'whatsapp' : null,
                  c.instagram_handle ? 'instagram' : null,
                  c.email ? 'email' : null,
                ].filter(Boolean);
                return (
                  <tr key={c.id} onClick={() => goto('contact', c.id)} style={{ borderBottom: '1px solid var(--divider)', cursor: 'pointer' }}
                      onMouseEnter={e => e.currentTarget.style.background = 'var(--surface)'}
                      onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                    <td style={tdStyle}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                        <Avatar name={c.name || '?'} initials={_initials(c.name)} color={_color(c.name || c.id)} size="sm" />
                        <span style={{ fontWeight: 500, color: 'var(--text)' }}>{c.name || '(unnamed)'}</span>
                      </div>
                    </td>
                    <td style={{...tdStyle, color: 'var(--text-secondary)' }}>{c.company || '—'}</td>
                    <td style={{...tdStyle, color: 'var(--text-dim)' }}>{c.title || '—'}</td>
                    <td style={tdStyle}>{c.source ? <SourceChip source={c.source} /> : '—'}</td>
                    <td style={tdStyle}>{c.temperature ? <TemperatureDot temp={c.temperature} label /> : '—'}</td>
                    <td style={{...tdStyle, color: 'var(--text)', fontSize: 11 }}>{c.pipeline_stage || 'New'}</td>
                    <td style={{...tdStyle, color: 'var(--text-dim)' }} className="mono">{_relTime(c.created_at)}</td>
                    <td style={tdStyle}>
                      <div style={{ display: 'flex', gap: 4 }}>
                        {channelKinds.length === 0 && <span style={{ color: 'var(--text-dim)', fontSize: 11 }}>—</span>}
                        {channelKinds.map((k) => <ChannelIcon key={k} kind={k} size={11} />)}
                      </div>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
}

const thStyle = { padding: '10px 16px', textAlign: 'left', fontSize: 9, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--text-dim)' };
const tdStyle = { padding: '10px 16px', verticalAlign: 'middle' };

/* ============================================================
   ACCOUNTS LIST
   ============================================================ */

function Accounts({ goto }) {
  const [accounts, setAccounts] = useState(null);
  const [error, setError] = useState(null);

  useEffect(() => {
    fetch('/api/accounts?limit=500', { credentials: 'include' })
      .then((r) => r.ok ? r.json() : Promise.reject(r.statusText))
      .then((d) => setAccounts(d.items || []))
      .catch((e) => setError(String(e)));
  }, []);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%', overflow: 'hidden' }}>
      <div className="page-header">
        <div className="page-header-left">
          <div className="page-eyebrow">CRM</div>
          <h1 className="page-title">Accounts</h1>
          <div className="page-subtitle">{accounts ? accounts.length : '—'} companies</div>
        </div>
        <div className="page-header-right">
          <button className="btn btn-primary" disabled style={{ opacity: 0.5 }}><Icon name="plus" size={12} /> New account</button>
        </div>
      </div>
      <div style={{ flex: 1, overflow: 'auto', padding: 20 }}>
        {accounts === null && !error && (
          <div style={{ padding: 60, textAlign: 'center', color: 'var(--text-dim)', fontSize: 12 }}>Loading…</div>
        )}
        {error && (
          <div style={{ padding: 60, textAlign: 'center', color: 'var(--red)', fontSize: 12 }}>Failed to load accounts: {error}</div>
        )}
        {accounts && accounts.length === 0 && (
          <div style={{ padding: 60, textAlign: 'center', color: 'var(--text-dim)', fontSize: 12, lineHeight: 1.6 }}>
            No accounts yet. Companies appear automatically as you add deals or tag contacts with a company.
          </div>
        )}
        {accounts && accounts.length > 0 && (
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: 12 }}>
            {accounts.map((co) => (
              <div key={co.id} className="card" style={{ padding: 16, cursor: 'pointer' }} onClick={() => goto('account', co.id)}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
                  <div style={{ width: 36, height: 36, background: 'var(--raised)', border: '1px solid var(--divider)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                    <Icon name="building" size={16} style={{ color: 'var(--text-secondary)' }} />
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--text)', overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{co.name}</div>
                    <div style={{ fontSize: 10, color: 'var(--text-dim)' }}>{co.industry || '—'} · {co.size || '—'}</div>
                  </div>
                </div>
                <div style={{ display: 'flex', gap: 12, fontSize: 11 }}>
                  <div><span className="mono" style={{ color: 'var(--text)' }}>{co.contact_count || 0}</span> <span style={{ color: 'var(--text-dim)' }}>contacts</span></div>
                  <div><span className="mono" style={{ color: 'var(--text)' }}>{co.deal_count || 0}</span> <span style={{ color: 'var(--text-dim)' }}>deals</span></div>
                  {co.deal_value_total > 0 && <div style={{ marginLeft: 'auto' }}><span className="mono" style={{ color: 'var(--accent)' }}>AED {fmtAED(co.deal_value_total)}</span></div>}
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { Contacts, Accounts });
