// Merge profile helper — finds potential duplicate contacts
function findPotentialMatches(target, contacts) {
  // target: { name, phone, email } either contact or deal-style
  const matches = [];
  const norm = (s) => (s || '').toString().toLowerCase().replace(/[^a-z0-9 ]/g, '').trim();
  const normPhone = (p) => (p || '').toString().replace(/\D/g, '').replace(/^61/, '0');

  const tName = norm(target.name || target.customer);
  const tPhone = normPhone(target.phone);
  const tEmail = (target.email || '').toLowerCase().trim();

  for (const c of contacts) {
    if (c.id === target.id) continue;
    const cName = norm(c.name);
    const cPhone = normPhone(c.phone);
    const cEmail = (c.email || '').toLowerCase().trim();
    let score = 0;
    let reason = [];
    if (tPhone && cPhone && tPhone.length >= 8 && tPhone === cPhone) { score += 100; reason.push('phone match'); }
    if (tEmail && cEmail && tEmail === cEmail) { score += 60; reason.push('email match'); }
    if (tName && cName && tName === cName) { score += 40; reason.push('exact name'); }
    else if (tName && cName) {
      // surname match
      const tLast = tName.split(' ').slice(-1)[0];
      const cLast = cName.split(' ').slice(-1)[0];
      if (tLast.length > 2 && tLast === cLast) { score += 15; reason.push('same surname'); }
    }
    if (score >= 40) matches.push({ contact: c, score, reason });
  }
  return matches.sort((a, b) => b.score - a.score).slice(0, 5);
}

function MergeModal({ source, candidates, onClose, onConfirm }) {
  const [selected, setSelected] = React.useState(null);
  return (
    <div>
      <div className="detail-overlay" onClick={onClose} style={{ zIndex: 52 }}/>
      <div className="invite-modal" style={{ zIndex: 53, width: 580 }}>
        <div style={{ padding: '18px 22px 14px', borderBottom: '1px solid var(--border)' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <div>
              <div style={{ fontSize: 18, fontWeight: 600, letterSpacing: '-0.02em' }}>Merge with existing contact</div>
              <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 4 }}>
                Found {candidates.length} possible match{candidates.length !== 1 ? 'es' : ''} for <strong>{source.name || source.customer}</strong>. Merging will combine all deals, activities, and history under one contact record.
              </div>
            </div>
            <button className="detail-close" style={{ marginLeft: 'auto' }} onClick={onClose}>
              <Icon name="close" size={16}/>
            </button>
          </div>
        </div>
        <div style={{ padding: '18px 22px', maxHeight: '60vh', overflowY: 'auto' }}>
          {candidates.length === 0 && <div className="empty">No potential matches found in the contact list.</div>}
          <div className="reassign-list">
            {candidates.map(m => (
              <div
                key={m.contact.id}
                className={`reassign-row ${selected === m.contact.id ? 'on' : ''}`}
                onClick={() => setSelected(m.contact.id)}
              >
                <span className={`radio ${selected === m.contact.id ? 'on' : ''}`}>
                  {selected === m.contact.id && <span className="radio-dot"></span>}
                </span>
                <Avatar name={m.contact.name} sz="sm"/>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontWeight: 500, fontSize: 13 }}>{m.contact.name}</div>
                  <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>
                    {m.contact.phone || 'no phone'} · {m.contact.email || 'no email'} · {m.contact.dealCount || 0} deal{m.contact.dealCount !== 1 ? 's' : ''}
                  </div>
                </div>
                <div style={{ textAlign: 'right' }}>
                  <div style={{ fontSize: 14, fontWeight: 600, color: m.score >= 100 ? 'var(--won)' : m.score >= 60 ? 'var(--accent)' : 'var(--ink-2)' }}>
                    {Math.min(m.score, 100)}%
                  </div>
                  <div style={{ fontSize: 10, color: 'var(--ink-3)' }}>{m.reason.join(', ')}</div>
                </div>
              </div>
            ))}
          </div>
        </div>
        <div style={{ padding: '14px 22px', borderTop: '1px solid var(--border)', background: 'var(--surface-2)', display: 'flex', gap: 8 }}>
          <button className="btn" onClick={onClose}>Cancel</button>
          <button
            className="btn primary"
            style={{ marginLeft: 'auto', opacity: !selected ? 0.5 : 1 }}
            disabled={!selected}
            onClick={() => { onConfirm(selected); onClose(); }}
          ><Icon name="check" size={12}/> Merge profiles</button>
        </div>
      </div>
    </div>
  );
}

window.findPotentialMatches = findPotentialMatches;
window.MergeModal = MergeModal;
