const MergeAccountModal = ({ sourceAccount, allAccounts, onMerge, onClose }) => {
    const [search, setSearch]   = React.useState('');
    const [targetId, setTarget] = React.useState(null);
    const [merging, setMerging] = React.useState(false);
    const [error, setError]     = React.useState('');

    const candidates = allAccounts.filter(a =>
        a.id !== sourceAccount.id &&
        (a.name.toLowerCase().includes(search.toLowerCase()) ||
         (a.main_email || '').toLowerCase().includes(search.toLowerCase()))
    ).slice(0, 20);

    const target = allAccounts.find(a => a.id === targetId);

    const handleMerge = async () => {
        if (!targetId) return;
        if (!window.confirm(`Merge "${sourceAccount.name}" INTO "${target?.name}"?\n\nAll contacts, tasks, and communications will move to "${target?.name}". This cannot be undone.`)) return;
        setMerging(true); setError('');
        try {
            await onMerge(sourceAccount.id, targetId);
            onClose();
        } catch(e) { setError(e.message); setMerging(false); }
    };

    return (
        <div className="modal-overlay" onClick={(e) => e.target === e.currentTarget && onClose()}>
            <div className="modal modal-medium">
                <div className="modal-header">
                    <h2 className="modal-title"><i className="fas fa-code-merge" style={{ marginRight: '0.5rem' }}></i>Merge Account</h2>
                    <button className="modal-close-btn" onClick={onClose}>&times;</button>
                </div>
                <div className="modal-body">
                    <div style={{ background: '#fef3c7', border: '1px solid #fcd34d', borderRadius: '0.375rem', padding: '0.75rem 1rem', marginBottom: '1.25rem', fontSize: '0.875rem' }}>
                        <strong>Merging:</strong> {sourceAccount.name}<br />
                        <span style={{ fontSize: '0.8125rem', color: '#92400e' }}>Contacts, tasks, and communications will be moved to the target account. "{sourceAccount.name}" will be marked as merged.</span>
                    </div>
                    <div className="form-group" style={{ marginBottom: '0.75rem' }}>
                        <label className="form-label">Search for target account</label>
                        <input className="form-input" placeholder="Type name or email…" value={search} onChange={e => setSearch(e.target.value)} autoFocus />
                    </div>
                    <div className="merge-target-list">
                        {candidates.length === 0
                            ? <div style={{ padding: '1rem', color: '#6b7280', fontSize: '0.875rem', textAlign: 'center' }}>No matching accounts</div>
                            : candidates.map(a => (
                                <div key={a.id} className={`merge-target-item ${targetId === a.id ? 'selected' : ''}`} onClick={() => setTarget(a.id)}>
                                    <div style={{ width: '2rem', height: '2rem', background: '#e2e8f0', borderRadius: '0.375rem', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                                        <i className={a.type === 'personal' ? 'fas fa-user' : 'fas fa-building'} style={{ fontSize: '0.75rem', color: '#475569' }}></i>
                                    </div>
                                    <div>
                                        <div style={{ fontWeight: 500, fontSize: '0.875rem' }}>{a.name}</div>
                                        <div style={{ fontSize: '0.75rem', color: '#6b7280' }}>{[a.type, a.main_email].filter(Boolean).join(' · ')}</div>
                                    </div>
                                    {targetId === a.id && <i className="fas fa-check-circle" style={{ marginLeft: 'auto', color: '#3b82f6' }}></i>}
                                </div>
                            ))
                        }
                    </div>
                    {error && <div className="api-error" style={{ marginTop: '0.75rem' }}>{error}</div>}
                    <div className="btn-group">
                        <button className="btn btn-secondary" onClick={onClose} disabled={merging}>Cancel</button>
                        <button className="btn btn-danger" onClick={handleMerge} disabled={!targetId || merging}>
                            {merging ? <><i className="fas fa-spinner fa-spin"></i> Merging…</> : <><i className="fas fa-code-merge"></i> Merge Into {target?.name || '…'}</>}
                        </button>
                    </div>
                </div>
            </div>
        </div>
    );
};
