// Workspace Settings — the full-page, card-first settings area.
//
// Design intent (owner's brief, 2026-07-30): this is the screen a
// non-technical business owner configures their CRM from. It must read like
// "configure your email" / "your logo", never like a cloud-console resource
// list. So: a home of plain-language cards with live status lines, each
// opening one focused section. Replaces the old AdminPanel drawer modal —
// its tabs live on as sections here.
//
// Two planes, kept visually separate:
//   Workspace cards — tenant-admin territory (their business, their data)
//   Platform card   — hosting-operator only (is_platform), manages tenants

// Card registry. `roles` gates visibility; status lines are computed from
// the light home-load below (never from heavy per-section fetches).
const SETTINGS_SECTIONS = [
    { id: 'company',  icon: 'fa-building',       title: 'Company Profile',
      blurb: 'Your business name and the contact details printed on quotes and invoices.', roles: ['admin'] },
    { id: 'branding', icon: 'fa-paint-brush',    title: 'Logo & Appearance',
      blurb: 'Upload your logo. Optional custom styling for the adventurous.', roles: ['admin'] },
    { id: 'email',    icon: 'fa-envelope',       title: 'Email',
      blurb: 'Connect your mailbox to send from the CRM and auto-log customer conversations.', roles: ['admin', 'manager'] },
    { id: 'leads',    icon: 'fa-globe',          title: 'Website Leads',
      blurb: 'Connect your website’s contact forms so new leads appear in your inbox automatically.', roles: ['admin'] },
    { id: 'users',    icon: 'fa-users',          title: 'Users',
      blurb: 'Invite teammates, set roles, and move accounts between reps.', roles: ['admin', 'manager'] },
    { id: 'teams',    icon: 'fa-layer-group',    title: 'Teams',
      blurb: 'Shared work queues and rep assistants.', roles: ['admin', 'manager'] },
    { id: 'tags',     icon: 'fa-tags',           title: 'Tags',
      blurb: 'The labels your team uses to organize and filter accounts.', roles: ['admin', 'manager'] },
    { id: 'audit',    icon: 'fa-clipboard-list', title: 'Audit Log',
      blurb: 'Every change on record — who did what, and when.', roles: ['admin'] },
];

