const { useState, useEffect, useCallback } = React;

const API_BASE = '/api';

const fetchJSON = async (url, options = {}) => {
    const res = await fetch(url, options);
    const text = await res.text();
    try {
        return JSON.parse(text);
    } catch (e) {
        console.error("Invalid JSON response:", text);
        throw new Error(`Server Error (Invalid JSON): ${text.substring(0, 100)}...`);
    }
};

const fetchSites = async () => {
    return fetchJSON(`${API_BASE}/sites`);
};

const createSite = async (data) => {
    return fetchJSON(`${API_BASE}/sites`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data)
    });
};

const uploadSite = async (id, zipFile) => {
    const formData = new FormData();
    formData.append('file', zipFile);
    return fetchJSON(`${API_BASE}/sites/${id}/upload`, {
        method: 'POST',
        body: formData
    });
};

const triggerDeploy = async (id) => {
    return fetchJSON(`${API_BASE}/sites/${id}/deploy`, { method: 'POST' });
};

const deleteSite = async (id) => {
    return fetchJSON(`${API_BASE}/sites/${id}`, { method: 'DELETE' });
};

const checkAuth = async () => {
    return fetchJSON(`${API_BASE}/auth/user`);
};

const loginGithub = async () => {
    const data = await fetchJSON(`${API_BASE}/auth/login`);
    if (data.url) window.location.href = data.url;
};

const loginGoogle = async () => {
    const data = await fetchJSON(`${API_BASE}/auth/google/login`);
    if (data.url) window.location.href = data.url;
};

const loginEmail = async (email, password) => {
    return fetchJSON(`${API_BASE}/auth/login_email`, {
        method: 'POST',
        body: JSON.stringify({ email, password })
    });
};

const registerUser = async (email, password, name) => {
    return fetchJSON(`${API_BASE}/auth/register`, {
        method: 'POST',
        body: JSON.stringify({ email, password, name })
    });
};

const topUpBalance = async (amount) => {
    return fetchJSON(`${API_BASE}/billing/topup`, {
        method: 'POST',
        body: JSON.stringify({ amount })
    });
};

const updateDomain = async (id, domain) => {
    return fetchJSON(`${API_BASE}/sites/${id}/update_domain`, {
        method: 'POST',
        body: JSON.stringify({ domain })
    });
};

const logoutGithub = async () => {
    await fetch(`${API_BASE}/auth/logout`);
    return true;
};

const fetchAdminStats = async () => fetchJSON(`${API_BASE}/admin/stats`);
const fetchAdminUsers = async () => fetchJSON(`${API_BASE}/admin/users`);
const fetchAdminSites = async () => fetchJSON(`${API_BASE}/admin/sites`);
const fetchAdminSettings = async () => fetchJSON(`${API_BASE}/admin/settings`);
const fetchAdminAffiliates = async () => fetchJSON(`${API_BASE}/admin/affiliates`);

const adminUserAction = async (id, action, data = {}) => fetchJSON(`${API_BASE}/admin/users/${id}/${action}`, { method: 'POST', body: JSON.stringify(data) });
const adminSiteAction = async (id, action) => fetchJSON(`${API_BASE}/admin/sites/${id}/${action}`, { method: 'POST' });
const saveAdminSettings = async (data) => fetchJSON(`${API_BASE}/admin/settings`, { method: 'POST', body: JSON.stringify(data) });
const adminAffiliateAction = async (id, action) => fetchJSON(`${API_BASE}/admin/affiliates/${id}/${action}`, { method: 'POST' });
const fetchAdminCoupons = async () => fetchJSON(`${API_BASE}/admin/coupons`);
const createAdminCoupon = async (data) => fetchJSON(`${API_BASE}/admin/coupons/create`, { method: 'POST', body: JSON.stringify(data) });
const deleteAdminCoupon = async (id) => fetchJSON(`${API_BASE}/admin/coupons/${id}/delete`, { method: 'POST' });

// Components

const Spinner = () => <i className="fas fa-circle-notch fa-spin"></i>;

