const { useState, useEffect } = React;

function CustomerLoginModal({ onClose, onLoginSuccess }) {
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const [step, setStep] = useState('login'); 
    const [twoFaCode, setTwoFaCode] = useState('');
    const [error, setError] = useState('');
    const [loading, setLoading] = useState(false);

    const handleLogin = async (e) => {
        e.preventDefault();
        setLoading(true);
        setError('');
        try {
            const res = await axios.post('/api/auth/customer/login', {
                email, password, rememberMe: true, 
                powChallenge: { challenge: { algorithm: "SHA-256", challenge: "mock", maxNumber: 0, salt: "mock", signature: "mock" }, solution: 0 },
                captcha: { image: { id: "3fa85f64-5717-4562-b3fc-2c963f66afa6", solution: "mock" } },
                trustedDeviceToken: "mock"
            });
            
            if (res.data.externalResponse && res.data.externalResponse.twoFactorAuthEnabled) {
                setStep('2fa');
            } else if (res.data.token) {
                onLoginSuccess(res.data);
            }
        } catch (err) {
            setError((err.response && err.response.data && err.response.data.message) || (err.response && err.response.data) || 'Login failed. Please check your credentials.');
        } finally {
            setLoading(false);
        }
    };

    const handle2FA = async (e) => {
        e.preventDefault();
        setLoading(true);
        setError('');
        try {
            const res = await axios.post(`/api/auth/customer/2fa-check?email=${encodeURIComponent(email)}`, {
                code: twoFaCode
            });
            
            if (res.data.token) {
                onLoginSuccess(res.data);
            }
        } catch (err) {
            setError((err.response && err.response.data && err.response.data.message) || (err.response && err.response.data) || '2FA Verification failed.');
        } finally {
            setLoading(false);
        }
    };

    return (
        <div style={{ position: 'fixed', top: 0, left: 0, right: 0, bottom: 0, backgroundColor: 'rgba(0,0,0,0.75)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 9999, backdropFilter: 'blur(4px)' }}>
            <div className="card" style={{ width: '400px', position: 'relative', boxShadow: '0 20px 25px -5px rgba(0, 0, 0, 0.5)' }}>
                <button onClick={onClose} style={{ position: 'absolute', top: '15px', right: '15px', background: 'transparent', border: 'none', color: '#94a3b8', cursor: 'pointer', fontSize: '1.5rem', transition: 'color 0.2s' }} onMouseOver={e => e.target.style.color = '#fff'} onMouseOut={e => e.target.style.color = '#94a3b8'}>&times;</button>
                <h2 style={{ marginBottom: '1.5rem', textAlign: 'center', color: '#f8fafc' }}>{step === 'login' ? 'Customer Sign In' : 'Two-Factor Authentication'}</h2>
                
                {error && <div className="notification error" style={{ marginBottom: '1rem' }}>{error}</div>}
                
                {step === 'login' ? (
                    <form onSubmit={handleLogin}>
                        <div className="form-group">
                            <label>Email Address</label>
                            <input type="email" required value={email} onChange={e => setEmail(e.target.value)} placeholder="name@domain.com" />
                        </div>
                        <div className="form-group">
                            <label>Password</label>
                            <input type="password" required value={password} onChange={e => setPassword(e.target.value)} placeholder="••••••••" />
                        </div>
                        <button type="submit" className="btn-primary" disabled={loading} style={{ marginTop: '0.5rem' }}>
                            {loading ? <span className="loader" style={{ width: '16px', height: '16px' }}></span> : 'Sign In'}
                        </button>
                    </form>
                ) : (
                    <form onSubmit={handle2FA}>
                        <p style={{ color: '#94a3b8', fontSize: '0.9rem', marginBottom: '1.2rem', textAlign: 'center' }}>Please enter the 2FA code sent to your device.</p>
                        <div className="form-group">
                            <label>Authentication Code</label>
                            <input type="text" required value={twoFaCode} onChange={e => setTwoFaCode(e.target.value)} placeholder="Enter code..." style={{ letterSpacing: '2px', textAlign: 'center' }} />
                        </div>
                        <button type="submit" className="btn-primary" disabled={loading} style={{ marginTop: '0.5rem' }}>
                            {loading ? <span className="loader" style={{ width: '16px', height: '16px' }}></span> : 'Verify Code'}
                        </button>
                    </form>
                )}
            </div>
        </div>
    );
}

function FaqSection({ filterCategoryName, excludeCategoryName, title }) {
    const [categories, setCategories] = useState([]);
    const [sections, setSections] = useState([]);
    const [articles, setArticles] = useState([]);
    const [searchResults, setSearchResults] = useState(null);
    const [searchQuery, setSearchQuery] = useState('');
    const [loading, setLoading] = useState(false);
    const [sectionPages, setSectionPages] = useState({});
    const [expandedArticles, setExpandedArticles] = useState({});

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

    const loadArticles = async () => {
        setLoading(true);
        try {
            const response = await axios.get('/api/articles');
            if (response.data) {
                setCategories(response.data.categories || []);
                setSections(response.data.sections || []);
                setArticles(response.data.articles || []);
            }
        } catch (error) { console.error("Error loading articles", error); }
        finally { setLoading(false); }
    }

    const handleSearch = async (e) => {
        e.preventDefault();
        if (searchQuery.trim() === '') {
            setSearchResults(null);
            return;
        }
        setLoading(true);
        try {
            const response = await axios.get(`/api/articles/search?query=${encodeURIComponent(searchQuery)}`);
            if (response.data.results) { setSearchResults(response.data.results); }
        } catch (error) { console.error("Error searching articles", error); }
        finally { setLoading(false); }
    }

    const toggleArticle = (artId) => {
        setExpandedArticles(prev => ({ ...prev, [artId]: !prev[artId] }));
    }

    const getCategoryIcon = (categoryName) => {
        const name = categoryName.toLowerCase();
        if (name.includes('account')) return <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path><circle cx="12" cy="7" r="4"></circle></svg>;
        if (name.includes('onboarding') || name.includes('verification')) return <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16h16v-8"></path><path d="M14 2v4a2 2 0 0 0 2 2h4"></path><polyline points="9 15 11 17 15 13"></polyline></svg>;
        if (name.includes('deposit') || name.includes('withdrawal')) return <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="2" y="5" width="20" height="14" rx="2"></rect><line x1="2" y1="10" x2="22" y2="10"></line><path d="M7 15h.01"></path><path d="M11 15h2"></path></svg>;
        if (name.includes('trading') || name.includes('execution')) return <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="22 12 18 12 15 21 9 3 6 12 2 12"></polyline></svg>;
        if (name.includes('mt5') || name.includes('platform')) return <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="2" y="3" width="20" height="14" rx="2" ry="2"></rect><line x1="8" y1="21" x2="16" y2="21"></line><line x1="12" y1="17" x2="12" y2="21"></line></svg>;
        if (name.includes('client')) return <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path><circle cx="9" cy="7" r="4"></circle><path d="M23 21v-2a4 4 0 0 0-3-3.87"></path><path d="M16 3.13a4 4 0 0 1 0 7.75"></path></svg>;
        if (name.includes('fees') || name.includes('charge')) return <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"></circle><path d="M16 8h-6a2 2 0 1 0 0 4h4a2 2 0 1 1 0 4H8"></path><line x1="12" y1="18" x2="12" y2="22"></line><line x1="12" y1="2" x2="12" y2="6"></line></svg>;
        if (name.includes('partner')) return <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"></path><path d="M8 11h8"></path></svg>;
        if (name.includes('safet') || name.includes('privacy')) return <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect><path d="M7 11V7a5 5 0 0 1 10 0v4"></path></svg>;
        return <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="16" x2="12" y2="12"></line><line x1="12" y1="8" x2="12.01" y2="8"></line></svg>;
    }

    // Master function combining Sections and their internal localized questions exactly into ONE massive 2-Column Grid native layout
    const renderUnifiedGrid = () => {
        const allowedCategoryIds = categories.filter(cat => {
            if (filterCategoryName) return cat.name.toLowerCase().includes(filterCategoryName.toLowerCase());
            if (excludeCategoryName) return !cat.name.toLowerCase().includes(excludeCategoryName.toLowerCase());
            return true;
        }).map(c => c.id);

        // Iterate over SECTIONS instead of Categories to produce the distinct cards
        const filteredSections = sections.filter(sec => allowedCategoryIds.includes(sec.category_id));

        // Ensure "About Daman Markets" is strictly sorted to the premier left position
        filteredSections.sort((a, b) => {
            const isA = a.name.toLowerCase().includes('about');
            const isB = b.name.toLowerCase().includes('about');
            if (isA && !isB) return -1;
            if (!isA && isB) return 1;
            return 0;
        });

        if (filteredSections.length === 0) return <p>No knowledge base items found.</p>;

        return (
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, minmax(0, 1fr))', gap: '2rem', marginTop: '1.5rem' }}>
                {filteredSections.map(sec => {
                    const secArts = articles.filter(a => a.section_id === sec.id);

                    // Natively track localized pagination limits strictly per section native card
                    const currentPage = sectionPages[sec.id] || 0;
                    const totalPages = Math.ceil(secArts.length / 5);
                    const startIndex = currentPage * 5;
                    const visibleArts = secArts.slice(startIndex, startIndex + 5);

                    return (
                        <div key={sec.id} className="glass-card">
                            <div className="cat-header">
                                <div className="cat-icon">{getCategoryIcon(sec.name)}</div>
                                <h3 className="cat-title-text">{sec.name}</h3>
                            </div>
                            
                            <div className="articles-container" style={{ display: 'flex', flexDirection: 'column', flex: 1 }}>
                                {visibleArts.map(art => {
                                    const isExpanded = expandedArticles[art.id];
                                    return (
                                        <div key={art.id} className={`accordion-item ${isExpanded ? 'expanded' : ''}`}>
                                            <button 
                                                onClick={() => toggleArticle(art.id)}
                                                className="accordion-btn"
                                            >
                                                <span style={{ paddingRight: '1rem', lineHeight: '1.4' }}>{art.title}</span>
                                                <div className={`chevron ${isExpanded ? 'expanded' : ''}`}>
                                                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="9 18 15 12 9 6"></polyline></svg>
                                                </div>
                                            </button>
                                            <div className="accordion-content">
                                                <div dangerouslySetInnerHTML={{ __html: art.body }}></div>
                                            </div>
                                        </div>
                                    );
                                })}
                                
                                {secArts.length === 0 && (
                                    <p style={{color: '#94a3b8', fontSize: '0.95rem', padding: '1rem 0'}}>No articles found for this section.</p>
                                )}
                            </div>
                            
                            {totalPages > 1 && (
                                <div className="pagination-pills">
                                    <button 
                                        className="page-btn"
                                        onClick={() => setSectionPages(prev => ({ ...prev, [sec.id]: Math.max(0, currentPage - 1) }))}
                                        disabled={currentPage === 0}
                                    >
                                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><polyline points="15 18 9 12 15 6"></polyline></svg> Prev
                                    </button>
                                    <span style={{fontSize:'0.85rem', color:'#64748b', fontWeight: '500'}}>Pg {currentPage + 1} / {totalPages}</span>
                                    <button 
                                        className="page-btn"
                                        onClick={() => setSectionPages(prev => ({ ...prev, [sec.id]: Math.min(totalPages - 1, currentPage + 1) }))}
                                        disabled={currentPage === totalPages - 1}
                                    >
                                        Next <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><polyline points="9 18 15 12 9 6"></polyline></svg>
                                    </button>
                                </div>
                            )}
                        </div>
                    );
                })}
            </div>
        );
    }

    return (
        <React.Fragment>
            <div className="top-header">
                <div>
                    <div className="page-sub">{title || "Support Center"}</div>
                    <h1 className="page-main-title">How can we help you?</h1>
                </div>
                {!searchResults && (
                    <form className="global-search-bar" onSubmit={handleSearch}>
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><circle cx="11" cy="11" r="8"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line></svg>
                        <input type="text" placeholder="Search FAQ, articles, topics..." value={searchQuery} onChange={(e) => setSearchQuery(e.target.value)} />
                    </form>
                )}
            </div>

            {loading ? <div className="loader"></div> : (
                searchResults ? (
                    <div className="article-list">
                        <h3 style={{ marginBottom: '1rem', color: '#94a3b8' }}>
                            Search Results
                            <button onClick={() => { setSearchResults(null); setSearchQuery(''); }} style={{ background: 'none', border: 'none', color: '#3b82f6', marginLeft: '1rem', cursor: 'pointer' }}>(Clear Search)</button>
                        </h3>
                        {searchResults.length > 0 ? searchResults.map(article => {
                            const isExpanded = expandedArticles[article.id];
                            return (
                                <div key={article.id} style={{ backgroundColor: '#141b2d', borderRadius: '8px', border: '1px solid #1e293b', overflow: 'hidden' }}>
                                    <button
                                        onClick={() => toggleArticle(article.id)}
                                        style={{ width: '100%', textAlign: 'left', padding: '1.2rem', background: 'transparent', border: 'none', color: '#fff', fontSize: '1.1rem', fontWeight: '500', cursor: 'pointer', display: 'flex', justifyContent: 'space-between' }}
                                    >
                                        <span>{article.title}</span>
                                        <span style={{ color: '#3b82f6', fontWeight: 'bold' }}>{isExpanded ? '−' : '+'}</span>
                                    </button>
                                    {isExpanded && (
                                        <div style={{ padding: '0 1.2rem 1.5rem 1.2rem', color: '#cbd5e1', lineHeight: '1.6' }} dangerouslySetInnerHTML={{ __html: article.body }}></div>
                                    )}
                                </div>
                            );
                        }) : <p>No articles match your search.</p>}
                    </div>
                ) : (
                    renderUnifiedGrid()
                )
            )}
        </React.Fragment>
    );
}

function SubmitTicketSection() {
    const [formData, setFormData] = useState({ subject: '', description: '', email: '' });
    const [status, setStatus] = useState({ type: '', message: '' });
    const [loading, setLoading] = useState(false);

    const handleSubmit = async (e) => {
        e.preventDefault();
        setLoading(true);
        setStatus({ type: '', message: '' });

        try {
            const ticketPayload = {
                ticket: {
                    subject: formData.subject,
                    comment: { body: formData.description },
                    requester: { name: formData.email.split('@')[0], email: formData.email }
                }
            };
            await axios.post('/api/tickets', ticketPayload);
            setStatus({ type: 'success', message: 'Ticket submitted successfully!' });
            setFormData({ subject: '', description: '', email: '' });
        } catch (error) {
            console.error(error);
            setStatus({ type: 'error', message: 'Failed to submit ticket. Please try again.' });
        } finally {
            setLoading(false);
        }
    };

    return (
        <div className="card" style={{ maxWidth: '1000px', margin: '0 auto', width: '100%' }}>
            <h2 style={{ marginBottom: '1.5rem', textAlign: 'center' }}>Submit a Support Ticket</h2>

            {status.message && (
                <div className={`notification ${status.type}`}>
                    {status.message}
                </div>
            )}

            <form onSubmit={handleSubmit}>
                <div className="form-group">
                    <label>Email Address</label>
                    <input
                        type="email"
                        required
                        value={formData.email}
                        onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                    />
                </div>
                <div className="form-group">
                    <label>Subject</label>
                    <input
                        type="text"
                        required
                        value={formData.subject}
                        onChange={(e) => setFormData({ ...formData, subject: e.target.value })}
                    />
                </div>
                <div className="form-group">
                    <label>Description</label>
                    <textarea
                        required
                        rows="5"
                        value={formData.description}
                        onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                    ></textarea>
                </div>
                <button type="submit" className="btn-primary" disabled={loading}>
                    {loading ? <span className="loader" style={{ width: '16px', height: '16px' }}></span> : 'Submit Ticket'}
                </button>
            </form>
        </div>
    );
}

function MyTicketsSection({ customerAuth }) {
    const email = customerAuth ? customerAuth.email : '';
    const [tickets, setTickets] = useState([]);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        const loadTickets = async () => {
            setLoading(true);
            try {
                const response = await axios.get(`/api/tickets/user/${encodeURIComponent(email)}`, {
                    headers: { 'Authorization': `Bearer ${customerAuth.token}` }
                });
                if (response.data.results) {
                    setTickets(response.data.results);
                }
            } catch (error) {
                console.error("Error loading tickets", error);
            } finally {
                setLoading(false);
            }
        };
        loadTickets();
    }, [email, customerAuth.token]);
    return (
        <div className="card">
            <h2 style={{ marginBottom: '1rem' }}>My Tickets</h2>

            {loading ? <div className="loader"></div> : (
                <div className="ticket-list">
                    <h3 style={{ marginBottom: '1rem', fontSize: '1.25rem' }}>Tickets for {email}</h3>
                        {tickets.length > 0 ? (
                            <div style={{ display: 'flex', flexDirection: 'column' }}>
                                {tickets.map(ticket => (
                                    <div key={ticket.id} className="ticket-item">
                                        <div>
                                            <div className="ticket-subject">#{ticket.id} - {ticket.subject}</div>
                                            <div className="ticket-meta">Created at {new Date(ticket.created_at).toLocaleDateString()}</div>
                                        </div>
                                        <div className={`ticket-status status-${ticket.status}`}>
                                            {ticket.status}
                                        </div>
                                    </div>
                                ))}
                            </div>
                        ) : (
                            <p>No tickets found for this email address.</p>
                        )}
                </div>
            )}
        </div>
    );
}