const SettingsView = ({ currentUser, allTags = [], onTagsChange, tenant, onTenantChange, initialSection = null }) => {
    const [section, setSection] = React.useState(initialSection);   // null = card home
    // Light data for the home cards' status lines. Loaded once per visit.
    const [emailStatus, setEmailStatus] = React.useState(null);
    const [users, setUsers]             = React.useState(null);
    const [keys, setKeys]               = React.useState(null);

    const isAdmin    = currentUser.role === 'admin';
    const isPlatform = !!currentUser.is_platform;

    React.useEffect(() => {
        api.getEmailStatus().then(setEmailStatus).catch(() => {});
        api.getUsers().then(setUsers).catch(() => {});
        if (isAdmin) api.getIntakeKeys().then(setKeys).catch(() => {});
    }, []);

    const visible = SETTINGS_SECTIONS.filter(s => s.roles.includes(currentUser.role));

    // One short human line per card — "what's my current state?" at a glance.
    const statusFor = (id) => {
        switch (id) {
            case 'company': {
                const b = tenant?.billing || {};
                return (b.address || b.phone || b.email)
                    ? { ok: true,  text: 'Letterhead is set up' }
                    : { ok: false, text: 'Letterhead not set up yet' };
            }
            case 'branding':
                return tenant?.branding?.logo
                    ? { ok: true,  text: 'Custom logo uploaded' }
                    : { ok: false, text: 'Using the default logo' };
            case 'email': {
                if (!emailStatus) return null;
                const conn = emailStatus.connection;
                if (conn) return { ok: conn.status === 'active', text: `Connected: ${conn.email_address}` };
                return { ok: false, text: (emailStatus.configured_providers || []).length ? 'Not connected yet' : 'Not available on this server' };
            }
            case 'leads': {
                if (!keys) return null;
                const active = keys.filter(k => !k.revoked_at).length;
                return active
                    ? { ok: true,  text: `${active} website${active === 1 ? '' : 's'} connected` }
                    : { ok: false, text: 'No websites connected yet' };
            }
            case 'users': {
                if (!users) return null;
                const active  = users.filter(u => u.is_active).length;
                const pending = users.filter(u => u.invite_pending).length;
                return { ok: true, text: `${active} active user${active === 1 ? '' : 's'}${pending ? ` · ${pending} invite pending` : ''}` };
            }
            default: return null;
        }
    };

    const open = SETTINGS_SECTIONS.find(s => s.id === section);

    const renderSection = () => {
        switch (section) {
            case 'company':  return <CompanySection  tenant={tenant} onTenantChange={onTenantChange} />;
            case 'branding': return <BrandingSection tenant={tenant} onTenantChange={onTenantChange} />;
            case 'email':    return <EmailSettingsBody currentUser={currentUser} oauthResult={null} />;
            case 'leads':    return <LeadsIntakeSection />;
            case 'users':    return <UsersSection currentUser={currentUser} onUsersChange={setUsers} />;
            case 'teams':    return <TeamsSection currentUser={currentUser} />;
            case 'tags':     return <TagsSection currentUser={currentUser} allTags={allTags} onTagsChange={onTagsChange} />;
            case 'audit':    return <AuditSection />;
            case 'platform': return <PlatformSection currentUser={currentUser} />;
            default:         return null;
        }
    };

    return (
        <div className="view-content settings-page">
            <div className="settings-header">
                {section ? (
                    <>
                        <button className="account-detail-back" onClick={() => setSection(null)}>
                            <i className="fas fa-arrow-left"></i> Settings
                        </button>
                        <h2 className="settings-title">
                            {section === 'platform'
                                ? <><i className="fas fa-city" style={{ marginRight: '0.5rem', color: 'var(--accent)' }}></i>Businesses</>
                                : <><i className={`fas ${open.icon}`} style={{ marginRight: '0.5rem', color: 'var(--accent)' }}></i>{open.title}</>}
                        </h2>
                    </>
                ) : (
                    <div>
                        <h2 className="settings-title"><i className="fas fa-sliders-h" style={{ marginRight: '0.5rem', color: 'var(--accent)' }}></i>Settings</h2>
                        <p className="settings-subtitle">{tenant?.name || 'Your workspace'} — set up your CRM the way you want it.</p>
                    </div>
                )}
            </div>

            {section ? (
                <div className="settings-section-body">{renderSection()}</div>
            ) : (
                <>
                    <div className="settings-cards">
                        {visible.map(s => {
                            const st = statusFor(s.id);
                            return (
                                <button key={s.id} className="settings-card" onClick={() => setSection(s.id)}>
                                    <div className="settings-card-icon"><i className={`fas ${s.icon}`}></i></div>
                                    <div className="settings-card-main">
                                        <div className="settings-card-title">{s.title}</div>
                                        <div className="settings-card-blurb">{s.blurb}</div>
                                        {st && (
                                            <div className={`settings-card-status ${st.ok ? 'ok' : ''}`}>
                                                <i className={`fas ${st.ok ? 'fa-check-circle' : 'fa-circle-notch'}`}></i> {st.text}
                                            </div>
                                        )}
                                    </div>
                                    <i className="fas fa-chevron-right settings-card-chevron"></i>
                                </button>
                            );
                        })}
                    </div>

                    {isPlatform && (
                        <>
                            <div className="settings-group-label">Platform — hosting operator only</div>
                            <div className="settings-cards">
                                <button className="settings-card" onClick={() => setSection('platform')}>
                                    <div className="settings-card-icon platform"><i className="fas fa-city"></i></div>
                                    <div className="settings-card-main">
                                        <div className="settings-card-title">Businesses</div>
                                        <div className="settings-card-blurb">Onboard and manage the businesses hosted on this server.</div>
                                    </div>
                                    <i className="fas fa-chevron-right settings-card-chevron"></i>
                                </button>
                            </div>
                        </>
                    )}
                </>
            )}
        </div>
    );
};