const AdminPanel = ({ onClose }) => {
    const [tab, setTab] = useState('stats');
    const [stats, setStats] = useState(null);
    const [users, setUsers] = useState([]);
    const [sites, setSites] = useState([]);
    const [settings, setSettings] = useState({});
    const [affiliates, setAffiliates] = useState([]);
    const [coupons, setCoupons] = useState([]);
    const [loading, setLoading] = useState(false);
    
    const [creditModal, setCreditModal] = useState(null);

    useEffect(() => {
        loadData();
    }, [tab]);

    const loadData = async () => {
        setLoading(true);
        try {
            if (tab === 'stats') setStats(await fetchAdminStats());
            else if (tab === 'users') setUsers(await fetchAdminUsers());
            else if (tab === 'sites') setSites(await fetchAdminSites());
            else if (tab === 'settings') setSettings(await fetchAdminSettings());
            else if (tab === 'affiliates') setAffiliates(await fetchAdminAffiliates());
            else if (tab === 'coupons') setCoupons(await fetchAdminCoupons());
        } catch (e) {
            alert(e.message);
        } finally {
            setLoading(false);
        }
    };

    const handleBan = async (id, isBanned) => {
        if (!confirm(`Are you sure you want to ${isBanned ? 'unban' : 'ban'} this user?`)) return;
        try {
            await adminUserAction(id, isBanned ? 'unban' : 'ban');
            loadData();
        } catch(e) { alert(e.message); }
    };

    const handlePause = async (id, isPaused) => {
        try {
            await adminSiteAction(id, isPaused ? 'resume' : 'pause');
            loadData();
        } catch(e) { alert(e.message); }
    };

    const handleCredit = async (e) => {
        e.preventDefault();
        const amount = e.target.amount.value;
        const reason = e.target.reason.value;
        try {
            await adminUserAction(creditModal, 'credit', { amount, reason });
            setCreditModal(null);
            loadData();
        } catch(e) { alert(e.message); }
    };
    
    const handleSettingsSave = async (e) => {
        e.preventDefault();
        const formData = new FormData(e.target);
        const data = Object.fromEntries(formData.entries());
        try {
            await saveAdminSettings(data);
            alert('Settings saved');
        } catch(e) { alert(e.message); }
    };

    const handleAffiliate = async (id, action) => {
        try {
            const res = await adminAffiliateAction(id, action);
            if (action === 'approve') alert(`Approved! Code: ${res.code}`);
            loadData();
        } catch(e) { alert(e.message); }
    };

    const handleCreateCoupon = async (e) => {
        e.preventDefault();
        const formData = new FormData(e.target);
        const data = Object.fromEntries(formData.entries());
        try {
            await createAdminCoupon(data);
            e.target.reset();
            loadData();
        } catch(e) { alert(e.message); }
    };

    const handleDeleteCoupon = async (id) => {
        if (!confirm('Delete this coupon?')) return;
        try {
            await deleteAdminCoupon(id);
            loadData();
        } catch(e) { alert(e.message); }
    };

    return (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50 overflow-auto">
            <div className="bg-white rounded-lg shadow-xl max-w-5xl w-full p-6 h-[90vh] flex flex-col">
                <div className="flex justify-between mb-4">
                    <h2 className="text-xl font-bold text-red-600"><i className="fas fa-shield-alt"></i> Admin Panel</h2>
                    <button onClick={onClose}><i className="fas fa-times"></i></button>
                </div>

                <div className="flex mb-4 border-b overflow-x-auto">
                    {['stats', 'users', 'sites', 'settings', 'affiliates', 'coupons'].map(t => (
                        <button key={t} onClick={() => setTab(t)} className={`px-4 py-2 capitalize whitespace-nowrap ${tab === t ? 'border-b-2 border-red-500 font-bold' : 'text-gray-500'}`}>
                            {t} {t === 'affiliates' && stats?.pending_affiliates > 0 && <span className="ml-1 bg-red-500 text-white text-xs px-1 rounded-full">{stats.pending_affiliates}</span>}
                        </button>
                    ))}
                </div>

                <div className="flex-1 overflow-auto">
                    {loading ? <div className="text-center py-10"><Spinner /></div> : (
                        <>
                            {tab === 'stats' && stats && (
                                <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                                    <div className="bg-blue-50 p-4 rounded text-center">
                                        <div className="text-2xl font-bold">{stats.users}</div>
                                        <div className="text-gray-500">Users</div>
                                    </div>
                                    <div className="bg-green-50 p-4 rounded text-center">
                                        <div className="text-2xl font-bold">{stats.sites}</div>
                                        <div className="text-gray-500">Sites</div>
                                    </div>
                                    <div className="bg-purple-50 p-4 rounded text-center">
                                        <div className="text-2xl font-bold">{stats.deployments}</div>
                                        <div className="text-gray-500">Deployments</div>
                                    </div>
                                    <div className="bg-yellow-50 p-4 rounded text-center">
                                        <div className="text-2xl font-bold">€{parseFloat(stats.total_balance).toFixed(2)}</div>
                                        <div className="text-gray-500">Total Balance</div>
                                    </div>
                                </div>
                            )}

                            {tab === 'users' && (
                                <table className="w-full text-left text-sm">
                                    <thead className="bg-gray-100">
                                        <tr>
                                            <th className="p-2">ID</th>
                                            <th className="p-2">Name</th>
                                            <th className="p-2">Email</th>
                                            <th className="p-2">Balance</th>
                                            <th className="p-2">Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        {users.map(u => (
                                            <tr key={u.id} className={`border-b ${u.is_banned ? 'bg-red-50' : ''}`}>
                                                <td className="p-2">{u.id}</td>
                                                <td className="p-2">
                                                    {u.name}
                                                    {u.is_banned && <span className="ml-2 text-xs bg-red-100 text-red-800 px-1 rounded">BANNED</span>}
                                                </td>
                                                <td className="p-2">{u.email}</td>
                                                <td className="p-2">€{u.balance}</td>
                                                <td className="p-2 flex gap-2">
                                                    <button onClick={() => handleBan(u.id, u.is_banned)} className={`text-xs px-2 py-1 rounded ${u.is_banned ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'}`}>
                                                        {u.is_banned ? 'Unban' : 'Ban'}
                                                    </button>
                                                    <button onClick={() => setCreditModal(u.id)} className="text-xs px-2 py-1 rounded bg-blue-100 text-blue-700">
                                                        + Credit
                                                    </button>
                                                </td>
                                            </tr>
                                        ))}
                                    </tbody>
                                </table>
                            )}

                            {tab === 'sites' && (
                                <table className="w-full text-left text-sm">
                                    <thead className="bg-gray-100">
                                        <tr>
                                            <th className="p-2">Site</th>
                                            <th className="p-2">Owner</th>
                                            <th className="p-2">Domain</th>
                                            <th className="p-2">Status</th>
                                            <th className="p-2">Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        {sites.map(s => (
                                            <tr key={s.id} className="border-b">
                                                <td className="p-2 font-bold">{s.name}</td>
                                                <td className="p-2">{s.user_email}</td>
                                                <td className="p-2">{s.subdomain}</td>
                                                <td className="p-2">
                                                    <span className={`px-2 py-0.5 rounded text-xs ${s.status === 'suspended' ? 'bg-red-100 text-red-800' : 'bg-green-100 text-green-800'}`}>
                                                        {s.status || 'active'}
                                                    </span>
                                                </td>
                                                <td className="p-2">
                                                    <button onClick={() => handlePause(s.id, s.status === 'suspended')} className="text-xs text-blue-600 hover:underline">
                                                        {s.status === 'suspended' ? 'Resume' : 'Pause'}
                                                    </button>
                                                </td>
                                            </tr>
                                        ))}
                                    </tbody>
                                </table>
                            )}

                            {tab === 'settings' && (
                                <form onSubmit={handleSettingsSave} className="max-w-md space-y-4">
                                    <div>
                                        <label className="block text-sm font-medium text-gray-700">Server Price (€/mo)</label>
                                        <input name="server_price" defaultValue={settings.server_price} className="mt-1 block w-full border border-gray-300 rounded p-2" />
                                    </div>
                                    <div>
                                        <label className="block text-sm font-medium text-gray-700">Affiliate Commission (%)</label>
                                        <input name="affiliate_percent" defaultValue={settings.affiliate_percent} className="mt-1 block w-full border border-gray-300 rounded p-2" />
                                    </div>
                                    <div>
                                        <label className="block text-sm font-medium text-gray-700">Free Slots Threshold (Referrals)</label>
                                        <input name="free_slots_threshold" defaultValue={settings.free_slots_threshold} className="mt-1 block w-full border border-gray-300 rounded p-2" />
                                    </div>
                                    <button type="submit" className="bg-blue-600 text-white px-4 py-2 rounded hover:bg-blue-700">Save Settings</button>
                                </form>
                            )}

                            {tab === 'affiliates' && (
                                <table className="w-full text-left text-sm">
                                    <thead className="bg-gray-100">
                                        <tr>
                                            <th className="p-2">User</th>
                                            <th className="p-2">Email</th>
                                            <th className="p-2">Date</th>
                                            <th className="p-2">Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        {affiliates.length === 0 && <tr><td colSpan="4" className="p-4 text-center text-gray-500">No pending applications</td></tr>}
                                        {affiliates.map(a => (
                                            <tr key={a.id} className="border-b">
                                                <td className="p-2">{a.name}</td>
                                                <td className="p-2">{a.email}</td>
                                                <td className="p-2">{new Date(a.created_at).toLocaleDateString()}</td>
                                                <td className="p-2 flex gap-2">
                                                    <button onClick={() => handleAffiliate(a.id, 'approve')} className="bg-green-100 text-green-700 px-2 py-1 rounded text-xs">Approve</button>
                                                    <button onClick={() => handleAffiliate(a.id, 'reject')} className="bg-red-100 text-red-700 px-2 py-1 rounded text-xs">Reject</button>
                                                </td>
                                            </tr>
                                        ))}
                                    </tbody>
                                </table>
                            )}

                            {tab === 'coupons' && (
                                <div className="space-y-6">
                                    <div className="bg-gray-50 p-4 rounded">
                                        <h3 className="font-bold mb-2">Create Coupon</h3>
                                        <form onSubmit={handleCreateCoupon} className="flex gap-2 flex-wrap items-end">
                                            <div>
                                                <label className="block text-xs text-gray-500">Code</label>
                                                <input name="code" placeholder="SALE20" className="border rounded p-1 text-sm uppercase" required />
                                            </div>
                                            <div>
                                                <label className="block text-xs text-gray-500">Discount %</label>
                                                <input name="discount_percent" type="number" placeholder="20" className="border rounded p-1 text-sm w-20" required />
                                            </div>
                                            <div>
                                                <label className="block text-xs text-gray-500">Max Uses (-1 for unlim.)</label>
                                                <input name="max_uses" type="number" defaultValue="-1" className="border rounded p-1 text-sm w-24" />
                                            </div>
                                            <div>
                                                <label className="block text-xs text-gray-500">Expires (Optional)</label>
                                                <input name="expires_at" type="datetime-local" className="border rounded p-1 text-sm" />
                                            </div>
                                            <button type="submit" className="bg-green-600 text-white px-3 py-1.5 rounded text-sm hover:bg-green-700">Create</button>
                                        </form>
                                    </div>

                                    <table className="w-full text-left text-sm">
                                        <thead className="bg-gray-100">
                                            <tr>
                                                <th className="p-2">Code</th>
                                                <th className="p-2">Discount</th>
                                                <th className="p-2">Uses</th>
                                                <th className="p-2">Expires</th>
                                                <th className="p-2">Action</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            {coupons.length === 0 && <tr><td colSpan="5" className="p-4 text-center text-gray-500">No coupons found</td></tr>}
                                            {coupons.map(c => (
                                                <tr key={c.id} className="border-b">
                                                    <td className="p-2 font-mono font-bold">{c.code}</td>
                                                    <td className="p-2">{c.discount_percent}%</td>
                                                    <td className="p-2">{c.used_count} / {c.max_uses === -1 ? '∞' : c.max_uses}</td>
                                                    <td className="p-2">{c.expires_at ? new Date(c.expires_at).toLocaleDateString() : 'Never'}</td>
                                                    <td className="p-2">
                                                        <button onClick={() => handleDeleteCoupon(c.id)} className="text-red-600 hover:underline">Delete</button>
                                                    </td>
                                                </tr>
                                            ))}
                                        </tbody>
                                    </table>
                                </div>
                            )}
                        </>
                    )}
                </div>

                {creditModal && (
                    <div className="fixed inset-0 bg-black bg-opacity-25 flex items-center justify-center z-50">
                        <div className="bg-white p-6 rounded shadow-lg w-80">
                            <h3 className="font-bold mb-4">Add Credit</h3>
                            <form onSubmit={handleCredit}>
                                <input name="amount" type="number" step="0.01" placeholder="Amount (€)" className="w-full mb-2 p-2 border rounded" required />
                                <input name="reason" placeholder="Reason" className="w-full mb-4 p-2 border rounded" required />
                                <div className="flex justify-end gap-2">
                                    <button type="button" onClick={() => setCreditModal(null)} className="px-3 py-1 text-gray-600">Cancel</button>
                                    <button type="submit" className="px-3 py-1 bg-blue-600 text-white rounded">Add</button>
                                </div>
                            </form>
                        </div>
                    </div>
                )}
            </div>
        </div>
    );
};

