// 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.
//
// One plane only: everything here is tenant-admin territory (their business,
// their data). Platform operations moved OFF the public app entirely
// (v0.20.0) — they live on the private operator console (server/operator/),
// reachable only over SSH. No operator UI exists in this product on purpose.

// Card registry. `roles` gates visibility; status lines are computed from
// the light home-load below (never from heavy per-section fetches).
// GROUPS (owner's call, 2026-08-02, replacing the flat most-common-first
// order): personal settings lead, then day-to-day team config, then set-once
// workspace setup, with the read-only Audit Log anchoring the bottom. The
// nav's old Preferences and Email buttons consolidated in here — which is
// why this page is now visible to every role, not just managers: reps get
// the "My Settings" group and the role filter hides the rest.
//
// PERMISSION MODEL (owner's call, 2026-08-02): configuring the CRM is
// admin-only by default — it's the owner's business, so the admin holds
// ultimate control. Managers keep day-to-day USE (sending templates,
// applying tags, declaring milestones, reassigning accounts) but not the
// settings that define those vocabularies. A future delegation framework
// lets an admin grant specific settings areas down to managers; until it
// ships, ['admin'] here is the default and the server routes enforce it.
const ALL_ROLES = ['admin', 'manager', 'rep'];
const SETTINGS_SECTIONS = [
    // ── My Settings — personal, every role ──
    { id: 'preferences', icon: 'fa-palette',     title: 'My Preferences', group: 'My Settings',
      blurb: 'Pick the theme the CRM wears for you.', roles: ALL_ROLES },
    { id: 'security', icon: 'fa-shield-alt',     title: 'Security', group: 'My Settings',
      blurb: 'Two-factor sign-in, security keys, and backup codes for your own account.', roles: ALL_ROLES },
    { id: 'email',    icon: 'fa-envelope',       title: 'Email', group: 'My Settings',
      blurb: 'Connect your mailbox to send from the CRM and auto-log customer conversations.', roles: ALL_ROLES },
    // ── Team — day-to-day config ──
    { id: 'users',    icon: 'fa-users',          title: 'Users', group: 'Team',
      blurb: 'Invite teammates, set roles, and move accounts between reps.', roles: ['admin'] },
    { id: 'teams',    icon: 'fa-layer-group',    title: 'Teams', group: 'Team',
      blurb: 'Shared work queues and rep assistants.', roles: ['admin'] },
    { id: 'templates', icon: 'fa-file-signature', title: 'Email Templates', group: 'Team',
      blurb: 'Reusable emails with fill-in-themselves fields and a personal-note slot.', roles: ['admin'] },
    { id: 'tags',     icon: 'fa-tags',           title: 'Tags', group: 'Team',
      blurb: 'The labels your team uses to organize and filter accounts.', roles: ['admin'] },
    { id: 'milestones', icon: 'fa-flag',         title: 'Milestones', group: 'Team',
      blurb: 'The big moments reps can mark on an account’s timeline — onboarded, contract signed, website live.', roles: ['admin'] },
    { id: 'categories', icon: 'fa-boxes',        title: 'Product Categories', group: 'Team',
      blurb: 'How your inventory is organized — the product form offers exactly this list.', roles: ['admin'] },
    // ── Workspace — set-once / connect-once ──
    { id: 'company',  icon: 'fa-building',       title: 'Company Profile', group: 'Workspace',
      blurb: 'Your business name and the contact details printed on quotes and invoices.', roles: ['admin'] },
    { id: 'branding', icon: 'fa-paint-brush',    title: 'Logo & Appearance', group: 'Workspace',
      blurb: 'Upload your logo. Optional custom styling for the adventurous.', roles: ['admin'] },
    { id: 'docstyle', icon: 'fa-file-invoice',   title: 'Document Style', group: 'Workspace',
      blurb: 'Pick the colors and font on your quote and invoice PDFs — with a live preview.', roles: ['admin'] },
    { id: 'leads',    icon: 'fa-globe',          title: 'Website Leads', group: 'Workspace',
      blurb: 'Connect your website’s contact forms so new leads appear in your inbox automatically.', roles: ['admin'] },
    { id: 'integrations', icon: 'fa-plug',       title: 'Integrations', group: 'Workspace',
      blurb: 'Connect GitHub so the work you ship shows up on client timelines.', roles: ['admin'] },
    { id: 'providers', icon: 'fa-globe-americas', title: 'Domain Providers', group: 'Workspace',
      blurb: 'Which registrar accounts you hold — so accepted quotes connect customers to them automatically.', roles: ['admin'] },
    // ── Advanced — the bottom of the page on purpose ──
    { id: 'export',   icon: 'fa-file-export',    title: 'Your Data', group: 'Advanced',
      blurb: 'Download a complete copy of everything in this workspace. It’s yours.', roles: ['admin'] },
    { id: 'audit',    icon: 'fa-clipboard-list', title: 'Audit Log', group: 'Advanced',
      blurb: 'Every change on record — who did what, and when.', roles: ['admin'] },
];

