const AccountDetailView = ({ account, currentUser, allTags, allUsers, onBack, onAccountUpdate, onAccountDelete, onMerge, onOpenAccount, openDoc, onOpenDoc }) => {
    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 [showTemplateSend, setShowTemplateSend] = React.useState(false);
    const [showMerge, setShowMerge]         = React.useState(false);
    const [contacts, setContacts]           = React.useState([]);
    // Full record from GET /:id — callers may hand us a list-row stub, but the
    // detail endpoint also carries parent name, children, linked_accounts.
    const [detail, setDetail]               = React.useState(null);
    const [showLink, setShowLink]           = React.useState(false);
    const [comms, setComms]                       = React.useState([]);
    const [completedTasks, setCompletedTasks]     = React.useState([]);
    // Timeline events (activity_events) — milestones now, git/marketing later.
    const [events, setEvents]                     = React.useState([]);
    const [showMilestone, setShowMilestone]       = React.useState(false);
    const [showRepoWire, setShowRepoWire]         = React.useState(false);
    const [showPaymentLinks, setShowPaymentLinks] = React.useState(false);
    const [activityFilter, setActivityFilter]     = React.useState('all');
    const [repFilter, setRepFilter]               = React.useState(null); // comms by one rep ("show me Mark's emails")
    const [quotes, setQuotes]                     = React.useState([]);
    const [invoices, setInvoices]                 = React.useState([]);
    // Split screen: openDoc/onOpenDoc come from MainApp — deep links set
    // account + doc together, so the doc-pane state must outlive this view.
    const [showNewDoc, setShowNewDoc]             = React.useState(null); // 'quote' | 'invoice' | null
    const [loading, setLoading]                   = React.useState(true);
    // A failed load must LOOK failed — without this, a fetch error renders as
    // an account with no contacts/activity/docs, which is a lie.
    const [loadError, setLoadError]               = React.useState(false);
    // 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);
    // thread_id → true when the user expanded that thread's older messages.
    const [expandedThreads, setExpandedThreads]   = React.useState({});

    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}`;

    React.useEffect(() => {
        if (!account) return;
        setActiveTab('overview');
        setEditingAccount(false);
        setActivityFilter('all'); // a source chip from the last account may not exist here — a stuck filter renders an inexplicably empty timeline
        setRepFilter(null);       // same trap: last account's rep may have no comms here
        // (Doc-pane clearing on account switch lives in MainApp now — it owns
        // openDoc and must NOT clear when a deep link sets account + doc together.)
        fetchAll();
    }, [account?.id]);

    const fetchAll = async () => {
        setLoading(true);
        setLoadError(false);
        try {
            const [full, c, cm, done, q, inv, ev] = await Promise.all([
                api.getAccount(account.id),
                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 }),
                api.getActivity({ account_id: account.id }),
            ]);
            setDetail(full);
            setContacts(c);
            setComms(cm);
            setCompletedTasks(done);
            setEvents(ev);
            setQuotes(q);
            setInvoices(inv);
        } catch (err) {
            console.error('AccountDetailView fetch error:', err);
            setLoadError(true);
        } finally {
            setLoading(false);
        }
    };

    // After any account mutation, refetch GET /:id instead of merging the bare
    // PATCH row: the PATCH response has no joined/derived fields (tags,
    // assigned_to_name, billing_stage, counts), so a merge left stale values —
    // e.g. the old rep's name in the accounts table after a reassign.
    const refreshAccount = async () => {
        const full = await api.getAccount(account.id);
        setDetail(full);
        onAccountUpdate(full);
    };

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

    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) => {
        await api.updateAccount(account.id, { assigned_to: userId || null });
        await refreshAccount();
    };

    // Inline follow-up date (owner's ask 2026-08-10): editable from the record
    // itself — no trip through the full edit form. Clearing the input clears it.
    const handleCallbackDate = async (dateStr) => {
        try {
            await api.updateAccount(account.id, { callback_date: dateStr || null });
            await refreshAccount();
        } catch (err) { alert(err.message); }
    };

    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';

    // Domain-provider registry (manager+ only — the API is requireManager).
    // Loaded once for the edit select on the Overview tab; reps just see the name.
    const [providerRegistry, setProviderRegistry] = React.useState([]);
    React.useEffect(() => {
        if (isManager) api.getProviderAccounts().then(d => setProviderRegistry(d.accounts || [])).catch(() => {});
    }, [isManager]);

    const handleProviderLink = async (val) => {
        let body;
        if (val === '') {
            body = {}; // clear
        } else if (val === 'custom-new') {
            const name = window.prompt('Provider name (as the customer knows it):');
            if (!name || !name.trim()) return;
            body = { name: name.trim() };
        } else if (val === 'custom-current') {
            return; // re-selecting the existing free-text entry is a no-op
        } else {
            body = { provider_account_id: parseInt(val, 10) };
        }
        try {
            const updated = await api.setAccountDomainProvider(account.id, body);
            onAccountUpdate({ ...account, ...updated, tags: account.tags });
        } catch (e) { alert(e.message); }
    };

    // A personal account IS the person — nesting a Contacts list under them
    // is business-account ceremony that makes no sense for an individual.
    // They keep everything else (activity, quotes/invoices, attachments).
    const isPersonal = account.type === 'personal';

    const TABS = [
        { id: 'overview',    icon: 'fa-info-circle',    label: 'Overview' },
        ...(isPersonal ? [] : [{ 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' },
    ];

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

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

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

    return (
        // Horizontal split: the account column + (optionally) a docked doc pane.
        <div className="account-detail-split">
        <div className="account-detail-view">

            <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>
                )}
                {/* Billing stage + urgent flare: derived-only, never hand-set.
                    (The old "Active customer" badge retired here 2026-08-09 —
                    the stage badge says strictly more; is_active_customer
                    still drives sidebar sort.) */}
                {billingStage(account.billing_stage) && (
                    <span className={`badge stage-badge ${billingStage(account.billing_stage).cls}`}
                          style={{ flexShrink: 0 }} title={billingStage(account.billing_stage).title}>
                        {billingStage(account.billing_stage).label}
                    </span>
                )}
                {account.urgent_task_count > 0 && (
                    <span className="badge urgent-flare" style={{ flexShrink: 0 }}
                          title={`${account.urgent_task_count} urgent open task${account.urgent_task_count > 1 ? 's' : ''} on this account`}>
                        <i className="fas fa-exclamation-circle"></i> {account.urgent_task_count}
                    </span>
                )}
                {/* Service pills: pipeline-conferred only, never manual — earned
                    by billing/onboarding events, removed by cancellation. */}
                {pipelineTags(account.tags).map(t => {
                    const p = pipelinePill(t);
                    return (
                        <span key={t.id} className="badge service-pill"
                              style={{ flexShrink: 0, color: p.color, borderColor: p.color + '55', background: p.color + '14' }}
                              title="Managed automatically by payment and onboarding events">
                            {p.text}
                        </span>
                    );
                })}
                <span className="badge secondary" style={{ flexShrink: 0 }}>{account.type}</span>
                <div className="account-detail-actions">
                    <button className="btn btn-secondary btn-small" onClick={() => setShowTemplateSend(true)}
                            title="Send a templated email (auto-logged)">
                        <i className="fas fa-paper-plane"></i> Send Email
                    </button>
                    <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>

            {loadError && !loading && (
                <div className="api-error" style={{ margin: '0.75rem 0' }}>
                    <i className="fas fa-exclamation-triangle"></i> Couldn't load this account's data — what's below may be incomplete.
                    <button className="btn btn-secondary btn-small" style={{ marginLeft: '0.75rem' }} onClick={fetchAll}>
                        <i className="fas fa-redo"></i> Retry
                    </button>
                </div>
            )}

            <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>

            <div className="account-detail-body">

                {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
                                                ? <a href={`tel:${account.main_phone}`}>{account.main_phone}</a>
                                                : <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
                                                ? <a href={composeHref(account.main_email)}
                                                     {...(emailProvider ? { target: '_blank', rel: 'noopener' } : {})}
                                                     title={emailProvider ? 'Compose in Outlook (auto-logged)' : 'Compose in your mail app (not logged)'}>
                                                      {account.main_email}
                                                  </a>
                                                : <span style={{ color: '#9ca3af' }}>—</span>}
                                        </div>
                                    </div>
                                    {/* Always rendered (both account types) — an unset date used to
                                        hide the card entirely, which read as "no such feature". */}
                                    <div className="detail-info-card">
                                        <div className="detail-info-label">Next Follow-up</div>
                                        <div className="detail-info-value">
                                            <input
                                                type="date"
                                                className="form-input"
                                                value={account.callback_date ? String(account.callback_date).slice(0, 10) : ''}
                                                onChange={(e) => handleCallbackDate(e.target.value)}
                                                style={{ marginTop: '0.25rem' }}
                                            />
                                        </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>
                                    )}
                                    {(isManager || account.domain_provider_name) && (
                                        <div className="detail-info-card">
                                            <div className="detail-info-label">Domain Provider</div>
                                            <div className="detail-info-value">
                                                {isManager ? (
                                                    <select
                                                        className="form-input"
                                                        value={account.domain_provider_account_id
                                                            ? String(account.domain_provider_account_id)
                                                            : (account.domain_provider_name ? 'custom-current' : '')}
                                                        onChange={(e) => handleProviderLink(e.target.value)}
                                                        style={{ marginTop: '0.25rem' }}
                                                    >
                                                        <option value="">— None —</option>
                                                        {providerRegistry.map(p => (
                                                            <option key={p.id} value={p.id}>{p.label || p.provider}</option>
                                                        ))}
                                                        {!account.domain_provider_account_id && account.domain_provider_name && (
                                                            <option value="custom-current">{account.domain_provider_name} (custom)</option>
                                                        )}
                                                        <option value="custom-new">Custom…</option>
                                                    </select>
                                                ) : account.domain_provider_name}
                                            </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>
                                )}

                                <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">
                                        {/* Manual tags only — pipeline pills live on the header as
                                            service status and never render here (0044 model). */}
                                        {manualTags(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>

                                {/* Related accounts — hierarchy (business only) + links (everyone).
                                    A person relates to companies via LINKS, never as parent/child. */}
                                <div style={{ marginBottom: '1.5rem' }}>
                                    <div className="detail-section-header">
                                        <div className="detail-section-title"><i className="fas fa-sitemap" style={{ marginRight: '0.5rem', color: '#6b7280' }}></i>Related Accounts</div>
                                        <button className="btn btn-secondary btn-small" onClick={() => setShowLink(true)}>
                                            <i className="fas fa-link"></i> Link Account
                                        </button>
                                    </div>

                                    {!isPersonal && detail?.parent_account_id && (
                                        <div className="contact-card-detail" style={{ marginBottom: '0.375rem' }}>
                                            <i className="fas fa-level-up-alt"></i>
                                            <span style={{ color: '#6b7280', fontSize: '0.8125rem' }}>Part of</span>
                                            <a href="#" onClick={(e) => { e.preventDefault(); onOpenAccount && onOpenAccount(detail.parent_account_id); }}>
                                                {detail.parent_account_name}
                                            </a>
                                        </div>
                                    )}

                                    {!isPersonal && (detail?.children || []).map(ch => (
                                        <div key={`ch-${ch.id}`} className="contact-card-detail" style={{ marginBottom: '0.375rem' }}>
                                            <i className="fas fa-level-down-alt"></i>
                                            <span style={{ color: '#6b7280', fontSize: '0.8125rem' }}>Sub-account</span>
                                            <a href="#" onClick={(e) => { e.preventDefault(); onOpenAccount && onOpenAccount(ch.id); }}>{ch.name}</a>
                                        </div>
                                    ))}

                                    {(detail?.linked_accounts || []).map(l => (
                                        <div key={`ln-${l.link_id}`} className="contact-card-detail" style={{ marginBottom: '0.375rem' }}>
                                            <i className={`fas ${l.type === 'personal' ? 'fa-user' : 'fa-building'}`}></i>
                                            <a href="#" onClick={(e) => { e.preventDefault(); onOpenAccount && onOpenAccount(l.id); }}>{l.name}</a>
                                            <span className="tag" style={{ fontSize: '0.7rem' }}>{l.link_type.replace(/_/g, ' ')}</span>
                                            <button className="btn-icon-sm danger" title="Remove link"
                                                    onClick={async () => { await api.unlinkAccounts(account.id, l.link_id); fetchAll(); }}>
                                                <i className="fas fa-times"></i>
                                            </button>
                                        </div>
                                    ))}

                                    {!(detail?.parent_account_id) && !(detail?.children || []).length && !(detail?.linked_accounts || []).length && (
                                        <span style={{ fontSize: '0.8125rem', color: '#9ca3af' }}>
                                            {isPersonal
                                                ? 'Not linked to any business yet — use Link Account to connect them to a company.'
                                                : 'No related accounts — link one, or set this account as another’s parent.'}
                                        </span>
                                    )}
                                </div>
                            </>
                        )}
                    </div>
                )}

                {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">
                                            {isManager && (
                                                <button className="btn-icon-sm" title="Download everything about this person (data request)"
                                                        onClick={() => api.downloadContactExport(contact.id).catch(err => alert(err.message))}>
                                                    <i className="fas fa-file-export"></i>
                                                </button>
                                            )}
                                            <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>
                )}

                {activeTab === 'comms' && (() => {
                    // Completed tasks and timeline events appear in the activity feed alongside
                    // comms — "what happened on this account" is one timeline, not three lists.
                    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 eventItems = events.map(ev => ({
                        _type: 'event', _date: new Date(ev.occurred_at || 0), ...ev
                    }));

                    // Category filter chips. Comms/Tasks/Milestones always offered;
                    // future sources (git, marketing…) get a chip only once events exist.
                    const CATEGORY_LABEL = { github: 'Git', marketing: 'Marketing', monitoring: 'Monitoring', external: 'Events' };
                    const extraSources = [...new Set(events.map(ev => ev.source))].filter(s => s !== 'milestone');
                    const categories = [
                        { id: 'all', label: 'All' },
                        { id: 'comms', label: 'Comms' },
                        { id: 'tasks', label: 'Tasks' },
                        { id: 'milestones', label: 'Milestones' },
                        ...extraSources.map(s => ({ id: s, label: CATEGORY_LABEL[s] || s })),
                    ];
                    const categoryOf = (item) =>
                        item._type === 'comm' ? 'comms'
                        : item._type === 'task' ? 'tasks'
                        : item.source === 'milestone' ? 'milestones'
                        : item.source;

                    // Rep chips (owner's ask 2026-08-10): who has comms on this record.
                    // Offered only when 2+ people show up — one author needs no filter.
                    const repsSeen = [];
                    for (const c of comms) {
                        if (c.created_by && c.created_by_name && !repsSeen.some(r => r.id === c.created_by))
                            repsSeen.push({ id: c.created_by, name: c.created_by_name });
                    }

                    const sorted = [...commItems, ...taskItems, ...eventItems]
                        .filter(i => activityFilter === 'all' || categoryOf(i) === activityFilter)
                        // Rep filter narrows to that person's comms — other item
                        // types drop out; it answers "what did Mark send here".
                        .filter(i => !repFilter || (i._type === 'comm' && i.created_by === repFilter))
                        .sort((a, b) => b._date - a._date);

                    // Thread grouping — DISPLAY ONLY. Auto-logged emails sharing a
                    // provider conversation id stack under their newest message;
                    // nothing is merged or hidden from the data itself, and manual
                    // logs (thread_id null) are never grouped.
                    const seenThreads = {};
                    const feed = [];
                    for (const item of sorted) {
                        if (item._type === 'comm' && item.thread_id) {
                            const head = seenThreads[item.thread_id];
                            if (head) { head._thread.push(item); continue; }
                            item._thread = [];
                            seenThreads[item.thread_id] = item;
                        }
                        feed.push(item);
                    }

                    // One comm row — shared by thread heads and their older replies
                    // (isChild indents + drops the per-row chrome that heads own).
                    const renderComm = (item, isChild) => {
                        const contact = contacts.find(c => c.id === item.contact_id);
                        // Delivery state is only meaningful for mail WE sent — an
                        // inbound message has no delivery outcome of ours to report.
                        const delivery = item.direction === 'outbound' ? deliveryState(item.delivery_status) : null;
                        const laneNote = delivery ? deliveryLaneNote(item.delivery_lane) : '';
                        return (
                            <div key={`comm-${item.id}`}
                                 className={`activity-item${item.is_unread ? ' unread' : ''}${delivery && delivery.cls === 'failed' ? ' bounced' : ''}${isChild ? ' thread-child' : ''}`}>
                                <div className="activity-icon comm">
                                    <i className={`fas ${commIcon(item.type)}`}></i>
                                </div>
                                <div className="activity-body">
                                    <div className="activity-title">
                                        {item.is_unread && <span className="unread-dot" title="Unread in your mailbox"></span>}
                                        {item.subject || `${item.type} (${item.direction})`}
                                        {delivery && (
                                            <span className={`delivery-badge ${delivery.cls}`}
                                                  title={laneNote ? `${delivery.title}\n\n${laneNote}` : delivery.title}>
                                                <i className={`fas ${delivery.icon}`}></i> {delivery.label}
                                            </span>
                                        )}
                                    </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>
                                        {item.created_by_name && (
                                            <span style={{ fontSize: '0.7rem', color: 'var(--text-3)' }}>by {item.created_by_name}</span>
                                        )}
                                    </div>
                                </div>
                                <div className="activity-right">
                                    <span className="activity-date">{formatDate(item.timestamp)}</span>
                                    {/* No edit on log entries — the comms log is append-only by
                                        design (owner, 2026-08-10): it's the record of what happened,
                                        corrected by delete-and-relog, never rewritten. */}
                                    <button className="btn-icon-sm danger" onClick={() => handleDeleteComm(item.id)} title="Delete">
                                        <i className="fas fa-trash"></i>
                                    </button>
                                </div>
                            </div>
                        );
                    };

                    return (
                        <div>
                            <div className="detail-section-header">
                                <div className="detail-section-title">Activity</div>
                                <div style={{ display: 'flex', gap: '0.5rem' }}>
                                    {isManager && (
                                        <button className="btn btn-secondary btn-small" onClick={() => setShowRepoWire(true)}
                                                title="Wire GitHub repos to this timeline">
                                            <i className="fab fa-github"></i> Repos
                                        </button>
                                    )}
                                    <button className="btn btn-secondary btn-small" onClick={() => setShowPaymentLinks(true)}
                                            title="Stripe payment links for this account">
                                        <i className="fas fa-credit-card"></i> Payments
                                    </button>
                                    <button className="btn btn-secondary btn-small" onClick={() => setShowMilestone(true)}>
                                        <i className="fas fa-flag"></i> Add Milestone
                                    </button>
                                    <button className="btn btn-primary btn-small" onClick={() => setShowNewComm(true)}>
                                        <i className="fas fa-plus"></i> Log Communication
                                    </button>
                                </div>
                            </div>

                            <div className="tag-filter-row" style={{ marginBottom: '0.75rem' }}>
                                {categories.map(cat => (
                                    <span key={cat.id}
                                          className="tag-pill tag-filter-chip"
                                          onClick={() => setActivityFilter(cat.id)}
                                          style={activityFilter === cat.id
                                              ? { background: 'var(--accent, #3b82f6)', color: '#fff' }
                                              : {}}>
                                        {cat.label}
                                    </span>
                                ))}
                                {repsSeen.length > 1 && (
                                    <>
                                        <span style={{ borderLeft: '1px solid var(--border, #334155)', margin: '0 0.25rem' }}></span>
                                        {repsSeen.map(r => (
                                            <span key={`rep-${r.id}`}
                                                  className="tag-pill tag-filter-chip"
                                                  onClick={() => setRepFilter(p => p === r.id ? null : r.id)}
                                                  title={`Communications by ${r.name}`}
                                                  style={repFilter === r.id
                                                      ? { background: 'var(--accent, #3b82f6)', color: '#fff' }
                                                      : {}}>
                                                <i className="fas fa-user" style={{ marginRight: '0.25rem', fontSize: '0.7rem' }}></i>{r.name}
                                            </span>
                                        ))}
                                    </>
                                )}
                            </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 older = item._thread || [];
                                        if (older.length === 0) return renderComm(item, false);
                                        const open = !!expandedThreads[item.thread_id];
                                        return (
                                            <div key={`thread-${item.thread_id}-${item.id}`} className="activity-thread">
                                                {renderComm(item, false)}
                                                <button className="thread-toggle"
                                                        onClick={() => setExpandedThreads(p => ({ ...p, [item.thread_id]: !open }))}>
                                                    <i className={`fas fa-chevron-${open ? 'up' : 'down'}`}></i>
                                                    {open ? 'Hide' : 'Show'} {older.length} earlier in this thread
                                                </button>
                                                {open && older.map(o => renderComm(o, true))}
                                            </div>
                                        );
                                    } else if (item._type === 'event') {
                                        // activity_events row — milestones now; git/marketing render
                                        // through the same branch when those sources land.
                                        const color = item.meta?.color || 'var(--accent)';
                                        const icon = { milestone: 'fa-flag', github: 'fa-code-branch', marketing: 'fa-bullhorn', monitoring: 'fa-heartbeat', external: 'fa-bolt' }[item.source] || 'fa-circle';
                                        return (
                                            <div key={`event-${item.id}`} className="activity-item">
                                                <div className="activity-icon" style={{ background: color + '22', color }}>
                                                    <i className={`fas ${icon}`}></i>
                                                </div>
                                                <div className="activity-body">
                                                    <div className="activity-title">{item.title}</div>
                                                    {item.meta?.note && <div className="activity-content">{item.meta.note}</div>}
                                                    {item.meta?.url && (
                                                        <div className="activity-sub">
                                                            <a href={item.meta.url} target="_blank" rel="noopener noreferrer">View on {CATEGORY_LABEL[item.source] || item.source} <i className="fas fa-external-link-alt" style={{ fontSize: '0.65rem' }}></i></a>
                                                        </div>
                                                    )}
                                                    <div className="activity-meta">
                                                        <span className="tag" style={{ fontSize: '0.7rem', background: color + '22', color }}>{item.source === 'external' ? item.event_type : item.source}</span>
                                                        {item.created_by_name && <span style={{ fontSize: '0.75rem', color: 'var(--text-3)' }}>by {item.created_by_name}</span>}
                                                    </div>
                                                </div>
                                                <div className="activity-right">
                                                    <span className="activity-date">{formatDate(item.occurred_at)}</span>
                                                    {isManager && (
                                                        <button className="btn-icon-sm danger" title="Delete"
                                                                onClick={async () => {
                                                                    if (!window.confirm('Delete this timeline event?')) return;
                                                                    try {
                                                                        await api.deleteActivityEvent(item.id);
                                                                        setEvents(prev => prev.filter(e => e.id !== item.id));
                                                                    } catch (err) { alert(err.message); }
                                                                }}>
                                                            <i className="fas fa-trash"></i>
                                                        </button>
                                                    )}
                                                </div>
                                            </div>
                                        );
                                    } else {
                                                                                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>}
                                                    {item.signoff_note && (
                                                        <div className="activity-content" style={{ borderLeft: '3px solid var(--accent, #3b82f6)', paddingLeft: '0.5rem', marginTop: '0.25rem' }}>
                                                            <i className="fas fa-clipboard-check" style={{ marginRight: '0.35rem' }}></i>
                                                            {item.signoff_note}
                                                            {item.signoff_initials && <strong> — {item.signoff_initials}</strong>}
                                                        </div>
                                                    )}
                                                    <div className="activity-meta">
                                                        <span className="task-prio-badge" style={{ background: PRIORITY_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>
                    );
                })()}

                {activeTab === 'quotes' && (
                    <div>
                        <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>
                                <button className="btn btn-primary btn-small" onClick={() => setShowNewDoc('quote')}>
                                    <i className="fas fa-plus"></i> New Quote
                                </button>
                            </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} className="row-clickable"
                                                onClick={() => onOpenDoc({ kind: 'quote', id: q.quote_number || q.id })}
                                                title="Open beside the account">
                                                <td style={{ fontWeight: 600 }}>
                                                    <a className="doc-link" href={'/quotes/' + encodeURIComponent(q.quote_number || q.id)}
                                                       onClick={(e) => { e.stopPropagation(); navClick(e, () => onOpenDoc({ kind: 'quote', id: q.quote_number || q.id })); }}>{q.quote_number || q.id}</a>
                                                </td>
                                                <td>{statusBadge(q.status)}</td>
                                                <td>{fmtMoney(q.total)}</td>
                                                <td>{formatDate(q.created_at)}</td>
                                            </tr>
                                        ))}
                                    </tbody>
                                </table>
                            )}
                        </div>

                        <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>
                                <button className="btn btn-primary btn-small" onClick={() => setShowNewDoc('invoice')}>
                                    <i className="fas fa-plus"></i> New Invoice
                                </button>
                            </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} className="row-clickable"
                                                onClick={() => onOpenDoc({ kind: 'invoice', id: inv.invoice_number || inv.id })}
                                                title="Open beside the account">
                                                <td style={{ fontWeight: 600 }}>
                                                    <a className="doc-link" href={'/invoices/' + encodeURIComponent(inv.invoice_number || inv.id)}
                                                       onClick={(e) => { e.stopPropagation(); navClick(e, () => onOpenDoc({ kind: 'invoice', id: inv.invoice_number || inv.id })); }}>{inv.invoice_number || inv.id}</a>
                                                </td>
                                                <td>{statusBadge(inv.status)}</td>
                                                <td>{fmtMoney(inv.total)}</td>
                                                <td>{formatDate(inv.created_at)}</td>
                                            </tr>
                                        ))}
                                    </tbody>
                                </table>
                            )}
                        </div>
                    </div>
                )}

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

            </div>

            <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)}
                />
            )}

            <Modal isOpen={showLink} onClose={() => setShowLink(false)} title={`Link Account — ${account.name}`}>
                <LinkAccountForm
                    account={account}
                    onLinked={() => { setShowLink(false); fetchAll(); }}
                    onCancel={() => setShowLink(false)}
                />
            </Modal>

            {showTemplateSend && (
                <TemplateSendModal
                    account={account}
                    contacts={contacts}
                    onSent={fetchAll}
                    onClose={() => setShowTemplateSend(false)}
                />
            )}

            {showMilestone && (
                <MilestoneModal
                    accountId={account.id}
                    onCreated={(ev) => {
                        setEvents(prev => [ev, ...prev]);
                        setShowMilestone(false);
                    }}
                    onClose={() => setShowMilestone(false)}
                />
            )}

            {showRepoWire && (
                <RepoWireModal
                    accountId={account.id}
                    // A sync may have just landed commits — refresh the feed.
                    onChanged={() => api.getActivity({ account_id: account.id }).then(setEvents).catch(() => {})}
                    onClose={() => setShowRepoWire(false)}
                />
            )}

            {showPaymentLinks && (
                <PaymentLinksModal
                    accountId={account.id}
                    accountName={account.name}
                    isManager={isManager}
                    onClose={() => setShowPaymentLinks(false)}
                />
            )}

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

            {showNewDoc && (
                <DocFormModal
                    kind={showNewDoc}
                    lockedAccount={account}
                    onClose={() => setShowNewDoc(null)}
                    onCreated={(doc) => {
                        fetchAll();
                        // Land straight in the new doc's pane — the natural next step
                        // after creating it is adding items / sending it.
                        if (doc?.id) onOpenDoc({ kind: showNewDoc, id: doc.quote_number || doc.invoice_number || doc.id });
                    }}
                />
            )}
        </div>

        {openDoc && (
            <DocDetailModal
                inline
                kind={openDoc.kind}
                docId={openDoc.id}
                currentUser={currentUser}
                onClose={() => onOpenDoc(null)}
                onChanged={fetchAll}
            />
        )}
        </div>
    );
};

// Link this account to another (personal ↔ business is the headline case:
// "this person owns/works at that company"). Suggests a sensible link type
// from the two account types but leaves the choice editable.
const LinkAccountForm = ({ account, onLinked, onCancel }) => {
    const [targetId, setTargetId] = React.useState('');
    const [linkType, setLinkType] = React.useState('related');
    const [error, setError]       = React.useState('');
    const [saving, setSaving]     = React.useState(false);

    // Person + business on either side → suggest the personal_business type.
    // AccountPicker hands back the full account, so no local list is needed.
    const pickTarget = (id, a) => {
        setTargetId(id);
        if (a && (a.type === 'personal') !== (account.type === 'personal')) setLinkType('personal_business');
    };

    const submit = async (e) => {
        e.preventDefault();
        if (!targetId) { setError('Pick an account to link.'); return; }
        setSaving(true); setError('');
        try { await api.linkAccounts(account.id, parseInt(targetId), linkType); onLinked(); }
        catch (err) { setError(err.message); setSaving(false); }
    };

    return (
        <form onSubmit={submit}>
            {error && <div className="api-error">{error}</div>}
            <div className="form-grid">
                <div className="form-group full-width">
                    <label className="form-label">Account *</label>
                    <AccountPicker
                        value={targetId}
                        excludeId={account.id}
                        autoFocus
                        onChange={pickTarget}
                    />
                </div>
                <div className="form-group full-width">
                    <label className="form-label">Relationship</label>
                    <select className="form-input" value={linkType} onChange={(e) => setLinkType(e.target.value)}>
                        <option value="personal_business">Personal ↔ Business (owner, employee…)</option>
                        <option value="related">Related</option>
                        <option value="partner">Partner</option>
                        <option value="subsidiary">Subsidiary</option>
                    </select>
                </div>
            </div>
            <div className="btn-group">
                <button type="button" className="btn btn-secondary" onClick={onCancel} disabled={saving}>Cancel</button>
                <button type="submit" className="btn btn-primary" disabled={saving}>
                    {saving ? <><i className="fas fa-spinner fa-spin"></i> Linking…</> : <><i className="fas fa-link"></i> Link Accounts</>}
                </button>
            </div>
        </form>
    );
};