const AuthModal = ({ onClose, onLogin }) => {
    const [isRegister, setIsRegister] = useState(false);
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const [name, setName] = useState('');
    const [error, setError] = useState('');
    const [loading, setLoading] = useState(false);

    const handleSubmit = async (e) => {
        e.preventDefault();
        setError('');
        setLoading(true);
        try {
            if (isRegister) {
                const res = await registerUser(email, password, name);
                if (res.error) throw new Error(res.error);
                // Auto login after register
                const loginRes = await loginEmail(email, password);
                if (loginRes.error) throw new Error(loginRes.error);
                onLogin(loginRes.user);
            } else {
                const res = await loginEmail(email, password);
                if (res.error) throw new Error(res.error);
                onLogin(res.user);
            }
            onClose();
        } catch (err) {
            setError(err.message);
        } finally {
            setLoading(false);
        }
    };

    return (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
            <div className="bg-white rounded-lg shadow-xl max-w-sm w-full p-6">
                <div className="flex justify-between mb-4">
                    <h2 className="text-xl font-bold">{isRegister ? 'Create Account' : 'Login'}</h2>
                    <button onClick={onClose}><i className="fas fa-times"></i></button>
                </div>

                <div className="flex mb-4 border-b">
                    <button onClick={() => setIsRegister(false)} className={`flex-1 py-2 ${!isRegister ? 'border-b-2 border-blue-500 font-bold' : 'text-gray-500'}`}>Login</button>
                    <button onClick={() => setIsRegister(true)} className={`flex-1 py-2 ${isRegister ? 'border-b-2 border-blue-500 font-bold' : 'text-gray-500'}`}>Register</button>
                </div>

                {error && <div className="bg-red-100 text-red-700 p-2 rounded mb-4 text-sm">{error}</div>}

                <form onSubmit={handleSubmit} className="space-y-4">
                    {isRegister && (
                        <div>
                            <label className="block text-sm font-medium text-gray-700">Name</label>
                            <input required value={name} onChange={e => setName(e.target.value)} className="mt-1 block w-full border border-gray-300 rounded-md p-2" />
                        </div>
                    )}
                    <div>
                        <label className="block text-sm font-medium text-gray-700">Email</label>
                        <input type="email" required value={email} onChange={e => setEmail(e.target.value)} className="mt-1 block w-full border border-gray-300 rounded-md p-2" />
                    </div>
                    <div>
                        <label className="block text-sm font-medium text-gray-700">Password</label>
                        <input type="password" required value={password} onChange={e => setPassword(e.target.value)} className="mt-1 block w-full border border-gray-300 rounded-md p-2" />
                    </div>
                    
                    <button type="submit" disabled={loading} className="w-full bg-blue-600 text-white py-2 rounded hover:bg-blue-700 disabled:opacity-50">
                        {loading ? <Spinner /> : (isRegister ? 'Sign Up' : 'Sign In')}
                    </button>
                </form>

                <div className="mt-4">
                    <div className="relative">
                        <div className="absolute inset-0 flex items-center"><div className="w-full border-t border-gray-300"></div></div>
                        <div className="relative flex justify-center text-sm"><span className="px-2 bg-white text-gray-500">Or continue with</span></div>
                    </div>
                    <div className="mt-4 grid grid-cols-2 gap-3">
                        <button onClick={loginGithub} className="flex justify-center items-center px-4 py-2 border border-gray-300 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50">
                            <i className="fab fa-github mr-2"></i> GitHub
                        </button>
                        <button onClick={loginGoogle} className="flex justify-center items-center px-4 py-2 border border-gray-300 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50">
                            <i className="fab fa-google mr-2 text-red-500"></i> Google
                        </button>
                    </div>
                </div>
            </div>
        </div>
    );
};

const TopUpModal = ({ onClose, onTopUp }) => {
    const [amount, setAmount] = useState('5.00');
    const [loading, setLoading] = useState(false);

    const handleSubmit = async (e) => {
        e.preventDefault();
        setLoading(true);
        try {
            const res = await fetchJSON(`${API_BASE}/payment/create`, {
                method: 'POST',
                body: JSON.stringify({ amount: parseFloat(amount) })
            });
            if (res.error) throw new Error(res.error);
            if (res.url) window.location.href = res.url;
        } catch (err) {
            alert(err.message);
            setLoading(false);
        }
    };

    return (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
            <div className="bg-white rounded-lg shadow-xl max-w-sm w-full p-6">
                <h2 className="text-xl font-bold mb-4">Add Funds</h2>
                <p className="text-gray-600 mb-4 text-sm">Add balance to your account to create more sites.</p>
                <form onSubmit={handleSubmit}>
                    <div className="mb-4">
                        <label className="block text-sm font-medium text-gray-700">Amount (€)</label>
                        <input type="number" step="0.01" min="1" required value={amount} onChange={e => setAmount(e.target.value)} className="mt-1 block w-full border border-gray-300 rounded-md p-2" />
                    </div>
                    <div className="flex justify-end gap-2">
                        <button type="button" onClick={onClose} className="px-4 py-2 text-gray-600 hover:bg-gray-100 rounded">Cancel</button>
                        <button type="submit" disabled={loading} className="px-4 py-2 bg-green-600 text-white rounded hover:bg-green-700 disabled:opacity-50">
                            {loading ? <Spinner /> : 'Pay Now'}
                        </button>
                    </div>
                </form>
            </div>
        </div>
    );
};

