(() => {
    const { useState, useEffect } = React;

    const TaxCalculator = () => {
    const [jurisdiction, setJurisdiction] = useState('mainland'); // 'mainland' | 'freezone'
    const [revenue, setRevenue] = useState(1000000);
    const [expenses, setExpenses] = useState(600000);
    const [nonQualifyingRevenue, setNonQualifyingRevenue] = useState(50000);
    const [sbrElected, setSbrElected] = useState(true);
    const [customVat, setCustomVat] = useState(false);
    const [localSales, setLocalSales] = useState(700000);
    const [vatExpenses, setVatExpenses] = useState(360000);

    // Parse input states to numbers for calculation safety (handles empty strings while typing)
    const revNum = Number(revenue) || 0;
    const expNum = Number(expenses) || 0;
    const nonQualNum = Number(nonQualifyingRevenue) || 0;
    const localSalesNum = Number(localSales) || 0;
    const vatExpensesNum = Number(vatExpenses) || 0;

    // Sync custom VAT fields if auto-calculation is on
    useEffect(() => {
        if (!customVat) {
            setLocalSales(Math.round(revNum * 0.7));
            setVatExpenses(Math.round(expNum * 0.6));
        }
    }, [revenue, expenses, customVat]);

    // Financial core calculations
    const netProfit = revNum - expNum;
    const profitMargin = revNum > 0 ? ((netProfit / revNum) * 100).toFixed(1) : '0.0';

    // VAT Calculations
    const finalLocalSales = customVat ? localSalesNum : Math.round(revNum * 0.7);
    const finalVatExpenses = customVat ? vatExpensesNum : Math.round(expNum * 0.6);

    const vatLocalSales = Math.max(0, finalLocalSales);
    const vatExportSales = Math.max(0, revNum - vatLocalSales);
    const taxableSupplies = vatLocalSales + vatExportSales; // Exports are zero-rated, but part of taxable supplies
    const outputVat = Math.round(vatLocalSales * 0.05);

    const eligibleExpenses = Math.max(0, finalVatExpenses);
    const inputVat = Math.round(eligibleExpenses * 0.05);
    const netVat = outputVat - inputVat;

    let vatStatus = 'Below Threshold';
    let vatStatusClass = 'badge-success';
    let vatStatusDesc = 'Taxable supplies are below the voluntary registration threshold. No VAT registration or filing is required.';

    if (taxableSupplies >= 375000) {
        vatStatus = 'Mandatory Registration';
        vatStatusClass = 'badge-danger';
        vatStatusDesc = 'Your taxable supplies exceed AED 375,000. You must register for VAT with the FTA and submit regular filings.';
    } else if (taxableSupplies >= 187500) {
        vatStatus = 'Voluntary Registration';
        vatStatusClass = 'badge-warning';
        vatStatusDesc = 'Your taxable supplies exceed AED 187,500. You are eligible for voluntary registration, allowing you to reclaim input tax.';
    }

    // Corporate Tax Calculations
    let ctDue = 0;
    let ctStatusText = '';
    let ctExplanation = '';
    let qualProfit = 0;
    let nonQualProfit = 0;
    let deMinimisLimit = 0;
    let deMinimisBreached = false;

    const formatAED = (value) => {
        return 'AED ' + Math.round(value).toLocaleString();
    };

    if (jurisdiction === 'mainland') {
        const sbrEligible = revNum > 0 && revNum <= 3000000;
        
        if (sbrEligible && sbrElected) {
            ctDue = 0;
            ctStatusText = '0% Rate (SBR)';
            ctExplanation = `Small Business Relief (SBR) is elected and active because gross revenue is below AED 3,000,000. Your corporate tax is AED 0 for the tax period.`;
        } else {
            if (netProfit <= 0) {
                ctDue = 0;
                ctStatusText = 'No Taxable Profit';
                ctExplanation = `The company reported an accounting loss of ${formatAED(Math.abs(netProfit))}. No corporate tax is due.`;
            } else if (netProfit <= 375000) {
                ctDue = 0;
                ctStatusText = '0% under 375k Slab';
                ctExplanation = `Net taxable profit is within the 0% tax slab (under AED 375,000). Tax liability is AED 0.`;
            } else {
                ctDue = Math.round((netProfit - 375000) * 0.09);
                ctStatusText = '9% Standard Rate';
                ctExplanation = `Net profit exceeds the AED 375,000 exemption limit. The standard rate of 9% applies strictly on the excess profit. Formula: (${formatAED(netProfit)} - AED 375,000) × 9% = ${formatAED(ctDue)}.`;
            }
        }
    } else {
        // Free Zone calculations
        deMinimisLimit = Math.min(Math.round(revNum * 0.05), 5000000);
        deMinimisBreached = nonQualNum > deMinimisLimit;

        if (deMinimisBreached) {
            if (netProfit <= 0) {
                ctDue = 0;
                ctExplanation = `De Minimis limit is breached. Entire profit is subject to standard rates, but net profit is below 0. Tax is AED 0.`;
            } else if (netProfit <= 375000) {
                ctDue = 0;
                ctExplanation = `De Minimis limit is breached. Entire profit is subject to standard mainland rates, but net profit is under AED 375,000. Tax is AED 0.`;
            } else {
                ctDue = Math.round((netProfit - 375000) * 0.09);
                ctExplanation = `CRITICAL BREACH: Non-qualifying revenue exceeds the De Minimis threshold (5% of revenue or AED 5M). The entity loses its Qualifying Free Zone status. The ENTIRE net profit of ${formatAED(netProfit)} is taxed at mainland standard rates: (Profit - 375,000) × 9% = ${formatAED(ctDue)}.`;
            }
            ctStatusText = 'Breached - 9% Standard';
            qualProfit = 0;
            nonQualProfit = netProfit;
        } else {
            if (netProfit <= 0) {
                ctDue = 0;
                ctStatusText = 'No Profit';
                ctExplanation = `Freezone entity is compliant with De Minimis, but net accounting profit is zero or negative. No tax due.`;
                qualProfit = 0;
                nonQualProfit = 0;
            } else {
                const nonQualRatio = revNum > 0 ? nonQualNum / revNum : 0;
                nonQualProfit = Math.round(netProfit * nonQualRatio);
                qualProfit = Math.max(0, netProfit - nonQualProfit);

                ctDue = Math.round(nonQualProfit * 0.09);
                ctStatusText = 'QFZP 0% / 9% split';
                ctExplanation = `Freezone De Minimis check passed. Qualifying Profit of ${formatAED(qualProfit)} is taxed at 0%. Non-Qualifying Profit of ${formatAED(nonQualProfit)} is taxed at a flat 9% rate without the 375,000 exemption threshold. Formula: ${formatAED(nonQualProfit)} × 9% = ${formatAED(ctDue)}.`;
            }
        }
    }

    return (
        <section id="calculator" className="calculator-section">
            <div className="container">
                <div className="section-header text-center">
                    <div className="badge">INTERACTIVE DEMO</div>
                    <h2 className="section-title">UAE Tax & Compliance Calculator</h2>
                    <p className="section-desc text-center" style={{ maxWidth: '700px', margin: '0 auto 40px auto' }}>
                        Estimate your company's Corporate Tax and VAT liabilities in seconds. Toggle between Mainland and Free Zone options to see how local tax laws apply to your business.
                    </p>
                </div>

                <div className="calculator-grid">
                    {/* Input Panel */}
                    <div className="calc-card input-panel">
                        <h3 className="calc-panel-title"><i className="fa-solid fa-sliders"></i> Input Parameters</h3>
                        
                        <div className="form-group">
                            <label>Jurisdiction Category</label>
                            <div className="segmented-control">
                                <button 
                                    className={`segment-btn ${jurisdiction === 'mainland' ? 'active' : ''}`}
                                    onClick={() => setJurisdiction('mainland')}
                                >
                                    Mainland Entity
                                </button>
                                <button 
                                    className={`segment-btn ${jurisdiction === 'freezone' ? 'active' : ''}`}
                                    onClick={() => setJurisdiction('freezone')}
                                >
                                    Free Zone (QFZP)
                                </button>
                            </div>
                        </div>

                        <div className="form-group">
                            <label htmlFor="calc-revenue">Annual Gross Revenue (AED)</label>
                            <div className="input-with-currency">
                                <span className="currency-addon">AED</span>
                                <input 
                                    type="number" 
                                    id="calc-revenue"
                                    className="form-control" 
                                    value={revenue}
                                    onChange={(e) => setRevenue(e.target.value === '' ? '' : Math.max(0, parseInt(e.target.value) || 0))}
                                />
                            </div>
                        </div>

                        <div className="form-group">
                            <label htmlFor="calc-expenses">Annual Operating Expenses (AED)</label>
                            <div className="input-with-currency">
                                <span className="currency-addon">AED</span>
                                <input 
                                    type="number" 
                                    id="calc-expenses"
                                    className="form-control" 
                                    value={expenses}
                                    onChange={(e) => setExpenses(e.target.value === '' ? '' : Math.max(0, parseInt(e.target.value) || 0))}
                                />
                            </div>
                        </div>

                        {/* Free Zone Specifics */}
                        {jurisdiction === 'freezone' && (
                            <div className="calc-conditional-group animated fade-in">
                                <div className="form-group">
                                    <div className="label-with-help">
                                        <label htmlFor="calc-nonqual">Non-Qualifying Revenue (AED)</label>
                                        <span className="tooltip-trigger" title="Revenue from transactions with mainland entities or individuals. Must be below 5% of total revenue or AED 5,000,000 to keep tax-free status.">
                                            <i className="fa-solid fa-circle-info"></i>
                                        </span>
                                    </div>
                                    <div className="input-with-currency">
                                        <span className="currency-addon">AED</span>
                                        <input 
                                            type="number" 
                                            id="calc-nonqual"
                                            className="form-control" 
                                            value={nonQualifyingRevenue}
                                            onChange={(e) => setNonQualifyingRevenue(e.target.value === '' ? '' : Math.max(0, parseInt(e.target.value) || 0))}
                                        />
                                    </div>
                                    <div className="help-text">
                                        De Minimis Limit: <span className="font-bold">{formatAED(deMinimisLimit)}</span> (5% of revenue).
                                    </div>
                                </div>
                            </div>
                        )}

                        {/* Mainland Specifics */}
                        {jurisdiction === 'mainland' && revNum > 0 && revNum <= 3000000 && (
                            <div className="calc-conditional-group animated fade-in">
                                <div className="form-group checkbox-group">
                                    <label className="checkbox-label">
                                        <input 
                                            type="checkbox" 
                                            checked={sbrElected}
                                            onChange={(e) => setSbrElected(e.target.checked)}
                                        />
                                        <span className="checkbox-custom"></span>
                                        <div className="checkbox-text-content">
                                            <span className="font-bold">Elect Small Business Relief (SBR)</span>
                                            <span className="checkbox-desc">Reduces your corporate tax to 0% as your revenue is under the AED 3,000,000 threshold.</span>
                                        </div>
                                    </label>
                                </div>
                            </div>
                        )}

                        {/* VAT Customization */}
                        <div className="vat-customizer-toggle">
                            <div className="form-group checkbox-group">
                                <label className="checkbox-label">
                                    <input 
                                        type="checkbox" 
                                        checked={customVat}
                                        onChange={(e) => setCustomVat(e.target.checked)}
                                    />
                                    <span className="checkbox-custom"></span>
                                    <div className="checkbox-text-content">
                                        <span className="font-bold">Customize VAT Estimates</span>
                                        <span className="checkbox-desc">Manually configure local sales and eligible VAT expenses.</span>
                                    </div>
                                </label>
                            </div>
                        </div>

                        {customVat && (
                            <div className="calc-conditional-group animated fade-in">
                                <div className="form-group">
                                    <label htmlFor="calc-local-sales">Local Taxable Sales (AED)</label>
                                    <div className="input-with-currency">
                                        <span className="currency-addon">AED</span>
                                        <input 
                                            type="number" 
                                            id="calc-local-sales"
                                            className="form-control" 
                                            value={localSales}
                                            onChange={(e) => setLocalSales(e.target.value === '' ? '' : Math.max(0, parseInt(e.target.value) || 0))}
                                        />
                                    </div>
                                    <div className="help-text">Standard 5% VAT applies to local sales. Export sales are zero-rated.</div>
                                </div>
                                <div className="form-group">
                                    <label htmlFor="calc-vat-expenses">VAT-Eligible Operating Expenses (AED)</label>
                                    <div className="input-with-currency">
                                        <span className="currency-addon">AED</span>
                                        <input 
                                            type="number" 
                                            id="calc-vat-expenses"
                                            className="form-control" 
                                            value={vatExpenses}
                                            onChange={(e) => setVatExpenses(e.target.value === '' ? '' : Math.max(0, parseInt(e.target.value) || 0))}
                                        />
                                    </div>
                                    <div className="help-text">Expenses with 5% VAT that are eligible for input tax reclaim.</div>
                                </div>
                            </div>
                        )}
                    </div>

                    {/* Results Panel */}
                    <div className="calc-card results-panel">
                        <h3 className="calc-panel-title"><i className="fa-solid fa-chart-pie"></i> Tax Estimate Summary</h3>

                        {/* KPI Cards */}
                        <div className="calc-kpi-grid">
                            <div className="calc-kpi-card">
                                <span className="kpi-label">Net Profit / Margin</span>
                                <span className={`kpi-value ${netProfit >= 0 ? 'text-green' : 'text-red'}`}>
                                    {formatAED(netProfit)}
                                </span>
                                <span className="kpi-meta">{profitMargin}% margin</span>
                            </div>

                            <div className="calc-kpi-card">
                                <span className="kpi-label">Corporate Tax Due</span>
                                <span className={`kpi-value ${ctDue > 0 ? 'text-red' : 'text-primary'}`}>
                                    {formatAED(ctDue)}
                                </span>
                                <span className="kpi-meta">{ctStatusText}</span>
                            </div>

                            <div className="calc-kpi-card">
                                <span className="kpi-label">Estimated VAT Payable</span>
                                <span className={`kpi-value ${netVat >= 0 ? 'text-red' : 'text-green'}`}>
                                    {formatAED(Math.abs(netVat))}
                                </span>
                                <span className="kpi-meta">
                                    {netVat >= 0 ? 'Net Payable to FTA' : 'Net Refundable'}
                                </span>
                            </div>
                        </div>

                        {/* Detailed Calculation Breakdown */}
                        <div className="calc-breakdown">
                            <h4 className="breakdown-title">Step-by-Step Breakdown</h4>
                            
                            <table className="breakdown-table">
                                <thead>
                                    <tr>
                                        <th>Description</th>
                                        <th className="text-right">Amount (AED)</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr>
                                        <td>Annual Revenue</td>
                                        <td className="text-right font-medium">{formatAED(revNum)}</td>
                                    </tr>
                                    <tr>
                                        <td>Annual Operating Expenses</td>
                                        <td className="text-right font-medium">{formatAED(expNum)}</td>
                                    </tr>
                                    <tr className="table-highlight">
                                        <td>Net Accounting Profit</td>
                                        <td className={`text-right font-bold ${netProfit >= 0 ? 'text-green' : 'text-red'}`}>
                                            {formatAED(netProfit)}
                                        </td>
                                    </tr>
                                    
                                    {/* Corporate Tax Rows */}
                                    {jurisdiction === 'freezone' && !deMinimisBreached && (
                                        <React.Fragment>
                                            <tr>
                                                <td><span className="indent">Qualifying Free Zone Profit (0% Tax)</span></td>
                                                <td className="text-right text-gray">{formatAED(qualProfit)}</td>
                                            </tr>
                                            <tr>
                                                <td><span className="indent">Non-Qualifying Profit (9% Tax)</span></td>
                                                <td className="text-right text-gray">{formatAED(nonQualProfit)}</td>
                                            </tr>
                                        </React.Fragment>
                                    )}
                                    <tr className="table-highlight-light">
                                        <td>Corporate Tax Liability</td>
                                        <td className="text-right font-bold text-dark">{formatAED(ctDue)}</td>
                                    </tr>

                                    {/* VAT Rows */}
                                    <tr>
                                        <td>Taxable Supplies (Local + Export Sales)</td>
                                        <td className="text-right text-gray">{formatAED(taxableSupplies)}</td>
                                    </tr>
                                    <tr>
                                        <td>Output VAT (5% on Local Sales)</td>
                                        <td className="text-right text-gray">{formatAED(outputVat)}</td>
                                    </tr>
                                    <tr>
                                        <td>Input VAT (5% on Eligible Expenses)</td>
                                        <td className="text-right text-gray">{formatAED(inputVat)}</td>
                                    </tr>
                                    <tr className="table-highlight-light">
                                        <td>Net VAT {netVat >= 0 ? 'Payable' : 'Refundable'}</td>
                                        <td className={`text-right font-bold ${netVat >= 0 ? 'text-orange' : 'text-green'}`}>
                                            {formatAED(Math.abs(netVat))}
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>

                        {/* Text explanations / badges */}
                        <div className="calc-explanations">
                            <div className="explanation-card">
                                <h5>Corporate Tax Analysis</h5>
                                <p>{ctExplanation}</p>
                            </div>

                            <div className="explanation-card">
                                <h5>VAT Status & Compliance</h5>
                                <div className="vat-badge-row">
                                    <span className={`badge ${vatStatusClass}`}>{vatStatus}</span>
                                </div>
                                <p>{vatStatusDesc}</p>
                            </div>
                        </div>

                        <div className="calc-disclaimer">
                            <i className="fa-solid fa-circle-exclamation"></i>
                            <span>This calculation serves as an estimate only. Actual tax liabilities depend on your exact FTA registration status, audits, and legal structure. Partner with Lumen for absolute certainty.</span>
                        </div>
                    </div>
                </div>
            </div>
        </section>
    );
};

    // Expose component to global window namespace so app.jsx can access it
    window.TaxCalculator = TaxCalculator;
})();