const SettingsView = ({ currentUser, allTags = [], onTagsChange, tenant, onTenantChange, initialSection = null, emailOAuthResult = 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 [templateCount, setTemplateCount] = React.useState(null);
    const [integrations, setIntegrations]   = React.useState(null);
    const [teamCount, setTeamCount]             = React.useState(null);
    const [milestoneCount, setMilestoneCount]   = React.useState(null);
    const [twofa, setTwofa]                     = React.useState(null);

    const isAdmin = currentUser.role === 'admin';

    // Only fetch what this role's cards can actually show — non-admins
    // hitting gated endpoints would just collect 403s.
    React.useEffect(() => {
        api.getEmailStatus().then(setEmailStatus).catch(() => {});
        api.get2faStatus().then(setTwofa).catch(() => {});   // own-user, every role
        if (isAdmin) api.getUsers().then(setUsers).catch(() => {});
        if (isAdmin) api.getTemplates().then(t => setTemplateCount(t.length)).catch(() => {});
        if (isAdmin) api.getIntakeKeys().then(setKeys).catch(() => {});
        if (isAdmin) api.getIntegrations().then(setIntegrations).catch(() => {});
        if (isAdmin) api.getTeams().then(t => setTeamCount(t.length)).catch(() => {});
        if (isAdmin) api.getMilestoneTypes().then(m => setMilestoneCount(m.length)).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 'preferences': {
                const themeId = localStorage.getItem('crm_theme') || currentUser.settings?.theme || 'dark';
                const theme = (typeof THEMES !== 'undefined') && THEMES.find(t => t.id === themeId);
                return theme ? { ok: true, text: `${theme.name} theme` } : null;
            }
            case 'security': {
                if (!twofa) return null;   // fetch failed/rate-limited → no line, never wrong
                const protectedBy = twofa.totp_enabled || (twofa.credentials || []).length > 0;
                return protectedBy
                    ? { ok: true,  text: 'Two-factor is on' }
                    : { ok: false, text: 'Two-factor not set up yet' };
            }
            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': {
                const n = (tenant?.branding?.logos?.length) || (tenant?.branding?.logo ? 1 : 0);
                return n
                    ? { ok: true,  text: n === 1 ? 'Custom logo uploaded' : `${n} logos in your library` }
                    : { ok: false, text: 'Using the default logo' };
            }
            case 'docstyle':
                return (tenant?.docs && Object.keys(tenant.docs).length)
                    ? { ok: true,  text: 'Custom document style' }
                    : { ok: false, text: 'Using the standard look' };
            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 'teams': {
                if (teamCount === null) return null;
                return teamCount
                    ? { ok: true,  text: `${teamCount} team${teamCount === 1 ? '' : 's'} active` }
                    : { ok: false, text: 'No teams yet' };
            }
            case 'tags': {
                // allTags rides in from MainApp — no extra fetch needed.
                return allTags.length
                    ? { ok: true,  text: `${allTags.length} tag${allTags.length === 1 ? '' : 's'} in use` }
                    : { ok: false, text: 'No tags yet' };
            }
            case 'milestones': {
                if (milestoneCount === null) return null;
                return milestoneCount
                    ? { ok: true,  text: `${milestoneCount} milestone type${milestoneCount === 1 ? '' : 's'} defined` }
                    : { ok: false, text: 'No milestone types yet' };
            }
            case 'templates': {
                if (templateCount === null) return null;
                return templateCount
                    ? { ok: true,  text: `${templateCount} template${templateCount === 1 ? '' : 's'} ready to send` }
                    : { ok: false, text: 'No templates yet' };
            }
            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` : ''}` };
            }
            case 'integrations': {
                if (!integrations) return null;
                const gh = integrations.find(c => c.provider === 'github');
                if (!gh) return { ok: false, text: 'Nothing connected yet' };
                return gh.status === 'active'
                    ? { ok: true,  text: `GitHub connected${gh.provider_login ? ` as ${gh.provider_login}` : ''}` }
                    : { ok: false, text: 'GitHub connection needs attention' };
            }
            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 'docstyle': return <DocStyleSection tenant={tenant} onTenantChange={onTenantChange} />;
            case 'preferences': return <PreferencesSection currentUser={currentUser} />;
            case 'security': return <SecuritySection />;
            case 'email':    return <EmailSettingsBody currentUser={currentUser} tenant={tenant} oauthResult={emailOAuthResult} />;
            case 'templates': return <EmailTemplatesSection onCountChange={setTemplateCount} />;
            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 'integrations': return <IntegrationsSection tenant={tenant} />;
            case 'providers': return <ProvidersSection />;
            case 'milestones': return <MilestonesSection currentUser={currentUser} />;
            case 'categories': return <ProductCategoriesSection currentUser={currentUser} />;
            case 'export':   return <DataExportSection />;
            case 'audit':    return <AuditSection />;
            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">
                            <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'}
                            {tenant?.plan?.name ? ` · ${tenant.plan.name} plan` : ''} — set up your CRM the way you want it.
                        </p>
                    </div>
                )}
            </div>

            {section ? (
                <div className="settings-section-body">{renderSection()}</div>
            ) : (
                // Registry order defines group order — walk unique group names,
                // render a label + card grid per group. A role that can only
                // see one group (reps) just gets one unlabeled-feeling block.
                [...new Set(visible.map(s => s.group))].map(group => (
                    <div key={group} className="settings-group">
                        <div className="settings-group-label">{group}</div>
                        <div className="settings-cards">
                            {visible.filter(s => s.group === group).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>
                    </div>
                ))
            )}
        </div>
    );
};