const SiteCard = ({ site, onClick }) => (
    <div onClick={() => onClick(site)} className="bg-white p-6 rounded-lg shadow hover:shadow-md cursor-pointer transition">
        <div className="flex justify-between items-start">
            <h3 className="text-lg font-bold text-gray-800">{site.name}</h3>
            <span className="text-xs px-2 py-1 bg-green-100 text-green-800 rounded-full">Active</span>
        </div>
        <p className="text-sm text-gray-500 mt-1">{site.subdomain}.{window.location.hostname}</p>
        <div className="mt-4 text-xs text-gray-400">
            {site.repo_url ? <><i className="fab fa-github"></i> Linked to Git</> : <><i className="fas fa-hdd"></i> Manual Deploy</>}
        </div>
    </div>
);

const FileUploader = ({ siteId, onUploadComplete }) => {
    const [status, setStatus] = useState('idle'); // idle, zipping, uploading, done, error
    const [progress, setProgress] = useState('');

    const handleDrop = useCallback(async (e) => {
        e.preventDefault();
        e.stopPropagation();
        setStatus('zipping');
        setProgress('Preparing files...');

        const items = e.dataTransfer.items;
        const zip = new JSZip();
        
        // Helper to read entries
        const processEntry = async (entry, path = '') => {
            if (entry.isFile) {
                const file = await new Promise((resolve, reject) => entry.file(resolve, reject));
                zip.file(path + entry.name, file);
            } else if (entry.isDirectory) {
                const dirReader = entry.createReader();
                const entries = await new Promise((resolve) => {
                    let allEntries = [];
                    const read = () => {
                        dirReader.readEntries((results) => {
                            if (results.length) {
                                allEntries = allEntries.concat(results);
                                read();
                            } else {
                                resolve(allEntries);
                            }
                        });
                    };
                    read();
                });
                for (let i = 0; i < entries.length; i++) {
                    await processEntry(entries[i], path + entry.name + '/');
                }
            }
        };

        try {
            for (let i = 0; i < items.length; i++) {
                const item = items[i];
                const entry = item.webkitGetAsEntry();
                if (entry) {
                    await processEntry(entry);
                }
            }
            
            setProgress('Compressing...');
            const blob = await zip.generateAsync({ type: 'blob' });
            
            setStatus('uploading');
            setProgress('Uploading...');
            await uploadSite(siteId, blob);
            
            setStatus('done');
            onUploadComplete();
        } catch (err) {
            console.error(err);
            setStatus('error');
            setProgress(err.message);
        }
    }, [siteId, onUploadComplete]);

    return (
        <div 
            onDragOver={(e) => { e.preventDefault(); e.currentTarget.classList.add('drop-active'); }}
            onDragLeave={(e) => { e.currentTarget.classList.remove('drop-active'); }}
            onDrop={handleDrop}
            className="border-2 border-dashed border-gray-300 rounded-lg p-8 text-center cursor-pointer hover:border-blue-500 transition"
        >
            {status === 'idle' && (
                <>
                    <i className="fas fa-cloud-upload-alt text-4xl text-gray-400 mb-2"></i>
                    <p className="text-gray-600">Drag & Drop your build folder (dist) here to deploy</p>
                </>
            )}
            {(status === 'zipping' || status === 'uploading') && (
                <div className="text-blue-600">
                    <Spinner /> {progress}
                </div>
            )}
            {status === 'done' && <div className="text-green-600"><i className="fas fa-check"></i> Deployed!</div>}
            {status === 'error' && <div className="text-red-600"><i className="fas fa-times"></i> {progress}</div>}
        </div>
    );
};

const NewSiteModal = ({ user, sites, onClose, onCreated }) => {
    const [mode, setMode] = useState('git'); // git, manual
    const [name, setName] = useState('');
    const [repo, setRepo] = useState('');
    const [code, setCode] = useState('');
    const [loading, setLoading] = useState(false);

    const freeSlots = user?.free_slots || 0;
    const usedSlots = sites?.length || 0;
    const isFree = usedSlots < (1 + freeSlots);
    const price = isFree ? 0 : (user?.server_price || 1.99);

    const handleSubmit = async (e) => {
        e.preventDefault();
        setLoading(true);
        try {
            const data = { name, repo: mode === 'git' ? repo : null, code };
            const res = await createSite(data);
            if (res.error) throw new Error(res.error);
            onCreated(res);
            onClose();
        } catch (err) {
            alert(err.message);
        } finally {
            setLoading(false);
        }
    };

    return (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
            <div className="bg-white rounded-lg shadow-xl max-w-md w-full p-6">
                <h2 className="text-xl font-bold mb-4">New Site</h2>
                
                <div className="flex mb-4 border-b">
                    <button onClick={() => setMode('git')} className={`flex-1 py-2 ${mode === 'git' ? 'border-b-2 border-blue-500 font-bold' : 'text-gray-500'}`}>Import from Git</button>
                    <button onClick={() => setMode('manual')} className={`flex-1 py-2 ${mode === 'manual' ? 'border-b-2 border-blue-500 font-bold' : 'text-gray-500'}`}>Drag & Drop</button>
                </div>

                <form onSubmit={handleSubmit}>
                    <div className="mb-4">
                        <label className="block text-sm font-medium text-gray-700">Site Name</label>
                        <input required value={name} onChange={e => setName(e.target.value)} className="mt-1 block w-full border border-gray-300 rounded-md p-2" placeholder="My Awesome Site" />
                    </div>

                    {mode === 'git' && (
                        <div className="mb-4">
                            <label className="block text-sm font-medium text-gray-700">Git Repository URL</label>
                            <input required value={repo} onChange={e => setRepo(e.target.value)} className="mt-1 block w-full border border-gray-300 rounded-md p-2" placeholder="https://github.com/user/repo" />
                            <p className="text-xs text-gray-500 mt-1">
                                {user ? <span className="text-green-600"><i className="fas fa-check"></i> Authenticated. Private repos supported.</span> : <span className="text-orange-500"><i className="fas fa-exclamation-triangle"></i> Login for private repos.</span>}
                            </p>
                        </div>
                    )}
                    
                    <div className="mb-4">
                        <label className="block text-sm font-medium text-gray-700">Promo / Affiliate Code (Optional)</label>
                        <input value={code} onChange={e => setCode(e.target.value)} className="mt-1 block w-full border border-gray-300 rounded-md p-2 uppercase" placeholder="CODE123" />
                    </div>

                    <div className="bg-gray-50 p-3 rounded border flex justify-between items-center mb-4">
                        <span className="text-sm font-bold text-gray-700">Total Price:</span>
                        <div className="text-right">
                            {isFree ? (
                                <span className="text-green-600 font-bold">Free</span>
                            ) : (
                                <span className="font-bold">€{price.toFixed(2)} <span className="text-xs font-normal text-gray-500">/ month</span></span>
                            )}
                            {isFree && <div className="text-xs text-green-600">Free slot available ({usedSlots}/{1 + freeSlots})</div>}
                        </div>
                    </div>

                    <div className="flex justify-end gap-2 mt-6">
                        <button type="button" onClick={onClose} className="px-4 py-2 text-gray-600 hover:bg-gray-100 rounded">Cancel</button>
                        <button type="submit" disabled={loading} className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 disabled:opacity-50">
                            {loading ? <Spinner /> : 'Create Site'}
                        </button>
                    </div>
                </form>
            </div>
        </div>
    );
};

