import React, { useEffect, useState } from 'react';
import { __ } from '@wordpress/i18n';

const appData = window.manfietExpenseTrackerData || {};

const requestJson = (url, options = {}) => {
    const headers = {
        'Content-Type': 'application/json',
        ...(options.headers || {}),
    };

    if (appData.restNonce) {
        headers['X-WP-Nonce'] = appData.restNonce;
    }

    return fetch(url, {
        credentials: 'same-origin',
        ...options,
        headers,
    }).then(async (response) => {
        const data = await response.json().catch(() => ({}));

        if (!response.ok) {
            throw new Error(data.message || 'Request failed');
        }

        return data;
    });
};

const IconGeneral = ({ size = 18, color = 'currentColor' }) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ display: 'block' }}>
        <circle cx="12" cy="12" r="3" />
        <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z" />
    </svg>
);

const IconModules = ({ size = 18, color = 'currentColor' }) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ display: 'block' }}>
        <path d="M12 2L2 7l10 5 10-5-10-5z" />
        <path d="M2 17l10 5 10-5" />
        <path d="M2 12l10 5 10-5" />
    </svg>
);

const IconGSheets = ({ size = 18, color = 'currentColor' }) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ display: 'block' }}>
        <rect x="3" y="3" width="18" height="18" rx="2" ry="2" />
        <line x1="3" y1="9" x2="21" y2="9" />
        <line x1="3" y1="15" x2="21" y2="15" />
        <line x1="9" y1="3" x2="9" y2="21" />
        <line x1="15" y1="3" x2="15" y2="21" />
    </svg>
);

const IconEmail = ({ size = 18, color = 'currentColor' }) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ display: 'block' }}>
        <path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z" />
        <polyline points="22,6 12,13 2,6" />
    </svg>
);

const IconAdvanced = ({ size = 18, color = 'currentColor' }) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ display: 'block' }}>
        <path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z" />
        <line x1="12" y1="9" x2="12" y2="13" />
        <line x1="12" y1="17" x2="12.01" y2="17" />
    </svg>
);

const IconBudget = ({ size = 18, color = 'currentColor' }) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ display: 'block' }}>
        <line x1="12" y1="1" x2="12" y2="23" />
        <path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6" />
    </svg>
);

const IconRefresh = ({ size = 14, color = 'currentColor' }) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ display: 'block' }}>
        <polyline points="23 4 23 10 17 10" />
        <path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10" />
    </svg>
);

const IconZap = ({ size = 14, color = 'currentColor' }) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ display: 'block' }}>
        <polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2" />
    </svg>
);

