const AccountDetailView = ({ account, currentUser, allTags, allUsers, onBack, onAccountUpdate, onAccountDelete, onMerge, onTagsChange }) => {
    const [activeTab, setActiveTab]         = React.useState('overview');
    const [editingAccount, setEditingAccount] = React.useState(false);
    const [editingContact, setEditingContact] = React.useState(null); // null | 'new' | contact obj
    const [showNewComm, setShowNewComm]     = React.useState(false);
    const [showMerge, setShowMerge]         = React.useState(false);
    const [contacts, setContacts]           = React.useState([]);
    const [comms, setComms]                       = React.useState([]);
    const [completedTasks, setCompletedTasks]     = React.useState([]);
    const [quotes, setQuotes]                     = React.useState([]);
    const [invoices, setInvoices]                 = React.useState([]);
    const [loading, setLoading]                   = React.useState(true);
    // Which mail provider (if any) this user has connected — drives whether
    // clicking a contact email opens Outlook web (gets auto-logged by the
    // poller) or falls back to the OS mail app via mailto: (never logged).
    const [emailProvider, setEmailProvider]       = React.useState(null);

    React.useEffect(() => {
        api.getEmailStatus()
            .then(s => setEmailProvider(s.connection?.status === 'active' ? s.connection.provider : null))
            .catch(() => {}); // no connection info → mailto fallback, not an error
    }, []);

    // Outlook web compose deep-link: mail sent here goes out through the
    // connected mailbox, so the auto-log poller sees it in Sent Items.
    const composeHref = (address) =>
        emailProvider === 'microsoft'
            ? `https://outlook.office.com/mail/deeplink/compose?to=${encodeURIComponent(address)}`
            : `mailto:${address}`;

    // Reset tab and reload data when account changes
    React.useEffect(() => {
        if (!account) return;
        setActiveTab('overview');
        setEditingAccount(false);
        fetchAll();
    }, [account?.id]);

    const fetchAll = async () => {
        setLoading(true);
        try {
            const [c, cm, done, q, inv] = await Promise.all([
                api.getContacts({ account_id: account.id }),
                api.getComms({ account_id: account.id }),
                api.getTasks({ account_id: account.id, completed: 'true' }),
                api.getQuotes({ account_id: account.id }),
                api.getInvoices({ account_id: account.id }),
            ]);
            setContacts(c);
            setComms(cm);
            setCompletedTasks(done);
            setQuotes(q);
            setInvoices(inv);
        } catch (err) {
            console.error('AccountDetailView fetch error:', err);
        } finally {
            setLoading(false);
        }
    };

    const handleUpdate = async (formData) => {
        const updated = await api.updateAccount(account.id, formData);
        setEditingAccount(false);
        onAccountUpdate(updated);
    };

    const handleDelete = async () => {
        if (!window.confirm(`Delete "${account.name}"? This cannot be undone.`)) return;
        await api.deleteAccount(account.id);
        onAccountDelete(account.id);
    };

    const handleAddTag = async (tagId) => {
        const updatedTags = await api.addAccountTag(account.id, tagId);
        onAccountUpdate({ ...account, tags: updatedTags });
    };

    const handleRemoveTag = async (tagId) => {
        await api.removeAccountTag(account.id, tagId);
        const updatedTags = (account.tags || []).filter(t => t.id !== tagId);
        onAccountUpdate({ ...account, tags: updatedTags });
    };

    const handleReassign = async (userId) => {
        const updated = await api.updateAccount(account.id, { assigned_to: userId || null });
        onAccountUpdate(updated);
    };

    const handleCreateComm = async (formData) => {
        const comm = await api.createComm(formData);
        setComms(prev => [comm, ...prev]);
        setShowNewComm(false);
    };

    const handleDeleteComm = async (commId) => {
        if (!window.confirm('Delete this communication log entry?')) return;
        await api.deleteComm(commId);
        setComms(prev => prev.filter(c => c.id !== commId));
    };

    const handleContactSaved = async () => {
        const fresh = await api.getContacts({ account_id: account.id });
        setContacts(fresh);
    };

    const handleDeleteContact = async (contact) => {
        if (!window.confirm(`Delete ${contact.first_name} ${contact.last_name || ''}?`)) return;
        await api.deleteContact(contact.id);
        setContacts(prev => prev.filter(c => c.id !== contact.id));
    };

    const isManager = currentUser.role === 'admin' || currentUser.role === 'manager';

    const TABS = [
        { id: 'overview',    icon: 'fa-info-circle',    label: 'Overview' },
        { id: 'contacts',    icon: 'fa-users',           label: 'Contacts' },
        { id: 'comms',       icon: 'fa-stream',           label: 'Activity' },
        { id: 'quotes',      icon: 'fa-file-alt',        label: 'Quotes & Invoices' },
        { id: 'attachments', icon: 'fa-paperclip',       label: 'Attachments' },
    ];

    // ── Comm type icon helper ───────────────────────────────────────
    const commIcon = (type) => ({ email: 'fa-envelope', phone: 'fa-phone', meeting: 'fa-calendar', note: 'fa-sticky-note', sms: 'fa-sms' }[type] || 'fa-comment');

    // ── Status badge helper ─────────────────────────────────────────
    const statusBadge = (status) => <span className={`status-badge ${status}`}>{status}</span>;

    // ── Currency formatter ──────────────────────────────────────────
    const fmtMoney = (v) => v != null ? `$${parseFloat(v).toFixed(2)}` : '—';

    return (
        <div className="account-detail-view">

            {/* ── Header ── */}
            <div className="account-detail-header">
                <button className="account-detail-back" onClick={onBack}>
                    <i className="fas fa-arrow-left"></i> Back
                </button>
                <div className="account-detail-title">{account.name}</div>
                {account.customer_number && (
                    <span className="customer-number-badge customer-number-lg" style={{ flexShrink: 0 }}>
                        {account.customer_number}
                    </span>
                )}
                <span className={`badge ${account.reference_only ? 'secondary' : 'success'}`} style={{ flexShrink: 0 }}>
                    {account.reference_only ? 'Reference' : 'Active'}
                </span>
                <span className="badge secondary" style={{ flexShrink: 0 }}>{account.type}</span>
                <div className="account-detail-actions">
                    <button
                        className="btn btn-secondary btn-small"
                        onClick={() => setEditingAccount(e => !e)}
                        title={editingAccount ? 'Cancel edit' : 'Edit account'}
                    >
                        <i className={`fas ${editingAccount ? 'fa-times' : 'fa-pencil-alt'}`}></i>
                        {editingAccount ? ' Cancel' : ' Edit'}
                    </button>
                    {isManager && (
                        <button className="btn btn-secondary btn-small" onClick={() => setShowMerge(true)} title="Merge account">
                            <i className="fas fa-code-merge"></i> Merge
                        </button>
                    )}
                    {currentUser.role === 'admin' && (
                        <button className="btn btn-danger btn-small" onClick={handleDelete} title="Delete account">
                            <i className="fas fa-trash"></i>
                        </button>
                    )}
                </div>
            </div>

            {/* ── Tab Bar ── */}
            <div className="account-detail-tabs">
                {TABS.map(tab => (
                    <button
                        key={tab.id}
                        className={`account-detail-tab ${activeTab === tab.id ? 'active' : ''}`}
                        onClick={() => setActiveTab(tab.id)}
                    >
                        <i className={`fas ${tab.icon}`}></i> {tab.label}
                    </button>
                ))}
            </div>

            {/* ── Body ── */}
            <div className="account-detail-body">

                {/* ── Overview Tab ── */}
                {activeTab === 'overview' && (
                    <div>
                        {editingAccount ? (
                            <AccountForm
                                initial={account}
                                onSubmit={handleUpdate}
                                onCancel={() => setEditingAccount(false)}
                            />
                        ) : (
                            <>
                                <div className="detail-info-grid">
                                    <div className="detail-info-card">
                                        <div className="detail-info-label">Name</div>
                                        <div className="detail-info-value">{account.name}</div>
                                    </div>
                                    <div className="detail-info-card">
                                        <div className="detail-info-label">Type</div>
                                        <div className="detail-info-value" style={{ textTransform: 'capitalize' }}>{account.type}</div>
                                    </div>
                                    <div className="detail-info-card">
                                        <div className="detail-info-label">Phone</div>
                                        <div className="detail-info-value">{account.main_phone || <span style={{ color: '#9ca3af' }}>—</span>}</div>
                                    </div>
                                    <div className="detail-info-card">
                                        <div className="detail-info-label">Email</div>
                                        <div className="detail-info-value">{account.main_email || <span style={{ color: '#9ca3af' }}>—</span>}</div>
                                    </div>
                                    {account.callback_date && (
                                        <div className="detail-info-card">
                                            <div className="detail-info-label">Next Follow-up</div>
                                            <div className="detail-info-value">{formatDate(account.callback_date)}</div>
                                        </div>
                                    )}
                                    {isManager && (
                                        <div className="detail-info-card">
                                            <div className="detail-info-label">Assigned Rep</div>
                                            <div className="detail-info-value">
                                                <select
                                                    className="form-input"
                                                    value={account.assigned_to || ''}
                                                    onChange={(e) => handleReassign(e.target.value ? parseInt(e.target.value) : null)}
                                                    style={{ marginTop: '0.25rem' }}
                                                >
                                                    <option value="">— Unassigned —</option>
                                                    {allUsers.filter(u => u.is_active).map(u => (
                                                        <option key={u.id} value={u.id}>{u.first_name} {u.last_name} ({u.role})</option>
                                                    ))}
                                                </select>
                                            </div>
                                        </div>
                                    )}
                                </div>

                                {account.notes && (
                                    <div className="detail-info-card" style={{ marginBottom: '1.5rem' }}>
                                        <div className="detail-info-label">Notes</div>
                                        <div className="detail-info-value" style={{ whiteSpace: 'pre-wrap', marginTop: '0.25rem', lineHeight: '1.6' }}>{account.notes}</div>
                                    </div>
                                )}

                                {/* Tags */}
                                <div style={{ marginBottom: '1.5rem' }}>
                                    <div className="detail-section-header">
                                        <div className="detail-section-title"><i className="fas fa-tags" style={{ marginRight: '0.5rem', color: '#6b7280' }}></i>Tags</div>
                                    </div>
                                    <div className="account-tags-row">
                                        {(account.tags || []).map(t => (
                                            <span key={t.id} className="tag-pill" style={{ background: t.color + '22', color: t.color, border: `1px solid ${t.color}44` }}>
                                                {t.name}
                                                <button className="tag-pill-remove" onClick={() => handleRemoveTag(t.id)} title="Remove tag">×</button>
                                            </span>
                                        ))}
                                        {allTags.filter(t => !(account.tags || []).find(at => at.id === t.id)).length > 0 && (
                                            <div className="tag-selector">
                                                <select defaultValue="" onChange={e => { if (e.target.value) { handleAddTag(parseInt(e.target.value)); e.target.value = ''; } }}>
                                                    <option value="">+ Add tag…</option>
                                                    {allTags.filter(t => !(account.tags || []).find(at => at.id === t.id)).map(t => (
                                                        <option key={t.id} value={t.id}>{t.name}</option>
                                                    ))}
                                                </select>
                                            </div>
                                        )}
                                        {allTags.length === 0 && (account.tags || []).length === 0 && (
                                            <span style={{ fontSize: '0.8125rem', color: '#9ca3af' }}>No tags — create them in Admin Panel</span>
                                        )}
                                    </div>
                                </div>
                            </>
                        )}
                    </div>
                )}

                {/* ── Contacts Tab ── */}
                {activeTab === 'contacts' && (
                    <div>
                        <div className="detail-section-header">
                            <div className="detail-section-title">Contacts</div>
                            <button className="btn btn-primary btn-small" onClick={() => setEditingContact('new')}>
                                <i className="fas fa-user-plus"></i> Add Contact
                            </button>
                        </div>

                        {loading ? (
                            <div className="loading-state"><i className="fas fa-spinner fa-spin"></i> Loading…</div>
                        ) : contacts.length === 0 ? (
                            <div className="empty-state">
                                <i className="fas fa-users empty-state-icon"></i>
                                <p className="empty-state-message">No contacts yet — click Add Contact above.</p>
                            </div>
                        ) : (
                            contacts.map(contact => (
                                <div key={contact.id} className="contact-card">
                                    <div className="contact-card-header">
                                        <div>
                                            <span className="contact-card-name">
                                                {contact.first_name} {contact.last_name}
                                                {contact.is_primary && <span className="primary-badge">Primary</span>}
                                            </span>
                                            {(contact.title || contact.role) && (
                                                <div className="contact-card-title">{[contact.title, contact.role].filter(Boolean).join(' · ')}</div>
                                            )}
                                        </div>
                                        <div className="contact-card-actions">
                                            <button className="btn-icon-sm" title="Edit contact" onClick={() => setEditingContact(contact)}>
                                                <i className="fas fa-pencil-alt"></i>
                                            </button>
                                            <button className="btn-icon-sm danger" title="Delete contact" onClick={() => handleDeleteContact(contact)}>
                                                <i className="fas fa-trash"></i>
                                            </button>
                                        </div>
                                    </div>
                                    {contact.emails?.map((e, i) => (
                                        <div key={i} className="contact-card-detail">
                                            <i className="fas fa-envelope"></i>
                                            <a href={composeHref(e.value)}
                                               {...(emailProvider ? { target: '_blank', rel: 'noopener' } : {})}
                                               title={emailProvider ? 'Compose in Outlook (auto-logged)' : 'Compose in your mail app (not logged)'}>
                                                {e.value}
                                            </a>
                                            <span style={{ fontSize: '0.7rem', color: '#9ca3af' }}>{e.type}{e.is_primary ? ' ★' : ''}</span>
                                        </div>
                                    ))}
                                    {contact.phones?.map((p, i) => (
                                        <div key={i} className="contact-card-detail">
                                            <i className="fas fa-phone"></i>
                                            <a href={`tel:${p.value}`}>{p.value}</a>
                                            <span style={{ fontSize: '0.7rem', color: '#9ca3af' }}>{p.type}{p.is_primary ? ' ★' : ''}</span>
                                        </div>
                                    ))}
                                    {contact.department && <div className="contact-card-detail"><i className="fas fa-sitemap"></i><span>{contact.department}</span></div>}
                                    {contact.location && <div className="contact-card-detail"><i className="fas fa-map-marker-alt"></i><span>{contact.location}</span></div>}
                                    {contact.notes && <div style={{ fontSize: '0.8125rem', color: '#6b7280', marginTop: '0.375rem', fontStyle: 'italic' }}>{contact.notes}</div>}
                                </div>
                            ))
                        )}
                    </div>
                )}

                {/* ── Activity Tab ── */}
                {activeTab === 'comms' && (() => {
                    // Build a unified chronological feed of comms + completed tasks
                    const commItems = comms.map(c => ({
                        _type: 'comm', _date: new Date(c.timestamp || 0), ...c
                    }));
                    const taskItems = completedTasks.map(t => ({
                        _type: 'task', _date: new Date(t.completed_at || t.updated_at || 0), ...t
                    }));
                    const feed = [...commItems, ...taskItems].sort((a, b) => b._date - a._date);

                    return (
                        <div>
                            <div className="detail-section-header">
                                <div className="detail-section-title">Activity</div>
                                <button className="btn btn-primary btn-small" onClick={() => setShowNewComm(true)}>
                                    <i className="fas fa-plus"></i> Log Communication
                                </button>
                            </div>

                            {loading ? (
                                <div className="loading-state"><i className="fas fa-spinner fa-spin"></i> Loading…</div>
                            ) : feed.length === 0 ? (
                                <div className="empty-state">
                                    <i className="fas fa-stream empty-state-icon"></i>
                                    <p className="empty-state-message">No activity yet.</p>
                                    <button className="btn btn-primary btn-small" style={{ marginTop: '0.5rem' }} onClick={() => setShowNewComm(true)}>
                                        <i className="fas fa-plus"></i> Log First Communication
                                    </button>
                                </div>
                            ) : (
                                feed.map(item => {
                                    if (item._type === 'comm') {
                                        const contact = contacts.find(c => c.id === item.contact_id);
                                        return (
                                            <div key={`comm-${item.id}`} className="activity-item">
                                                <div className="activity-icon comm">
                                                    <i className={`fas ${commIcon(item.type)}`}></i>
                                                </div>
                                                <div className="activity-body">
                                                    <div className="activity-title">
                                                        {item.subject || `${item.type} (${item.direction})`}
                                                    </div>
                                                    {contact && <div className="activity-sub">with {contact.first_name} {contact.last_name}</div>}
                                                    {item.content && <div className="activity-content">{item.content}</div>}
                                                    <div className="activity-meta">
                                                        <span className="tag" style={{ fontSize: '0.7rem' }}>{item.type}</span>
                                                        <span className="tag" style={{ fontSize: '0.7rem' }}>{item.direction}</span>
                                                    </div>
                                                </div>
                                                <div className="activity-right">
                                                    <span className="activity-date">{formatDate(item.timestamp)}</span>
                                                    <button className="btn-icon-sm danger" onClick={() => handleDeleteComm(item.id)} title="Delete">
                                                        <i className="fas fa-trash"></i>
                                                    </button>
                                                </div>
                                            </div>
                                        );
                                    } else {
                                        // Completed task
                                        const PRIO_COLOR = { urgent: '#dc2626', high: '#ef4444', medium: '#f59e0b', low: '#6b7280', normal: '#6b7280' };
                                        return (
                                            <div key={`task-${item.id}`} className="activity-item completed-task">
                                                <div className="activity-icon task-done">
                                                    <i className="fas fa-check"></i>
                                                </div>
                                                <div className="activity-body">
                                                    <div className="activity-title">{item.title}</div>
                                                    {item.notes && <div className="activity-content">{item.notes}</div>}
                                                    <div className="activity-meta">
                                                        <span className="task-prio-badge" style={{ background: PRIO_COLOR[item.priority] || '#6b7280' }}>{item.priority}</span>
                                                        <span className="badge secondary" style={{ fontSize: '0.7rem' }}>{item.task_type.replace(/_/g, ' ')}</span>
                                                        {item.due_date && <span style={{ fontSize: '0.75rem', color: '#6b7280' }}>was due {formatDate(item.due_date)}</span>}
                                                    </div>
                                                </div>
                                                <div className="activity-right">
                                                    <span className="activity-date">Completed {formatDate(item.completed_at)}</span>
                                                </div>
                                            </div>
                                        );
                                    }
                                })
                            )}
                        </div>
                    );
                })()}

                {/* ── Quotes & Invoices Tab ── */}
                {activeTab === 'quotes' && (
                    <div>
                        {/* Quotes section */}
                        <div style={{ marginBottom: '2rem' }}>
                            <div className="detail-section-header">
                                <div className="detail-section-title"><i className="fas fa-file-alt" style={{ marginRight: '0.5rem', color: '#6b7280' }}></i>Quotes</div>
                            </div>
                            {loading ? (
                                <div className="loading-state"><i className="fas fa-spinner fa-spin"></i> Loading…</div>
                            ) : quotes.length === 0 ? (
                                <div className="empty-state" style={{ padding: '1rem' }}>
                                    <p className="empty-state-message">No quotes yet.</p>
                                </div>
                            ) : (
                                <table className="data-table">
                                    <thead>
                                        <tr>
                                            <th>#</th>
                                            <th>Status</th>
                                            <th>Total</th>
                                            <th>Date</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        {quotes.map(q => (
                                            <tr key={q.id}>
                                                <td style={{ fontWeight: 600 }}>{q.quote_number || q.id}</td>
                                                <td>{statusBadge(q.status)}</td>
                                                <td>{fmtMoney(q.total)}</td>
                                                <td>{formatDate(q.created_at)}</td>
                                            </tr>
                                        ))}
                                    </tbody>
                                </table>
                            )}
                        </div>

                        {/* Invoices section */}
                        <div>
                            <div className="detail-section-header">
                                <div className="detail-section-title"><i className="fas fa-file-invoice-dollar" style={{ marginRight: '0.5rem', color: '#6b7280' }}></i>Invoices</div>
                            </div>
                            {loading ? (
                                <div className="loading-state"><i className="fas fa-spinner fa-spin"></i> Loading…</div>
                            ) : invoices.length === 0 ? (
                                <div className="empty-state" style={{ padding: '1rem' }}>
                                    <p className="empty-state-message">No invoices yet.</p>
                                </div>
                            ) : (
                                <table className="data-table">
                                    <thead>
                                        <tr>
                                            <th>#</th>
                                            <th>Status</th>
                                            <th>Total</th>
                                            <th>Date</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        {invoices.map(inv => (
                                            <tr key={inv.id}>
                                                <td style={{ fontWeight: 600 }}>{inv.invoice_number || inv.id}</td>
                                                <td>{statusBadge(inv.status)}</td>
                                                <td>{fmtMoney(inv.total)}</td>
                                                <td>{formatDate(inv.created_at)}</td>
                                            </tr>
                                        ))}
                                    </tbody>
                                </table>
                            )}
                        </div>
                    </div>
                )}

                {/* ── Attachments Tab ── */}
                {activeTab === 'attachments' && (
                    <AttachmentsPanel entityType="account" entityId={account.id} />
                )}

            </div>

            {/* ── Modals ── */}
            <Modal isOpen={showNewComm} onClose={() => setShowNewComm(false)} title={`Log Communication — ${account.name}`}>
                <CommForm
                    accountId={account.id}
                    contacts={contacts}
                    onSubmit={handleCreateComm}
                    onCancel={() => setShowNewComm(false)}
                />
            </Modal>

            {editingContact && (
                <ContactEditModal
                    contact={editingContact === 'new' ? null : editingContact}
                    accountId={account.id}
                    onSave={handleContactSaved}
                    onClose={() => setEditingContact(null)}
                />
            )}

            {showMerge && (
                <MergeAccountModal
                    sourceAccount={account}
                    allAccounts={[]}
                    onMerge={async (sourceId, targetId) => {
                        await onMerge(sourceId, targetId);
                        setShowMerge(false);
                    }}
                    onClose={() => setShowMerge(false)}
                />
            )}
        </div>
    );
};