const getLatestDeployment = async (siteId) => {
    return fetchJSON(`${API_BASE}/sites/${siteId}/deployments/latest`);
};

const DeploymentStatus = ({ siteId }) => {
    const [deploy, setDeploy] = useState(null);
    
    useEffect(() => {
        let interval;
        const fetchStatus = async () => {
            const data = await getLatestDeployment(siteId);
            setDeploy(data);
            if (data.status === 'success' || data.status === 'error') {
                clearInterval(interval);
            }
        };
        
        fetchStatus();
        interval = setInterval(fetchStatus, 2000); // Poll every 2s
        return () => clearInterval(interval);
    }, [siteId]);

    if (!deploy || deploy.status === 'none') return null;

    const isRunning = deploy.status === 'pending' || deploy.status === 'building';
    
    return (
        <div className="bg-gray-900 text-gray-300 p-4 rounded-lg font-mono text-xs mb-4 max-h-64 overflow-y-auto">
            <div className="flex justify-between items-center mb-2 border-b border-gray-700 pb-2">
                <div className="flex items-center gap-2">
                    <span className="font-bold uppercase text-gray-400">Deployment Status</span>
                    <button 
                        onClick={() => { navigator.clipboard.writeText(deploy.log); }} 
                        className="text-gray-500 hover:text-white px-2 py-1 rounded hover:bg-gray-800 transition" 
                        title="Copy Log"
                    >
                        <i className="fas fa-copy"></i> Copy
                    </button>
                </div>
                <span className={`px-2 py-1 rounded ${deploy.status === 'success' ? 'bg-green-900 text-green-300' : (deploy.status === 'error' ? 'bg-red-900 text-red-300' : 'bg-blue-900 text-blue-300')}`}>
                    {isRunning && <Spinner />} {deploy.status}
                </span>
            </div>
            {deploy.status === 'error' && (
                <div className="bg-red-900/50 p-2 rounded mb-2 border border-red-700">
                    <p className="font-bold text-red-300">Deployment Failed</p>
                    <p className="text-red-200 mt-1">
                        Please contact support: <a href="https://support.hostigo-cloud.de" target="_blank" className="underline text-white hover:text-red-100">https://support.hostigo-cloud.de</a>
                    </p>
                </div>
            )}
            <pre className="whitespace-pre-wrap">{deploy.log}</pre>
        </div>
    );
};

const SiteDetail = ({ site, onBack, onError }) => {
    const [deploying, setDeploying] = useState(false);
    // Force re-render of status component
    const [deployKey, setDeployKey] = useState(0);
    const [customDomain, setCustomDomain] = useState(site.custom_domain || '');
    const [savingDomain, setSavingDomain] = useState(false);

    const handleDeploy = async () => {
        if (!confirm('Start new deployment?')) return;
        setDeploying(true);
        try {
            const res = await triggerDeploy(site.id);
            if (res.error) {
                if (onError) onError(res.error);
                else alert(res.error);
            } else {
                setDeployKey(k => k + 1); // Reset polling
            }
        } catch (e) {
            if (onError) onError(e.message);
            else alert(e.message);
        } finally {
            setDeploying(false);
        }
    };
    
    const handleDelete = async () => {
        if (!confirm('Are you sure you want to delete this site?')) return;
        await deleteSite(site.id);
        onBack();
    };

    const handleSaveDomain = async () => {
        setSavingDomain(true);
        try {
            const res = await updateDomain(site.id, customDomain);
            if (res.error) {
                if (onError) onError(res.error);
                else alert(res.error);
            } else {
                alert('Domain updated successfully!');
            }
        } catch (e) {
            if (onError) onError(e.message);
            else alert(e.message);
        } finally {
            setSavingDomain(false);
        }
    };

    // Ensure port is included in URL if needed
    const port = window.location.port ? ':' + window.location.port : '';
    const siteUrl = `http://${site.subdomain}.${window.location.hostname}${port}`;
    const webhookUrl = `${window.location.origin}/api/webhook/${site.id}`;

    return (
        <div>
            <button onClick={onBack} className="mb-4 text-blue-600 hover:underline"><i className="fas fa-arrow-left"></i> Back to Sites</button>
            
            <div className="bg-white rounded-lg shadow p-6 mb-6">
                <div className="flex justify-between items-start">
                    <div>
                        <h1 className="text-3xl font-bold">{site.name}</h1>
                        <a href={siteUrl} target="_blank" className="text-blue-600 hover:underline mt-1 block">{siteUrl} <i className="fas fa-external-link-alt text-sm"></i></a>
                    </div>
                    <button onClick={handleDelete} className="text-red-600 hover:bg-red-50 px-3 py-1 rounded">Delete Site</button>
                </div>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div className="bg-white rounded-lg shadow p-6">
                    <h2 className="text-xl font-bold mb-4">Deployment</h2>
                    
                    <DeploymentStatus key={deployKey} siteId={site.id} />

                    {site.repo_url ? (
                        <div>
                            <p className="mb-4 text-sm text-gray-600">Connected to: <b>{site.repo_url}</b></p>
                            <button onClick={handleDeploy} disabled={deploying} className="w-full bg-gray-800 text-white py-2 rounded hover:bg-gray-900 disabled:opacity-50">
                                {deploying ? <><Spinner /> Starting...</> : 'Trigger New Deploy'}
                            </button>
                            
                            <div className="mt-6">
                                <label className="block text-xs font-bold uppercase text-gray-500 mb-1">Webhook URL</label>
                                <div className="flex">
                                    <input readOnly value={webhookUrl} className="flex-1 bg-gray-100 border p-2 text-sm rounded-l" />
                                    <button onClick={() => navigator.clipboard.writeText(webhookUrl)} className="bg-gray-200 px-3 py-2 rounded-r hover:bg-gray-300"><i className="fas fa-copy"></i></button>
                                </div>
                                <p className="text-xs text-gray-500 mt-1">Add this to your GitHub repository settings under Webhooks.</p>
                            </div>
                        </div>
                    ) : (
                        <div>
                            <p className="mb-4 text-sm text-gray-600">Drag and drop your project folder (containing index.html) to deploy.</p>
                            <FileUploader siteId={site.id} onUploadComplete={() => alert('Deployed successfully!')} />
                        </div>
                    )}
                </div>

                <div className="bg-white rounded-lg shadow p-6">
                    <h2 className="text-xl font-bold mb-4">Configuration</h2>
                    <div className="space-y-4">
                         <div>
                            <label className="block text-sm font-medium text-gray-700">Subdomain</label>
                            <input disabled value={site.subdomain} className="mt-1 block w-full border border-gray-300 rounded-md p-2 bg-gray-50" />
                        </div>
                        <div>
                            <label className="block text-sm font-medium text-gray-700">Custom Domain</label>
                            <div className="flex mt-1">
                                <input 
                                    value={customDomain} 
                                    onChange={e => setCustomDomain(e.target.value)} 
                                    className="block w-full border border-gray-300 rounded-l-md p-2" 
                                    placeholder="example.com"
                                />
                                <button 
                                    onClick={handleSaveDomain} 
                                    disabled={savingDomain}
                                    className="bg-blue-600 text-white px-4 py-2 rounded-r-md hover:bg-blue-700 disabled:opacity-50"
                                >
                                    {savingDomain ? <Spinner /> : 'Save'}
                                </button>
                            </div>
                            <p className="text-xs text-gray-500 mt-1">
                                Point your domain's A-Record to <b>{window.location.hostname}</b> (or CNAME to this subdomain).
                            </p>
                        </div>
                        <div>
                            <label className="block text-sm font-medium text-gray-700">Site ID</label>
                            <input disabled value={site.id} className="mt-1 block w-full border border-gray-300 rounded-md p-2 bg-gray-50 font-mono text-sm" />
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
};

const TransactionsView = ({ onBack }) => {
    const [transactions, setTransactions] = useState([]);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        fetchJSON(`${API_BASE}/auth/transactions`)
            .then(setTransactions)
            .catch(err => alert(err.message))
            .finally(() => setLoading(false));
    }, []);

    return (
        <div className="max-w-4xl mx-auto p-6">
            <button onClick={onBack} className="mb-4 text-blue-600 hover:underline"><i className="fas fa-arrow-left"></i> Back to Dashboard</button>
            <h2 className="text-2xl font-bold mb-6">Transaction History</h2>
            <div className="bg-white rounded-lg shadow overflow-hidden">
                <table className="min-w-full">
                    <thead className="bg-gray-50">
                        <tr>
                            <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Date</th>
                            <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Description</th>
                            <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">Amount</th>
                        </tr>
                    </thead>
                    <tbody className="bg-white divide-y divide-gray-200">
                        {loading ? (
                            <tr><td colSpan="3" className="px-6 py-4 text-center"><Spinner /></td></tr>
                        ) : transactions.length === 0 ? (
                            <tr><td colSpan="3" className="px-6 py-4 text-center text-gray-500">No transactions found</td></tr>
                        ) : (
                            transactions.map(t => (
                                <tr key={t.id}>
                                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{new Date(t.created_at).toLocaleString()}</td>
                                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{t.description}</td>
                                    <td className={`px-6 py-4 whitespace-nowrap text-sm text-right font-bold ${parseFloat(t.amount) >= 0 ? 'text-green-600' : 'text-red-600'}`}>
                                        {parseFloat(t.amount) >= 0 ? '+' : ''}{parseFloat(t.amount).toFixed(2)} €
                                    </td>
                                </tr>
                            ))
                        )}
                    </tbody>
                </table>
            </div>
        </div>
    );
};

