// Otto App · Contacts screen (CRM)

const ContactsScreen = () => {
  const [filter, setFilter] = React.useState('All');
  const filters = ['All', 'Primary', 'Otto-enriched', 'Stale · 14d+', 'No primary contact'];

  // Flatten contacts across accounts
  const allContacts = Object.entries(CONTACTS).flatMap(([accountId, list]) =>
    list.map(c => ({ ...c, accountId }))
  );

  // Crude relative-time → days for filter
  const staleDays = (lt) => {
    if (!lt) return 0;
    if (lt.includes('d ago')) return parseInt(lt, 10) || 0;
    if (lt.includes('w ago')) return (parseInt(lt, 10) || 0) * 7;
    return 0;
  };

  const filtered = (() => {
    switch (filter) {
      case 'Primary':         return allContacts.filter(c => c.primary);
      case 'Otto-enriched':   return allContacts.filter(c => c.byOtto);
      case 'Stale · 14d+':    return allContacts.filter(c => staleDays(c.lastTouch) >= 14);
      case 'No primary contact': {
        const accountsWithPrimary = new Set(
          allContacts.filter(c => c.primary).map(c => c.accountId)
        );
        return allContacts.filter(c => !accountsWithPrimary.has(c.accountId));
      }
      default: return allContacts;
    }
  })();

  // Sort by last touch ascending (most recent first using the staleDays measure)
  const sorted = [...filtered].sort((a, b) => staleDays(a.lastTouch) - staleDays(b.lastTouch));

  const ottoEnrichedCount = allContacts.filter(c => c.byOtto).length;
  const staleCount        = allContacts.filter(c => staleDays(c.lastTouch) >= 14).length;

  // Top accounts by contact count
  const accountCounts = Object.entries(CONTACTS)
    .map(([id, list]) => ({ id, name: accountById(id)?.name, count: list.length }))
    .sort((a, b) => b.count - a.count);

  return (
    <>
      <PageHeader
        eyebrow="CRM"
        title="Contacts"
        sub={`${allContacts.length} contacts across ${Object.keys(CONTACTS).length} accounts · ${ottoEnrichedCount} enriched by Otto · ${staleCount} stale`}
        tabs={filters} activeTab={filter} onTab={setFilter}
        actions={<><Btn leadingIcon="plus">New contact</Btn><Btn kind="primary" leadingIcon="sparkle">Ask Otto</Btn></>}
      />
      <div style={{ padding: 28, display: 'grid', gridTemplateColumns: '1.6fr 1fr', gap: 14, alignItems: 'start' }}>
        <Card title={`Contacts · ${sorted.length}`} sub="Sorted by last touch" padded={false}>
          {sorted.length > 0 ? (
            <ContactRows contacts={sorted} />
          ) : (
            <div style={{ padding: 32, textAlign: 'center', color: 'var(--fg-soft)', fontSize: 13 }}>
              No contacts match this filter.
            </div>
          )}
        </Card>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          <Card title="Otto summary" sub="From signature parsing & activity" accent="var(--signal)">
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10, fontSize: 13, lineHeight: 1.55 }}>
              <OttoLine>{ottoEnrichedCount} contacts enriched from email signatures · 2 new this week.</OttoLine>
              <OttoLine>Cardinal Auto Parts has gone 34 days without a touch on Priscilla Vance.</OttoLine>
              <OttoLine>Want me to draft re-engagement emails for the {staleCount} stale contacts?</OttoLine>
            </div>
          </Card>

          <Card title="By account">
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8, fontSize: 13 }}>
              {accountCounts.map(a => (
                <div key={a.id} style={{
                  display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                  padding: '6px 8px', background: 'var(--bg)', borderRadius: 'var(--r-xs)',
                }}>
                  <span>{a.name}</span>
                  <span style={{ fontFamily: 'var(--t-mono)', fontSize: 11, color: 'var(--fg-muted)' }}>
                    {a.count} {a.count === 1 ? 'contact' : 'contacts'}
                  </span>
                </div>
              ))}
            </div>
          </Card>
        </div>
      </div>
    </>
  );
};

const ContactRows = ({ contacts }) => (
  <div style={{ margin: 0 }}>
    {/* Column header */}
    <div style={{
      padding: '10px 16px', display: 'grid',
      gridTemplateColumns: '40px 1.4fr 1fr 1.4fr 90px', gap: 12, alignItems: 'center',
      borderBottom: '1px solid var(--line-soft)',
      background: 'var(--paper-2)',
    }}>
      <span></span>
      <span className="eyebrow" style={{ fontSize: 9 }}>Name · Title</span>
      <span className="eyebrow" style={{ fontSize: 9 }}>Account</span>
      <span className="eyebrow" style={{ fontSize: 9 }}>Email</span>
      <span className="eyebrow" style={{ fontSize: 9, textAlign: 'right' }}>Last touch</span>
    </div>
    {contacts.map((c, i) => {
      const acc = accountById(c.accountId);
      return (
        <div key={c.id} style={{
          padding: '12px 16px', display: 'grid',
          gridTemplateColumns: '40px 1.4fr 1fr 1.4fr 90px', gap: 12, alignItems: 'center',
          borderTop: i === 0 ? 'none' : '1px solid var(--line-soft)',
          fontSize: 13,
        }}>
          <Avatar initials={c.initials} color="#6B47E0" size={32} />
          <div style={{ minWidth: 0 }}>
            <div style={{ display: 'flex', gap: 6, alignItems: 'center', flexWrap: 'wrap' }}>
              <span style={{ fontWeight: 500 }}>{c.name}</span>
              {c.primary && <Pill color="var(--sky)" bg="var(--sky-soft)">Primary</Pill>}
              {c.byOtto && <Pill color="var(--signal)" bg="var(--signal-soft)">via Otto</Pill>}
            </div>
            <div style={{ fontSize: 11, color: 'var(--fg-muted)', marginTop: 2 }}>{c.title}</div>
          </div>
          <span style={{ color: 'var(--fg-muted)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
            {acc?.name}
          </span>
          <span style={{
            fontFamily: 'var(--t-mono)', fontSize: 11.5, color: 'var(--fg-muted)',
            whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
          }}>{c.email}</span>
          <span style={{ fontSize: 11, color: 'var(--fg-soft)', fontFamily: 'var(--t-mono)', textAlign: 'right' }}>
            {c.lastTouch}
          </span>
        </div>
      );
    })}
  </div>
);

Object.assign(window, { ContactsScreen, ContactRows });