function App() {
    const [activeTab, setActiveTab] = useState('faq');
    const [showLoginModal, setShowLoginModal] = useState(false);
    const [customerAuth, setCustomerAuth] = useState(() => {
        try {
            const saved = localStorage.getItem('customerAuth');
            return saved ? JSON.parse(saved) : null;
        } catch (e) {
            console.error("Failed to parse customerAuth from localStorage", e);
            localStorage.removeItem('customerAuth');
            return null;
        }
    });

    const handleLoginSuccess = (authData) => {
        setCustomerAuth(authData);
        localStorage.setItem('customerAuth', JSON.stringify(authData));
        setShowLoginModal(false);
        if (window.damanChatLogin) {
            window.damanChatLogin(authData);
        }
    };

    const handleLogout = () => {
        setCustomerAuth(null);
        localStorage.removeItem('customerAuth');
        axios.post('/api/auth/customer/logout', {}).catch(() => {});
        if (window.damanChatLogout) {
            window.damanChatLogout();
        }
    };

    return (
        <div className="app-container">
            {showLoginModal && <CustomerLoginModal onClose={() => setShowLoginModal(false)} onLoginSuccess={handleLoginSuccess} />}
            <aside className="sidebar">
                <div className="sidebar-logo" style={{ padding: '0', marginBottom: '1.5rem', marginTop: '0' }}>
                    <img src="/logo.png" alt="Daman Markets Support Center" style={{ width: '100%', maxHeight: '150px', objectFit: 'contain', borderRadius: '12px', backgroundColor: '#ffffff', padding: '2px' }} />
                </div>
                <nav className="sidebar-nav">
                    <button className={`nav-item ${activeTab === 'faq' ? 'active' : ''}`} onClick={() => setActiveTab('faq')}>
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="3" width="7" height="7"></rect><rect x="14" y="3" width="7" height="7"></rect><rect x="14" y="14" width="7" height="7"></rect><rect x="3" y="14" width="7" height="7"></rect></svg>
                        Support Center
                    </button>
                    <button className={`nav-item ${activeTab === 'submit' ? 'active' : ''}`} onClick={() => setActiveTab('submit')}>
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16h16v-8"></path><path d="M14 2v4a2 2 0 0 0 2 2h4"></path><path d="M16 13H8"></path><path d="M16 17H8"></path><path d="M10 9H8"></path></svg>
                        Submit Ticket
                    </button>
                    {customerAuth && (
                        <button className={`nav-item ${activeTab === 'integration' ? 'active' : ''}`} onClick={() => setActiveTab('integration')}>
                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="16 18 22 12 16 6"></polyline><polyline points="8 6 2 12 8 18"></polyline></svg>
                            Integration Guide
                        </button>
                    )}
                </nav>
            </aside>

            <main className="main-content">
                <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: '1.5rem', borderBottom: '1px solid #1e293b', paddingBottom: '1rem' }}>
                    {customerAuth ? (
                        <div style={{ display: 'flex', alignItems: 'center', gap: '1rem', color: '#cbd5e1' }}>
                            <span style={{ fontSize: '0.95rem' }}>Signed in as <b style={{ color: '#fff' }}>{customerAuth.email}</b></span>
                            <button className="btn-primary" style={{ padding: '0.4rem 1rem', width: 'auto', background: 'rgba(59, 130, 246, 0.1)', color: '#3b82f6', border: '1px solid rgba(59, 130, 246, 0.3)' }} onClick={handleLogout}>Logout</button>
                        </div>
                    ) : (
                        <button className="btn-primary" style={{ padding: '0.5rem 1.2rem', width: 'auto', display: 'flex', alignItems: 'center', gap: '0.5rem' }} onClick={() => setShowLoginModal(true)}>
                            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4"></path><polyline points="10 17 15 12 10 7"></polyline><line x1="15" y1="12" x2="3" y2="12"></line></svg>
                            Customer Sign In
                        </button>
                    )}
                </div>

                {activeTab === 'faq' && <FaqSection title="Support Center" />}

                {activeTab === 'submit' && (
                    <div style={{ display: 'grid', gridTemplateColumns: customerAuth ? 'repeat(2, minmax(0, 1fr))' : '1fr', gap: '2rem', alignItems: 'start' }}>
                        <SubmitTicketSection />
                        {customerAuth && <MyTicketsSection customerAuth={customerAuth} />}
                    </div>
                )}

                {activeTab === 'integration' && customerAuth && (
                    <div className="card" style={{ height: 'calc(100vh - 200px)', padding: '0', overflow: 'hidden' }}>
                        <iframe 
                            src="/widget-integration.html" 
                            style={{ width: '100%', height: '100%', border: 'none', borderRadius: '12px' }}
                            title="Integration Guide"
                        ></iframe>
                    </div>
                )}
            </main>
        </div>
    );
}

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