const SettingsView = ({ user, onBack, onUserUpdate }) => {
    const [email, setEmail] = useState(user.email || '');
    const [isEditing, setIsEditing] = useState(!user.email);
    const [loading, setLoading] = useState(false);

    const handleSave = async () => {
        setLoading(true);
        try {
            await fetchJSON(`${API_BASE}/auth/update_email`, {
                method: 'POST',
                body: JSON.stringify({ email })
            });
            await onUserUpdate();
            setIsEditing(false);
        } catch (err) {
            alert(err.message);
        } finally {
            setLoading(false);
        }
    };

    return (
        <div className="max-w-2xl mx-auto p-6">
            <button onClick={onBack} className="mb-4 text-blue-600 hover:underline"><i className="fas fa-arrow-left"></i> Back to Dashboard</button>
            <h2 className="text-2xl font-bold mb-6">Account Settings</h2>
            <div className="bg-white rounded-lg shadow p-6 space-y-4">
                <div>
                    <label className="block text-sm font-medium text-gray-700">Display Name</label>
                    <div className="mt-1 p-2 bg-gray-50 rounded border">{user.name}</div>
                </div>
                <div>
                    <label className="block text-sm font-medium text-gray-700">Email Address</label>
                    <div className="mt-1 flex gap-2">
                        {isEditing ? (
                            <>
                                <input 
                                    type="email" 
                                    value={email} 
                                    onChange={e => setEmail(e.target.value)}
                                    className="flex-1 border border-gray-300 rounded-md p-2 focus:ring-blue-500 focus:border-blue-500"
                                    placeholder="Enter your email"
                                />
                                <button 
                                    onClick={handleSave} 
                                    disabled={loading}
                                    className="bg-blue-600 text-white px-4 py-2 rounded hover:bg-blue-700 disabled:opacity-50"
                                >
                                    {loading ? <Spinner className="w-4 h-4" /> : 'Save'}
                                </button>
                                {user.email && (
                                    <button 
                                        onClick={() => { setIsEditing(false); setEmail(user.email); }}
                                        className="text-gray-500 hover:text-gray-700 px-2"
                                    >
                                        Cancel
                                    </button>
                                )}
                            </>
                        ) : (
                            <div className="flex-1 flex justify-between items-center p-2 bg-gray-50 rounded border">
                                <span className={!user.email ? 'text-gray-400 italic' : ''}>{user.email || 'No email linked (GitHub)'}</span>
                                <button onClick={() => setIsEditing(true)} className="text-blue-600 text-sm hover:underline">Change</button>
                            </div>
                        )}
                    </div>
                    {!user.email && <p className="mt-1 text-xs text-yellow-600"><i className="fas fa-info-circle"></i> Please link an email address for notifications and account recovery.</p>}
                </div>
                <div>
                    <label className="block text-sm font-medium text-gray-700">User ID</label>
                    <div className="mt-1 p-2 bg-gray-50 rounded border font-mono text-sm">{user.id}</div>
                </div>
                <div className="pt-4 border-t">
                    <h3 className="text-lg font-medium text-gray-900">Linked Accounts</h3>
                    <div className="mt-2 flex gap-4">
                    {user.github_id && <span className="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-gray-100 text-gray-800"><i className="fab fa-github mr-2"></i> GitHub Connected</span>}
                    {user.google_id && <span className="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-blue-100 text-blue-800"><i className="fab fa-google mr-2"></i> Google Connected</span>}
                    </div>
                </div>
            </div>
        </div>
    );
};