const SettingsManager = () => {
    const restBase = appData.restBase || '/wp-json/manfi-expense-tracker/v1/';
    const [settings, setSettings] = useState({
        default_budget: 500,
        default_weekly_budget: 125,
        default_yearly_budget: 6000,
        export_unknown_user_label: 'Unknown User',
        expenses_per_page: 20,
        currency: 'USD',
        enable_invoice_manager: 0,
        invoice_late_fee_enabled: 1,
        invoice_late_fee_pct: 5.0,
        invoice_late_fee_type: 'percentage',
        invoice_default_terms: "• Payment is due on or before the specified due date.\n• An overdue/late payment fee of {late_fee}% will apply to any unpaid balance after the due date.\n• Please mention the invoice number as reference when making payments.",
        enable_gutenberg_blocks: 1,
        enable_elementor_widgets: 0,
        email_sender_address: '',
        email_sender_name: 'Manfi Expense Tracker',
        currency_symbols: {}
    });

    const [loading, setLoading] = useState(true);
    const [saving, setSaving] = useState(false);
    const [error, setError] = useState('');
    const [success, setSuccess] = useState('');
    const [rollbackVersion, setRollbackVersion] = useState('');
    const [activeTab, setActiveTab] = useState('general');

    const tabs = [
        { id: 'general', label: __('General & Budgets', 'manfi-expense-tracker'), Icon: IconGeneral },
        { id: 'modules', label: __('Modules & Builder', 'manfi-expense-tracker'), Icon: IconModules },
        { id: 'gsheets', label: __('Google Sheets Sync', 'manfi-expense-tracker'), Icon: IconGSheets },
        { id: 'email', label: __('Email Alerts', 'manfi-expense-tracker'), Icon: IconEmail },
        { id: 'advanced', label: __('Advanced & Rollback', 'manfi-expense-tracker'), Icon: IconAdvanced },
    ];

    const [gsheets, setGsheets] = useState({
        webhook_url: '',
        auto_sync: false,
        sync_token: '',
        expenses_formula: '',
        invoices_formula: '',
    });
    const [gsheetsSaving, setGsheetsSaving] = useState(false);
    const [copiedKey, setCopiedKey] = useState('');

    const loadGsheets = () => {
        requestJson(`${restBase}gsheets/settings`)
            .then((data) => setGsheets(data))
            .catch(() => {});
    };

    useEffect(() => {
        Promise.all([
            requestJson(`${restBase}settings`),
            requestJson(`${restBase}gsheets/settings`),
        ])
            .then(([settingsData, gsheetsData]) => {
                setSettings(settingsData);
                setGsheets(gsheetsData);
                setLoading(false);
            })
            .catch((err) => {
                setError(err.message || __('Failed to load settings.', 'manfi-expense-tracker'));
                setLoading(false);
            });
    }, []);

    const handleChange = (key, value) => {
        setSettings((prev) => ({
            ...prev,
            [key]: value
        }));
    };

    const handleCopyFormula = (text, key) => {
        navigator.clipboard.writeText(text).then(() => {
            setCopiedKey(key);
            setTimeout(() => setCopiedKey(''), 2000);
        });
    };

    const handleSaveGsheets = () => {
        setGsheetsSaving(true);
        requestJson(`${restBase}gsheets/settings`, {
            method: 'POST',
            body: JSON.stringify({
                webhook_url: gsheets.webhook_url,
                auto_sync: gsheets.auto_sync,
            }),
        })
            .then((data) => {
                setGsheets(data);
                setSuccess(__('Google Sheets & Sync settings saved.', 'manfi-expense-tracker'));
            })
            .catch((err) => setError(err.message || __('Failed to save Google Sheets settings.', 'manfi-expense-tracker')))
            .finally(() => setGsheetsSaving(false));
    };

    const handleRegenerateToken = () => {
        if (!confirm(__('Regenerating token will invalidate existing Google Sheets IMPORTDATA links. Continue?', 'manfi-expense-tracker'))) {
            return;
        }

        setGsheetsSaving(true);
        requestJson(`${restBase}gsheets/settings`, {
            method: 'POST',
            body: JSON.stringify({ regenerate_token: 1 }),
        })
            .then((data) => {
                setGsheets(data);
                setSuccess(__('New security token generated successfully.', 'manfi-expense-tracker'));
            })
            .catch((err) => setError(err.message || __('Failed to regenerate token.', 'manfi-expense-tracker')))
            .finally(() => setGsheetsSaving(false));
    };

    const handleBulkSync = () => {
        setGsheetsSaving(true);
        requestJson(`${restBase}gsheets/sync-all`, { method: 'POST' })
            .then((res) => setSuccess(res.message || __('Bulk sync triggered.', 'manfi-expense-tracker')))
            .catch((err) => setError(err.message || __('Failed to trigger bulk sync.', 'manfi-expense-tracker')))
            .finally(() => setGsheetsSaving(false));
    };

    const handleSave = (e) => {
        e.preventDefault();
        setSaving(true);
        setError('');
        setSuccess('');

        requestJson(`${restBase}settings`, {
            method: 'POST',
            body: JSON.stringify(settings)
        })
            .then((data) => {
                setSuccess(data.message || __('Settings saved successfully.', 'manfi-expense-tracker'));
                setSaving(false);
                window.scrollTo({ top: 0, behavior: 'smooth' });
            })
            .catch((err) => {
                setError(err.message || __('Failed to save settings.', 'manfi-expense-tracker'));
                setSaving(false);
                window.scrollTo({ top: 0, behavior: 'smooth' });
            });
    };

    if (loading) {
        return (
            <div className="manfiet-page-shell">
                <div style={{ padding: '40px', textAlign: 'center', color: '#64748b' }}>
                    <div style={{ fontSize: '32px', marginBottom: '12px' }}>🔄</div>
                    <p style={{ margin: 0, fontWeight: '600' }}>{__('Loading settings dashboard...', 'manfi-expense-tracker')}</p>
                </div>
            </div>
        );
    }

    const currentSymbol = (settings.currency_symbols && settings.currency_symbols[settings.currency]) || '$';

    return (
        <div className="manfiet-page-shell">
            <div className="manfiet-page-hero">
                <div className="left-section">
                    <h1 className="manfiet-page-title">{__('Global Plugin Settings', 'manfi-expense-tracker')}</h1>
                    <p className="manfiet-page-subtitle">{__('Configure thresholds, currency formatting, email logs, module switches, and developer rollback tools.', 'manfi-expense-tracker')}</p>
                </div>
            </div>

            {error && <div className="manfiet-alert manfiet-alert-error" style={{ marginBottom: '24px', borderRadius: '8px' }}>{error}</div>}
            {success && <div className="manfiet-alert manfiet-alert-success" style={{ marginBottom: '24px', borderRadius: '8px' }}>{success}</div>}

            {/* TAB NAVIGATION BAR */}
            <div style={{ display: 'flex', gap: '8px', borderBottom: '2px solid #e2e8f0', paddingBottom: '12px', marginBottom: '24px', flexWrap: 'wrap' }}>
                {tabs.map((tab) => {
                    const isActive = activeTab === tab.id;
                    const TabIcon = tab.Icon;
                    return (
                        <button
                            key={tab.id}
                            type="button"
                            onClick={() => setActiveTab(tab.id)}
                            style={{
                                display: 'flex',
                                alignItems: 'center',
                                gap: '8px',
                                padding: '10px 18px',
                                borderRadius: '8px',
                                border: 'none',
                                background: isActive ? '#2563eb' : '#f1f5f9',
                                color: isActive ? '#ffffff' : '#475569',
                                fontWeight: isActive ? '700' : '600',
                                fontSize: '14px',
                                cursor: 'pointer',
                                transition: 'all 0.2s ease',
                                boxShadow: isActive ? '0 4px 12px rgba(37, 99, 235, 0.25)' : 'none',
                            }}
                        >
                            <TabIcon size={16} color={isActive ? '#ffffff' : '#475569'} />
                            <span>{tab.label}</span>
                        </button>
                    );
                })}
            </div>

            {/* TAB 1: GENERAL & BUDGETS */}
            {activeTab === 'general' && (
                <form onSubmit={handleSave} style={{ display: 'flex', flexDirection: 'column', gap: '28px' }}>
                    <div className="manfiet-card" style={{ padding: '30px' }}>
                        <div style={{ display: 'flex', alignItems: 'center', gap: '10px', marginBottom: '8px', borderBottom: '1px solid #e2e8f0', paddingBottom: '12px' }}>
                            <IconGeneral size={20} color="#2563eb" />
                            <h3 className="manfiet-card-title" style={{ margin: 0, fontSize: '18px', fontWeight: '700' }}>{__('General Configuration', 'manfi-expense-tracker')}</h3>
                        </div>
                        <p style={{ margin: '0 0 20px 0', fontSize: '13px', color: '#64748b' }}>
                            {__('Adjust primary currency defaults, table pagination counts, and CSV/Excel backup fields.', 'manfi-expense-tracker')}
                        </p>

                        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: '24px' }}>
                            <div>
                                <label className="manfiet-label" style={{ fontWeight: '600', display: 'block', marginBottom: '6px' }}>
                                    {__('Plugin Currency', 'manfi-expense-tracker')}
                                </label>
                                <p style={{ margin: '0 0 8px 0', fontSize: '12px', color: '#94a3b8' }}>
                                    {__('Global currency code used across entries, dashboards, and generated invoices.', 'manfi-expense-tracker')}
                                </p>
                                <select
                                    className="manfiet-input"
                                    value={settings.currency}
                                    onChange={(e) => handleChange('currency', e.target.value)}
                                    style={{ width: '100%', height: '40px', borderRadius: '6px' }}
                                >
                                    <option value="USD">{__('USD ($)', 'manfi-expense-tracker')}</option>
                                    <option value="EUR">{__('EUR (€)', 'manfi-expense-tracker')}</option>
                                    <option value="GBP">{__('GBP (£)', 'manfi-expense-tracker')}</option>
                                    <option value="INR">{__('INR (₹)', 'manfi-expense-tracker')}</option>
                                    <option value="BDT">{__('BDT (৳)', 'manfi-expense-tracker')}</option>
                                    <option value="CAD">{__('CAD (C$)', 'manfi-expense-tracker')}</option>
                                    <option value="AUD">{__('AUD (A$)', 'manfi-expense-tracker')}</option>
                                    <option value="JPY">{__('JPY (¥)', 'manfi-expense-tracker')}</option>
                                    <option value="CNY">{__('CNY (¥)', 'manfi-expense-tracker')}</option>
                                </select>
                            </div>

                            <div>
                                <label className="manfiet-label" style={{ fontWeight: '600', display: 'block', marginBottom: '6px' }}>
                                    {__('Expenses Per Page', 'manfi-expense-tracker')}
                                </label>
                                <p style={{ margin: '0 0 8px 0', fontSize: '12px', color: '#94a3b8' }}>
                                    {__('Default pagination limit for listings, budgets, and dashboard lists.', 'manfi-expense-tracker')}
                                </p>
                                <input
                                    type="number"
                                    className="manfiet-input"
                                    value={settings.expenses_per_page}
                                    onChange={(e) => handleChange('expenses_per_page', e.target.value)}
                                    min="1"
                                    max="500"
                                    style={{ width: '100%', borderRadius: '6px' }}
                                />
                            </div>

                            <div>
                                <label className="manfiet-label" style={{ fontWeight: '600', display: 'block', marginBottom: '6px' }}>
                                    {__('Missing User Label (Export)', 'manfi-expense-tracker')}
                                </label>
                                <p style={{ margin: '0 0 8px 0', fontSize: '12px', color: '#94a3b8' }}>
                                    {__('Fallback name displayed in exports if the linked user account has been deleted.', 'manfi-expense-tracker')}
                                </p>
                                <input
                                    type="text"
                                    className="manfiet-input"
                                    value={settings.export_unknown_user_label}
                                    onChange={(e) => handleChange('export_unknown_user_label', e.target.value)}
                                    style={{ width: '100%', borderRadius: '6px' }}
                                />
                            </div>
                        </div>
                    </div>

                    <div className="manfiet-card" style={{ padding: '30px' }}>
                        <div style={{ display: 'flex', alignItems: 'center', gap: '10px', marginBottom: '8px', borderBottom: '1px solid #e2e8f0', paddingBottom: '12px' }}>
                            <IconBudget size={20} color="#2563eb" />
                            <h3 className="manfiet-card-title" style={{ margin: 0, fontSize: '18px', fontWeight: '700' }}>{__('Budget Alarm Thresholds', 'manfi-expense-tracker')}</h3>
                        </div>
                        <p style={{ margin: '0 0 20px 0', fontSize: '13px', color: '#64748b' }}>
                            {__('Set default ceiling targets. Automatic admin warnings and email notifications will trigger when a user transcends these limits.', 'manfi-expense-tracker')}
                        </p>

                        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: '24px' }}>
                            <div style={{ background: '#f8fafc', padding: '18px', borderRadius: '8px', border: '1px solid #e2e8f0' }}>
                                <label className="manfiet-label" style={{ fontWeight: '600', display: 'block', marginBottom: '6px', color: '#0f172a' }}>
                                    {__('Default Monthly Budget Limit', 'manfi-expense-tracker')}
                                </label>
                                <p style={{ margin: '0 0 12px 0', fontSize: '11px', color: '#94a3b8', lineHeight: '1.4' }}>
                                    {__('Default monthly limit allocated per user account.', 'manfi-expense-tracker')}
                                </p>
                                <div style={{ position: 'relative' }}>
                                    <span style={{ position: 'absolute', left: '12px', top: '10px', color: '#64748b', fontWeight: 'bold' }}>{currentSymbol}</span>
                                    <input
                                        type="number"
                                        className="manfiet-input"
                                        value={settings.default_budget}
                                        onChange={(e) => handleChange('default_budget', e.target.value)}
                                        min="0"
                                        style={{ width: '100%', paddingLeft: '30px', borderRadius: '6px' }}
                                    />
                                </div>
                            </div>

                            <div style={{ background: '#f8fafc', padding: '18px', borderRadius: '8px', border: '1px solid #e2e8f0' }}>
                                <label className="manfiet-label" style={{ fontWeight: '600', display: 'block', marginBottom: '6px', color: '#0f172a' }}>
                                    {__('Default Weekly Budget Limit', 'manfi-expense-tracker')}
                                </label>
                                <p style={{ margin: '0 0 12px 0', fontSize: '11px', color: '#94a3b8', lineHeight: '1.4' }}>
                                    {__('Default weekly limit allocated per user account.', 'manfi-expense-tracker')}
                                </p>
                                <div style={{ position: 'relative' }}>
                                    <span style={{ position: 'absolute', left: '12px', top: '10px', color: '#64748b', fontWeight: 'bold' }}>{currentSymbol}</span>
                                    <input
                                        type="number"
                                        className="manfiet-input"
                                        value={settings.default_weekly_budget}
                                        onChange={(e) => handleChange('default_weekly_budget', e.target.value)}
                                        min="0"
                                        style={{ width: '100%', paddingLeft: '30px', borderRadius: '6px' }}
                                    />
                                </div>
                            </div>

                            <div style={{ background: '#f8fafc', padding: '18px', borderRadius: '8px', border: '1px solid #e2e8f0' }}>
                                <label className="manfiet-label" style={{ fontWeight: '600', display: 'block', marginBottom: '6px', color: '#0f172a' }}>
                                    {__('Default Yearly Budget Limit', 'manfi-expense-tracker')}
                                </label>
                                <p style={{ margin: '0 0 12px 0', fontSize: '11px', color: '#94a3b8', lineHeight: '1.4' }}>
                                    {__('Default yearly limit allocated per user account.', 'manfi-expense-tracker')}
                                </p>
                                <div style={{ position: 'relative' }}>
                                    <span style={{ position: 'absolute', left: '12px', top: '10px', color: '#64748b', fontWeight: 'bold' }}>{currentSymbol}</span>
                                    <input
                                        type="number"
                                        className="manfiet-input"
                                        value={settings.default_yearly_budget}
                                        onChange={(e) => handleChange('default_yearly_budget', e.target.value)}
                                        min="0"
                                        style={{ width: '100%', paddingLeft: '30px', borderRadius: '6px' }}
                                    />
                                </div>
                            </div>
                        </div>
                    </div>

                    <div style={{ display: 'flex', justifyContent: 'flex-start' }}>
                        <button
                            type="submit"
                            className="manfiet-button manfiet-button-primary"
                            disabled={saving}
                            style={{ padding: '14px 44px', fontSize: '15px', fontWeight: '700', borderRadius: '8px', cursor: 'pointer', transition: 'all 0.2s ease', boxShadow: '0 4px 12px rgba(37, 99, 235, 0.2)' }}
                        >
                            {saving ? __('Saving Configurations...', 'manfi-expense-tracker') : __('Save General Settings', 'manfi-expense-tracker')}
                        </button>
                    </div>
                </form>
            )}

            {/* TAB 2: MODULES & BUILDERS */}
            {activeTab === 'modules' && (
                <form onSubmit={handleSave} style={{ display: 'flex', flexDirection: 'column', gap: '28px' }}>
                    <div className="manfiet-card" style={{ padding: '30px' }}>
                        <div style={{ display: 'flex', alignItems: 'center', gap: '10px', marginBottom: '8px', borderBottom: '1px solid #e2e8f0', paddingBottom: '12px' }}>
                            <IconModules size={20} color="#2563eb" />
                            <h3 className="manfiet-card-title" style={{ margin: 0, fontSize: '18px', fontWeight: '700' }}>{__('Active Modules & Integrations', 'manfi-expense-tracker')}</h3>
                        </div>
                        <p style={{ margin: '0 0 20px 0', fontSize: '13px', color: '#64748b' }}>
                            {__('Toggle optional sub-systems, invoice editors, and visual block builder capabilities.', 'manfi-expense-tracker')}
                        </p>

                        <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
                            <div style={{ display: 'flex', alignItems: 'flex-start', gap: '12px', background: '#f8fafc', padding: '14px 18px', borderRadius: '8px', border: '1px solid #e2e8f0' }}>
                                <input
                                    type="checkbox"
                                    id="enable_invoice_manager"
                                    checked={settings.enable_invoice_manager === 1}
                                    onChange={(e) => handleChange('enable_invoice_manager', e.target.checked ? 1 : 0)}
                                    style={{ width: '18px', height: '18px', marginTop: '2px', cursor: 'pointer' }}
                                />
                                <div style={{ cursor: 'pointer' }} onClick={() => handleChange('enable_invoice_manager', settings.enable_invoice_manager === 1 ? 0 : 1)}>
                                    <label htmlFor="enable_invoice_manager" style={{ fontWeight: '600', color: '#0f172a', display: 'block', cursor: 'pointer' }}>
                                        {__('Invoice Manager Module (Beta)', 'manfi-expense-tracker')}
                                    </label>
                                    <span style={{ fontSize: '12.5px', color: '#64748b', display: 'block', marginTop: '4px', lineHeight: '1.4' }}>
                                        {__('Exposes customer directories, vendor managers, financial bank ledgers, and enqueues custom PDF builders.', 'manfi-expense-tracker')}
                                    </span>
                                </div>
                            </div>

                            <div style={{ display: 'flex', alignItems: 'flex-start', gap: '12px', background: '#f8fafc', padding: '14px 18px', borderRadius: '8px', border: '1px solid #e2e8f0' }}>
                                <input
                                    type="checkbox"
                                    id="enable_gutenberg_blocks"
                                    checked={settings.enable_gutenberg_blocks === 1}
                                    onChange={(e) => handleChange('enable_gutenberg_blocks', e.target.checked ? 1 : 0)}
                                    style={{ width: '18px', height: '18px', marginTop: '2px', cursor: 'pointer' }}
                                />
                                <div style={{ cursor: 'pointer' }} onClick={() => handleChange('enable_gutenberg_blocks', settings.enable_gutenberg_blocks === 1 ? 0 : 1)}>
                                    <label htmlFor="enable_gutenberg_blocks" style={{ fontWeight: '600', color: '#0f172a', display: 'block', cursor: 'pointer' }}>
                                        {__('WordPress Gutenberg Block Registrar', 'manfi-expense-tracker')}
                                    </label>
                                    <span style={{ fontSize: '12.5px', color: '#64748b', display: 'block', marginTop: '4px', lineHeight: '1.4' }}>
                                        {__('Enables block builder widgets. Exposes native page blocks to render dashboards and statistics grids on front-end layouts.', 'manfi-expense-tracker')}
                                    </span>
                                </div>
                            </div>

                            <div style={{ display: 'flex', alignItems: 'flex-start', gap: '12px', background: '#f8fafc', padding: '14px 18px', borderRadius: '8px', border: '1px solid #e2e8f0' }}>
                                <input
                                    type="checkbox"
                                    id="enable_elementor_widgets"
                                    checked={settings.enable_elementor_widgets === 1}
                                    onChange={(e) => handleChange('enable_elementor_widgets', e.target.checked ? 1 : 0)}
                                    style={{ width: '18px', height: '18px', marginTop: '2px', cursor: 'pointer' }}
                                />
                                <div style={{ cursor: 'pointer' }} onClick={() => handleChange('enable_elementor_widgets', settings.enable_elementor_widgets === 1 ? 0 : 1)}>
                                    <label htmlFor="enable_elementor_widgets" style={{ fontWeight: '600', color: '#0f172a', display: 'block', cursor: 'pointer' }}>
                                        {__('Elementor Addon Widgets', 'manfi-expense-tracker')}
                                    </label>
                                    <span style={{ fontSize: '12.5px', color: '#64748b', display: 'block', marginTop: '4px', lineHeight: '1.4' }}>
                                        {__('Registers Elementor drag-and-drop templates. (Only operational when Elementor core is installed).', 'manfi-expense-tracker')}
                                    </span>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div className="manfiet-card" style={{ padding: '30px' }}>
                        <div style={{ display: 'flex', alignItems: 'center', gap: '10px', marginBottom: '8px', borderBottom: '1px solid #e2e8f0', paddingBottom: '12px' }}>
                            <IconGeneral size={20} color="#2563eb" />
                            <h3 className="manfiet-card-title" style={{ margin: 0, fontSize: '18px', fontWeight: '700' }}>{__('Invoice Overdue Late Fee & Terms', 'manfi-expense-tracker')}</h3>
                        </div>
                        <p style={{ margin: '0 0 20px 0', fontSize: '13px', color: '#64748b' }}>
                            {__('Configure automatic overdue fine/due fee calculations and standard Terms & Conditions templates for generated invoices.', 'manfi-expense-tracker')}
                        </p>

                        <div style={{ display: 'flex', flexDirection: 'column', gap: '20px' }}>
                            <div style={{ display: 'flex', alignItems: 'flex-start', gap: '12px', background: '#f8fafc', padding: '14px 18px', borderRadius: '8px', border: '1px solid #e2e8f0' }}>
                                <input
                                    type="checkbox"
                                    id="invoice_late_fee_enabled"
                                    checked={settings.invoice_late_fee_enabled === 1}
                                    onChange={(e) => handleChange('invoice_late_fee_enabled', e.target.checked ? 1 : 0)}
                                    style={{ width: '18px', height: '18px', marginTop: '2px', cursor: 'pointer' }}
                                />
                                <div style={{ cursor: 'pointer' }} onClick={() => handleChange('invoice_late_fee_enabled', settings.invoice_late_fee_enabled === 1 ? 0 : 1)}>
                                    <label htmlFor="invoice_late_fee_enabled" style={{ fontWeight: '600', color: '#0f172a', display: 'block', cursor: 'pointer' }}>
                                        {__('Enable Automatic Overdue Late Due Fee Calculation', 'manfi-expense-tracker')}
                                    </label>
                                    <span style={{ fontSize: '12.5px', color: '#64748b', display: 'block', marginTop: '4px', lineHeight: '1.4' }}>
                                        {__('Automatically computes and attaches late fine adjustments when carrying forward past due balances from overdue invoices.', 'manfi-expense-tracker')}
                                    </span>
                                </div>
                            </div>

                            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(240px, 1fr))', gap: '16px' }}>
                                <div>
                                    <label htmlFor="invoice_late_fee_type" style={{ fontWeight: '600', color: '#0f172a', display: 'block', marginBottom: '6px', fontSize: '13.5px' }}>
                                        {__('Late Fee Calculation Mode', 'manfi-expense-tracker')}
                                    </label>
                                    <select
                                        id="invoice_late_fee_type"
                                        className="manfiet-input"
                                        value={settings.invoice_late_fee_type || 'percentage'}
                                        onChange={(e) => handleChange('invoice_late_fee_type', e.target.value)}
                                    >
                                        <option value="percentage">{__('Percentage (%) on Overdue Balance', 'manfi-expense-tracker')}</option>
                                        <option value="flat">{__('Fixed Flat Amount', 'manfi-expense-tracker')}</option>
                                    </select>
                                </div>

                                <div>
                                    <label htmlFor="invoice_late_fee_pct" style={{ fontWeight: '600', color: '#0f172a', display: 'block', marginBottom: '6px', fontSize: '13.5px' }}>
                                        {settings.invoice_late_fee_type === 'flat' ? __('Default Flat Late Fee Amount', 'manfi-expense-tracker') : __('Default Overdue Late Fee Percentage (%)', 'manfi-expense-tracker')}
                                    </label>
                                    <input
                                        type="number"
                                        step="0.1"
                                        min="0"
                                        id="invoice_late_fee_pct"
                                        className="manfiet-input"
                                        value={settings.invoice_late_fee_pct ?? 5.0}
                                        onChange={(e) => handleChange('invoice_late_fee_pct', parseFloat(e.target.value) || 0)}
                                        placeholder="5.0"
                                    />
                                    <p className="description" style={{ margin: '4px 0 0 0', fontSize: '12px', color: '#64748b' }}>
                                        {settings.invoice_late_fee_type === 'flat' ? __('Flat fine amount added when overdue.', 'manfi-expense-tracker') : __('e.g. 5% applied automatically to unpaid balances past their due date.', 'manfi-expense-tracker')}
                                    </p>
                                </div>
                            </div>

                            <div>
                                <label htmlFor="invoice_default_terms" style={{ fontWeight: '600', color: '#0f172a', display: 'block', marginBottom: '6px', fontSize: '13.5px' }}>
                                    {__('Default Terms & Conditions / Notes Template', 'manfi-expense-tracker')}
                                </label>
                                <textarea
                                    id="invoice_default_terms"
                                    className="manfiet-input"
                                    rows="4"
                                    value={settings.invoice_default_terms || ''}
                                    onChange={(e) => handleChange('invoice_default_terms', e.target.value)}
                                    placeholder="Enter default invoice terms & conditions..."
                                />
                                <p className="description" style={{ margin: '4px 0 0 0', fontSize: '12px', color: '#64748b' }}>
                                    {__('Available tags: {due_date} = Due Date, {late_fee} = Late fee rate, {invoice_no} = Invoice number.', 'manfi-expense-tracker')}
                                </p>
                            </div>
                        </div>
                    </div>

                    <div style={{ display: 'flex', justifyContent: 'flex-start' }}>
                        <button
                            type="submit"
                            className="manfiet-button manfiet-button-primary"
                            disabled={saving}
                            style={{ padding: '14px 44px', fontSize: '15px', fontWeight: '700', borderRadius: '8px', cursor: 'pointer', transition: 'all 0.2s ease', boxShadow: '0 4px 12px rgba(37, 99, 235, 0.2)' }}
                        >
                            {saving ? __('Saving Configurations...', 'manfi-expense-tracker') : __('Save Module Settings', 'manfi-expense-tracker')}
                        </button>
                    </div>
                </form>
            )}

            {/* TAB 3: GOOGLE SHEETS SYNC */}
            {activeTab === 'gsheets' && (
                <div className="manfiet-card" style={{ borderLeft: '4px solid #10b981', padding: '30px 30px 30px 24px' }}>
                    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '12px' }}>
                        <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
                            <IconGSheets size={20} color="#10b981" />
                            <h3 className="manfiet-card-title" style={{ margin: 0, fontSize: '18px', fontWeight: '700', color: '#0f172a' }}>
                                {__('Google Sheets & Live Data Sync', 'manfi-expense-tracker')}
                            </h3>
                        </div>
                        <button
                            type="button"
                            className="manfiet-button manfiet-button-secondary"
                            onClick={handleRegenerateToken}
                            disabled={gsheetsSaving}
                            style={{ fontSize: '12px', padding: '6px 14px', display: 'flex', alignItems: 'center', gap: '6px' }}
                        >
                            <IconRefresh size={12} color="currentColor" />
                            <span>{__('Regenerate Token', 'manfi-expense-tracker')}</span>
                        </button>
                    </div>

                    <p style={{ margin: '0 0 20px 0', fontSize: '13px', color: '#64748b', lineHeight: '1.6' }}>
                        {__('Sync expenses and invoices directly with Google Sheets. Paste pre-formatted =IMPORTDATA() formulas into any Google Sheet cell for live CSV feed sync, or configure a Webhook for automated background pushes.', 'manfi-expense-tracker')}
                    </p>

                    {/* LIVE IMPORTDATA FORMULAS */}
                    <div className="manfiet-card manfiet-card-inset" style={{ background: '#f8fafc', border: '1px solid #e2e8f0', padding: '16px', borderRadius: '8px', marginBottom: '20px' }}>
                        <h4 style={{ margin: '0 0 12px 0', fontSize: '14px', fontWeight: '600', color: '#1e293b', display: 'flex', alignItems: 'center', gap: '8px' }}>
                            <IconGSheets size={16} color="#10b981" />
                            <span>{__('Live Google Sheets =IMPORTDATA() Formulas', 'manfi-expense-tracker')}</span>
                        </h4>

                        <div style={{ display: 'grid', gap: '14px' }}>
                            <div>
                                <label className="manfiet-label" style={{ fontSize: '12px', color: '#475569', fontWeight: '600' }}>
                                    {__('Expenses Live Feed Formula:', 'manfi-expense-tracker')}
                                </label>
                                <div style={{ display: 'flex', gap: '8px', marginTop: '4px' }}>
                                    <input
                                        type="text"
                                        readOnly
                                        className="manfiet-input"
                                        value={gsheets.expenses_formula}
                                        style={{ fontFamily: 'monospace', fontSize: '12px', background: '#ffffff' }}
                                    />
                                    <button
                                        type="button"
                                        className="manfiet-button manfiet-button-secondary"
                                        onClick={() => handleCopyFormula(gsheets.expenses_formula, 'expenses')}
                                        style={{ whiteSpace: 'nowrap', fontSize: '12px' }}
                                    >
                                        {copiedKey === 'expenses' ? __('Copied! ✓', 'manfi-expense-tracker') : __('Copy Formula', 'manfi-expense-tracker')}
                                    </button>
                                </div>
                            </div>

                            <div>
                                <label className="manfiet-label" style={{ fontSize: '12px', color: '#475569', fontWeight: '600' }}>
                                    {__('Invoices Live Feed Formula:', 'manfi-expense-tracker')}
                                </label>
                                <div style={{ display: 'flex', gap: '8px', marginTop: '4px' }}>
                                    <input
                                        type="text"
                                        readOnly
                                        className="manfiet-input"
                                        value={gsheets.invoices_formula}
                                        style={{ fontFamily: 'monospace', fontSize: '12px', background: '#ffffff' }}
                                    />
                                    <button
                                        type="button"
                                        className="manfiet-button manfiet-button-secondary"
                                        onClick={() => handleCopyFormula(gsheets.invoices_formula, 'invoices')}
                                        style={{ whiteSpace: 'nowrap', fontSize: '12px' }}
                                    >
                                        {copiedKey === 'invoices' ? __('Copied! ✓', 'manfi-expense-tracker') : __('Copy Formula', 'manfi-expense-tracker')}
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>

                    {/* WEBHOOK PUSH CONFIGURATION */}
                    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: '20px', marginBottom: '20px' }}>
                        <div>
                            <label className="manfiet-label" style={{ fontWeight: '600', display: 'block', marginBottom: '6px' }}>
                                {__('Google Apps Script / Webhook URL', 'manfi-expense-tracker')}
                            </label>
                            <input
                                type="url"
                                className="manfiet-input"
                                value={gsheets.webhook_url}
                                onChange={(e) => setGsheets((prev) => ({ ...prev, webhook_url: e.target.value }))}
                                style={{ width: '100%', borderRadius: '6px' }}
                                placeholder="https://script.google.com/macros/s/.../exec"
                            />
                        </div>

                        <div style={{ display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
                            <label style={{ display: 'flex', alignItems: 'center', gap: '10px', cursor: 'pointer', fontWeight: '600', color: '#1e293b' }}>
                                <input
                                    type="checkbox"
                                    checked={gsheets.auto_sync}
                                    onChange={(e) => setGsheets((prev) => ({ ...prev, auto_sync: e.target.checked }))}
                                />
                                {__('Enable Automated Real-Time Background Webhook Sync', 'manfi-expense-tracker')}
                            </label>
                            <p style={{ margin: '4px 0 0 28px', fontSize: '12px', color: '#94a3b8' }}>
                                {__('Fires an instant background payload on expense/invoice create, edit, or delete events.', 'manfi-expense-tracker')}
                            </p>
                        </div>
                    </div>

                    <div style={{ display: 'flex', gap: '12px', alignItems: 'center' }}>
                        <button
                            type="button"
                            className="manfiet-button manfiet-button-primary"
                            onClick={handleSaveGsheets}
                            disabled={gsheetsSaving}
                        >
                            {gsheetsSaving ? __('Saving Google Sync...', 'manfi-expense-tracker') : __('Save Sync Settings', 'manfi-expense-tracker')}
                        </button>

                        <button
                            type="button"
                            className="manfiet-button manfiet-button-secondary"
                            onClick={handleBulkSync}
                            disabled={gsheetsSaving || !gsheets.webhook_url}
                            style={{ display: 'flex', alignItems: 'center', gap: '6px' }}
                            title={!gsheets.webhook_url ? __('Configure a Webhook URL above to trigger bulk sync', 'manfi-expense-tracker') : ''}
                        >
                            <IconZap size={14} color="currentColor" />
                            <span>{__('Sync All Data Now', 'manfi-expense-tracker')}</span>
                        </button>
                    </div>
                </div>
            )}

            {/* TAB 4: EMAIL ALERTS */}
            {activeTab === 'email' && (
                <form onSubmit={handleSave} style={{ display: 'flex', flexDirection: 'column', gap: '28px' }}>
                    <div className="manfiet-card" style={{ padding: '30px' }}>
                        <div style={{ display: 'flex', alignItems: 'center', gap: '10px', marginBottom: '8px', borderBottom: '1px solid #e2e8f0', paddingBottom: '12px' }}>
                            <IconEmail size={20} color="#2563eb" />
                            <h3 className="manfiet-card-title" style={{ margin: 0, fontSize: '18px', fontWeight: '700' }}>{__('Email Sender Configurations', 'manfi-expense-tracker')}</h3>
                        </div>
                        <p style={{ margin: '0 0 20px 0', fontSize: '13px', color: '#64748b' }}>
                            {__('Configure outgoing mail metadata. These credentials stamp alert reports and threshold warning emails dispatched by the plugin.', 'manfi-expense-tracker')}
                        </p>

                        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: '24px' }}>
                            <div>
                                <label className="manfiet-label" style={{ fontWeight: '600', display: 'block', marginBottom: '6px' }}>
                                    {__('Sender Email Address', 'manfi-expense-tracker')}
                                </label>
                                <p style={{ margin: '0 0 8px 0', fontSize: '12px', color: '#94a3b8' }}>
                                    {__('The "From" email address attached to outgoing budget system alerts.', 'manfi-expense-tracker')}
                                </p>
                                <input
                                    type="email"
                                    className="manfiet-input"
                                    value={settings.email_sender_address}
                                    onChange={(e) => handleChange('email_sender_address', e.target.value)}
                                    style={{ width: '100%', borderRadius: '6px' }}
                                    placeholder="e.g. alerts@yoursite.com"
                                />
                            </div>

                            <div>
                                <label className="manfiet-label" style={{ fontWeight: '600', display: 'block', marginBottom: '6px' }}>
                                    {__('Sender Display Name', 'manfi-expense-tracker')}
                                </label>
                                <p style={{ margin: '0 0 8px 0', fontSize: '12px', color: '#94a3b8' }}>
                                    {__('Friendly label showing in inbox clients (e.g., "Finance Alerts Hub").', 'manfi-expense-tracker')}
                                </p>
                                <input
                                    type="text"
                                    className="manfiet-input"
                                    value={settings.email_sender_name}
                                    onChange={(e) => handleChange('email_sender_name', e.target.value)}
                                    style={{ width: '100%', borderRadius: '6px' }}
                                    placeholder="e.g. Manfi Expense Alerts"
                                />
                            </div>
                        </div>
                    </div>

                    <div style={{ display: 'flex', justifyContent: 'flex-start' }}>
                        <button
                            type="submit"
                            className="manfiet-button manfiet-button-primary"
                            disabled={saving}
                            style={{ padding: '14px 44px', fontSize: '15px', fontWeight: '700', borderRadius: '8px', cursor: 'pointer', transition: 'all 0.2s ease', boxShadow: '0 4px 12px rgba(37, 99, 235, 0.2)' }}
                        >
                            {saving ? __('Saving Configurations...', 'manfi-expense-tracker') : __('Save Email Settings', 'manfi-expense-tracker')}
                        </button>
                    </div>
                </form>
            )}

            {/* TAB 5: ADVANCED & ROLLBACK */}
            {activeTab === 'advanced' && (
                <div className="manfiet-card" style={{ borderLeft: '4px solid #d63638', padding: '30px 30px 30px 24px' }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: '10px', marginBottom: '8px' }}>
                        <IconAdvanced size={20} color="#d63638" />
                        <h3 className="manfiet-card-title" style={{ color: '#d63638', margin: 0, fontSize: '18px', fontWeight: '700' }}>{__('Danger Zone — Version Rollback', 'manfi-expense-tracker')}</h3>
                    </div>
                    <p style={{ fontSize: '13px', margin: '0 0 20px 0', color: '#64748b', lineHeight: '1.5' }}>
                        {__('Experience glitches on the current build? Instantly downgrade directory structures back to a previous official stable release. Overwrites active local files.', 'manfi-expense-tracker')}
                    </p>

                    <form
                        method="post"
                        action={appData.rollbackUrl || ''}
                        onSubmit={(e) => {
                            if (!confirm(__('Warning: This will overwrite your active plugin files with the selected version. Are you sure you want to proceed?', 'manfi-expense-tracker'))) {
                                e.preventDefault();
                            }
                        }}
                        style={{ display: 'flex', alignItems: 'center', gap: '14px', flexWrap: 'wrap' }}
                    >
                        <input type="hidden" name="action" value="manfiet_version_rollback" />
                        <input type="hidden" name="_wpnonce" value={appData.rollbackNonce || ''} />

                        <select
                            name="rollback_version"
                            required
                            className="manfiet-input"
                            value={rollbackVersion}
                            onChange={(e) => setRollbackVersion(e.target.value)}
                            style={{ maxWidth: '280px', height: '40px', borderRadius: '6px' }}
                        >
                            <option value="">{__('— select version —', 'manfi-expense-tracker')}</option>
                            <option value="1.0.7">{__('Version 1.0.7 (Stable)', 'manfi-expense-tracker')}</option>
                            <option value="1.0.6">{__('Version 1.0.6', 'manfi-expense-tracker')}</option>
                            <option value="1.0.5">{__('Version 1.0.5', 'manfi-expense-tracker')}</option>
                            <option value="1.0.4">{__('Version 1.0.4', 'manfi-expense-tracker')}</option>
                            <option value="1.0.3">{__('Version 1.0.3', 'manfi-expense-tracker')}</option>
                            <option value="1.0.2">{__('Version 1.0.2', 'manfi-expense-tracker')}</option>
                            <option value="1.0.1">{__('Version 1.0.1', 'manfi-expense-tracker')}</option>
                            <option value="1.0.0">{__('Version 1.0.0', 'manfi-expense-tracker')}</option>
                        </select>

                        <button
                            type="submit"
                            className="manfiet-button"
                            style={{
                                height: '40px',
                                lineHeight: '40px',
                                background: '#d63638',
                                color: '#ffffff',
                                border: 'none',
                                fontWeight: '700',
                                padding: '0 28px',
                                borderRadius: '6px',
                                cursor: 'pointer',
                                boxShadow: '0 4px 12px rgba(214, 54, 56, 0.2)',
                                transition: 'background 0.2s'
                            }}
                        >
                            {__('Rollback Version', 'manfi-expense-tracker')}
                        </button>
                    </form>
                </div>
            )}
        </div>
    );
};

export default SettingsManager;