const LandingPage = ({ onGetStarted }) => (
    <div className="min-h-screen bg-gray-50 flex flex-col justify-center items-center p-4">
        <div className="max-w-4xl w-full text-center">
            <h1 className="text-5xl font-bold text-gray-900 mb-6">Deploy your site in seconds.</h1>
            <p className="text-xl text-gray-600 mb-8">
                The best way to build, deploy, and scale your web projects. 
                Drag & Drop or connect via Git.
            </p>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-8 mb-12 text-left">
                <div className="bg-white p-6 rounded-lg shadow-sm">
                    <div className="text-blue-600 text-2xl mb-4"><i className="fas fa-bolt"></i></div>
                    <h3 className="font-bold text-lg mb-2">Fast Deploys</h3>
                    <p className="text-gray-600 text-sm">Push to Git or drag a folder. Your site is live instantly.</p>
                </div>
                <div className="bg-white p-6 rounded-lg shadow-sm">
                    <div className="text-green-600 text-2xl mb-4"><i className="fas fa-dollar-sign"></i></div>
                    <h3 className="font-bold text-lg mb-2">Start for Free</h3>
                    <p className="text-gray-600 text-sm">One site is always free. Scale up as you grow for just €1.99/mo.</p>
                </div>
                <div className="bg-white p-6 rounded-lg shadow-sm">
                    <div className="text-purple-600 text-2xl mb-4"><i className="fab fa-github"></i></div>
                    <h3 className="font-bold text-lg mb-2">Git Integration</h3>
                    <p className="text-gray-600 text-sm">Automatic builds for every push. Supports private repositories.</p>
                </div>
            </div>
            <button onClick={onGetStarted} className="bg-blue-600 text-white px-8 py-4 rounded-lg text-lg font-bold hover:bg-blue-700 shadow-lg transition transform hover:-translate-y-1">
                Get Started for Free <i className="fas fa-arrow-right ml-2"></i>
            </button>
        </div>
        <div className="mt-12 text-gray-400 text-sm">
            &copy; 2026 PHP-lify. All rights reserved.
        </div>
    </div>
);

const ErrorModal = ({ error, onClose }) => {
    if (!error) return null;
    return (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-[60]">
            <div className="bg-white rounded-lg shadow-xl max-w-lg w-full p-6 border-t-4 border-red-500">
                <div className="flex justify-between items-start mb-4">
                    <h2 className="text-xl font-bold text-red-600 flex items-center">
                        <i className="fas fa-exclamation-triangle mr-2"></i> Error
                    </h2>
                    <button onClick={onClose} className="text-gray-400 hover:text-gray-600"><i className="fas fa-times"></i></button>
                </div>
                <div className="bg-gray-100 p-4 rounded mb-4 overflow-auto max-h-60">
                    <pre className="text-xs font-mono text-gray-800 whitespace-pre-wrap select-text">{error}</pre>
                </div>
                <div className="flex justify-end gap-3">
                    <button 
                        onClick={() => { navigator.clipboard.writeText(error); }} 
                        className="px-4 py-2 bg-gray-200 text-gray-700 rounded hover:bg-gray-300 flex items-center"
                    >
                        <i className="fas fa-copy mr-2"></i> Copy Error
                    </button>
                    <button onClick={onClose} className="px-4 py-2 bg-red-600 text-white rounded hover:bg-red-700">Close</button>
                </div>
            </div>
        </div>
    );
};

const AffiliateView = ({ user, onClose }) => {
    const [info, setInfo] = useState(null);
    const [loading, setLoading] = useState(false);
    
    useEffect(() => {
        loadInfo();
    }, []);

    const loadInfo = async () => {
        setLoading(true);
        try {
            const data = await fetchJSON(`${API_BASE}/auth/affiliate/info`);
            setInfo(data);
        } catch(e) {
            alert(e.message);
        } finally {
            setLoading(false);
        }
    };

    const handleApply = async () => {
        setLoading(true);
        try {
            await fetchJSON(`${API_BASE}/auth/affiliate/apply`, { method: 'POST' });
            loadInfo();
        } catch(e) {
            alert(e.message);
        } finally {
            setLoading(false);
        }
    };

    return (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50 overflow-auto">
            <div className="bg-white rounded-lg shadow-xl max-w-lg w-full p-6 relative">
                <button onClick={onClose} className="absolute top-4 right-4 text-gray-500 hover:text-black">
                    <i className="fas fa-times"></i>
                </button>
                
                <h2 className="text-2xl font-bold mb-6 text-purple-700">
                    <i className="fas fa-handshake"></i> Affiliate Program
                </h2>

                {loading ? <div className="text-center py-10"><Spinner /></div> : (
                    <>
                        {!info?.has_code && !info?.is_pending && (
                            <div className="text-center">
                                <i className="fas fa-rocket text-6xl text-purple-200 mb-4"></i>
                                <h3 className="text-xl font-bold mb-2">Join our Partner Program</h3>
                                <p className="text-gray-600 mb-6">
                                    Earn 12% commission on every server purchase made using your unique code.
                                    Get free server slots when you refer 1000+ users!
                                </p>
                                <button onClick={handleApply} className="bg-purple-600 text-white px-6 py-3 rounded-lg font-bold hover:bg-purple-700 transition transform hover:scale-105">
                                    Apply Now
                                </button>
                            </div>
                        )}

                        {info?.is_pending && (
                            <div className="text-center py-8">
                                <i className="fas fa-clock text-5xl text-yellow-500 mb-4"></i>
                                <h3 className="text-xl font-bold">Application Pending</h3>
                                <p className="text-gray-600 mt-2">We are reviewing your application. Please check back later.</p>
                            </div>
                        )}

                        {info?.has_code && (
                            <div>
                                <div className="bg-purple-50 border border-purple-200 rounded-lg p-4 mb-6 text-center">
                                    <p className="text-sm text-purple-600 uppercase font-bold tracking-wider mb-1">Your Unique Code</p>
                                    <div className="text-3xl font-mono font-bold text-purple-800 tracking-widest">{info.code}</div>
                                    <p className="text-xs text-gray-500 mt-2">Share this code with your audience</p>
                                </div>

                                <div className="grid grid-cols-2 gap-4 mb-6">
                                    <div className="bg-gray-50 p-4 rounded text-center">
                                        <div className="text-2xl font-bold text-gray-800">{info.referrals}</div>
                                        <div className="text-xs text-gray-500 uppercase">Referrals</div>
                                    </div>
                                    <div className="bg-gray-50 p-4 rounded text-center">
                                        <div className="text-2xl font-bold text-green-600">€{info.earnings}</div>
                                        <div className="text-xs text-gray-500 uppercase">Earnings</div>
                                    </div>
                                </div>

                                <div className="bg-blue-50 p-4 rounded text-sm text-blue-800">
                                    <i className="fas fa-info-circle mr-2"></i>
                                    Free slots progress: <strong>{info.referrals} / {info.threshold || 1000}</strong>
                                    <div className="w-full bg-blue-200 h-2 rounded-full mt-2">
                                        <div className="bg-blue-600 h-2 rounded-full" style={{ width: `${Math.min(100, (info.referrals / (info.threshold || 1000)) * 100)}%` }}></div>
                                    </div>
                                </div>
                            </div>
                        )}
                    </>
                )}
            </div>
        </div>
    );
};

const App = () => {
    const [user, setUser] = useState(null);
    const [loading, setLoading] = useState(true);
    const [sites, setSites] = useState([]);
    const [showNewModal, setShowNewModal] = useState(false);
    const [showTopUp, setShowTopUp] = useState(false);
    const [showAdmin, setShowAdmin] = useState(false);
    const [selectedSite, setSelectedSite] = useState(null);
    const [authModal, setAuthModal] = useState(false);
    const [globalError, setGlobalError] = useState(null);
    const [userMenuOpen, setUserMenuOpen] = useState(false);
    const [showAffiliate, setShowAffiliate] = useState(false);

    const [view, setView] = useState('list'); // list, detail, settings, transactions

    const refreshData = useCallback(async () => {
        setLoading(true);
        try {
            const data = await fetchSites();
            setSites(data);
            const auth = await checkAuth();
            if (auth.authenticated) setUser(auth.user);
        } catch (err) {
            setGlobalError(err.message);
        } finally {
            setLoading(false);
        }
    }, []);

    useEffect(() => {
        refreshData();
    }, [refreshData]);

    const handleSiteClick = (site) => {
        setSelectedSite(site);
        setView('detail');
    };

    const handleBack = () => {
        setSelectedSite(null);
        setView('list');
        refreshData();
    };
    
    const handleLogout = async () => {
        await logoutGithub();
        setUser(null);
        setSites([]);
        setView('list');
        setUserMenuOpen(false);
    };

    // If not logged in and not loading, show Landing Page
    if (!loading && !user) {
        return (
            <>
                <LandingPage onGetStarted={() => setAuthModal(true)} />
                {authModal && (
                    <AuthModal 
                        onClose={() => setAuthModal(false)}
                        onLogin={(u) => {
                            setUser(u);
                            refreshData();
                        }}
                    />
                )}
                <ErrorModal error={globalError} onClose={() => setGlobalError(null)} />
            </>
        );
    }

    return (
        <div className="min-h-screen">
            <ErrorModal error={globalError} onClose={() => setGlobalError(null)} />
            <nav className="bg-white border-b border-gray-200 relative z-30">
                <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
                    <div className="flex justify-between h-16">
                        <div className="flex items-center cursor-pointer" onClick={() => { setView('list'); setSelectedSite(null); }}>
                            <i className="fas fa-layer-group text-blue-600 text-2xl mr-2"></i>
                            <span className="font-bold text-xl text-gray-900">PHP-lify</span>
                        </div>
                        <div className="flex items-center gap-4">
                            {user ? (
                                 <div className="flex items-center gap-4">
                                    <div className="flex items-center text-sm text-gray-600 bg-gray-100 px-3 py-1 rounded-full">
                                        <i className="fas fa-wallet mr-2 text-green-600"></i>
                                        <span className="font-bold">€{parseFloat(user.balance || 0).toFixed(2)}</span>
                                        <button onClick={() => setShowTopUp(true)} className="ml-2 text-blue-600 hover:text-blue-800 text-xs font-bold uppercase">Top Up</button>
                                    </div>
                                    
                                    <div className="relative">
                                        <button onClick={() => setUserMenuOpen(!userMenuOpen)} className="flex items-center gap-2 focus:outline-none hover:bg-gray-50 p-1 rounded transition">
                                            <img src={user.avatar_url || 'https://www.gravatar.com/avatar/?d=mp'} className="w-8 h-8 rounded-full border border-gray-300" />
                                            <span className="font-medium text-gray-700 hidden sm:block">{user.name || user.email}</span>
                                            <i className={`fas fa-chevron-down text-xs text-gray-500 transition-transform ${userMenuOpen ? 'rotate-180' : ''}`}></i>
                                        </button>
                                        
                                        {userMenuOpen && (
                                            <>
                                                <div className="fixed inset-0 z-10 cursor-default" onClick={() => setUserMenuOpen(false)}></div>
                                                <div className="absolute right-0 mt-2 w-56 bg-white rounded-md shadow-xl py-1 z-20 border border-gray-100 ring-1 ring-black ring-opacity-5">
                                                    <div className="px-4 py-3 border-b border-gray-100">
                                                        <p className="text-sm text-gray-900 font-bold truncate">{user.name}</p>
                                                        <p className="text-xs text-gray-500 truncate">{user.email}</p>
                                                    </div>
                                                    
                                                    <button onClick={() => { setView('settings'); setUserMenuOpen(false); }} className="block w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-50 hover:text-blue-600">
                                                        <i className="fas fa-cog w-5 text-gray-400 mr-2"></i> Account Settings
                                                    </button>
                                                    
                                                    <button onClick={() => { setView('transactions'); setUserMenuOpen(false); }} className="block w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-50 hover:text-blue-600">
                                                        <i className="fas fa-receipt w-5 text-gray-400 mr-2"></i> Transactions
                                                    </button>
                                                    
                                                    <button onClick={() => { setShowAffiliate(true); setUserMenuOpen(false); }} className="block w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-50 hover:text-purple-600">
                                                        <i className="fas fa-handshake w-5 text-gray-400 mr-2"></i> Affiliate Program
                                                    </button>
                                                    
                                                    {user.is_admin && (
                                                        <button onClick={() => { setShowAdmin(true); setUserMenuOpen(false); }} className="block w-full text-left px-4 py-2 text-sm text-red-600 hover:bg-red-50">
                                                            <i className="fas fa-shield-alt w-5 mr-2"></i> Admin Panel
                                                        </button>
                                                    )}
                                                    
                                                    <div className="border-t border-gray-100 my-1"></div>
                                                    
                                                    <button onClick={handleLogout} className="block w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-50 hover:text-red-600">
                                                        <i className="fas fa-sign-out-alt w-5 text-gray-400 mr-2"></i> Sign out
                                                    </button>
                                                </div>
                                            </>
                                        )}
                                    </div>
                                 </div>
                            ) : (
                                <button onClick={() => setAuthModal(true)} className="bg-gray-800 text-white px-3 py-1 rounded hover:bg-gray-900 text-sm">Login / Register</button>
                            )}
                        </div>
                    </div>
                </div>
            </nav>

            <main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
                {view === 'list' && (
                    <>
                        <div className="flex justify-between items-center mb-6">
                            <h2 className="text-2xl font-bold text-gray-800">Your Sites</h2>
                            <button onClick={() => {
                                if (!user) {
                                    setAuthModal(true);
                                } else {
                                    setShowNewModal(true);
                                }
                            }} className="bg-blue-600 text-white px-4 py-2 rounded hover:bg-blue-700 shadow">
                                <i className="fas fa-plus mr-2"></i> New Site
                            </button>
                        </div>

                        {loading ? (
                            <div className="text-center py-12"><Spinner /> Loading...</div>
                        ) : (
                            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                                {sites.length === 0 ? (
                                    <div className="col-span-full text-center py-12 text-gray-500">
                                        No sites yet. Create one to get started!
                                    </div>
                                ) : (
                                    sites.map(site => <SiteCard key={site.id} site={site} onClick={handleSiteClick} />)
                                )}
                            </div>
                        )}
                    </>
                )}

                {view === 'detail' && selectedSite && (
                    <SiteDetail site={selectedSite} onBack={handleBack} onError={setGlobalError} />
                )}

                {view === 'settings' && <SettingsView user={user} onBack={() => setView('list')} onUserUpdate={refreshData} />}
                {view === 'transactions' && <TransactionsView onBack={() => setView('list')} />}
            </main>

            {showNewModal && (
                <NewSiteModal 
                    user={user}
                    sites={sites}
                    onClose={() => setShowNewModal(false)} 
                    onCreated={(site) => {
                        setSites([site, ...sites]);
                        handleSiteClick(site);
                        refreshData();
                    }} 
                />
            )}

            {authModal && (
                <AuthModal 
                    onClose={() => setAuthModal(false)}
                    onLogin={(u) => {
                        setUser(u);
                        refreshData();
                    }}
                />
            )}

            {showTopUp && (
                <TopUpModal 
                    onClose={() => setShowTopUp(false)}
                    onTopUp={(newBalance) => setUser({...user, balance: newBalance})}
                />
            )}

            {showAdmin && <AdminPanel onClose={() => setShowAdmin(false)} />}
            {showAffiliate && <AffiliateView user={user} onClose={() => setShowAffiliate(false)} />}
        </div>
    );
};

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
