const { useState, useRef, useEffect } = React;

const DownloadButton = ({ label, targetUrl, activeTab }) => {
    const [status, setStatus] = useState(label);
    const [progress, setProgress] = useState(0);
    const [disabled, setDisabled] = useState(false);

    const handleDownload = async () => {
        if (!targetUrl) return;
        setDisabled(true); setStatus("Processing... 0%"); setProgress(5);
        try {
            let res;
            if (targetUrl.startsWith('data:')) {
                res = await fetch(targetUrl);
            } else {
                try {
                    res = await fetch(targetUrl, { referrerPolicy: 'no-referrer' });
                    if (!res.ok) throw new Error("CORS");
                } catch (e) {
                    res = await fetch(`https://api.allorigins.win/raw?url=${encodeURIComponent(targetUrl)}`);
                    if (!res.ok) throw new Error("Proxy");
                }
            }
            
            const total = parseInt(res.headers.get('content-length')) || 0;
            let loaded = 0; const chunks = []; const reader = res.body.getReader();

            while (true) {
                const { done, value } = await reader.read();
                if (done) break;
                chunks.push(value); loaded += value.length;
                if (total) {
                    const p = Math.round((loaded / total) * 100);
                    setProgress(p); setStatus(`Processing... ${p}%`);
                } else {
                    setStatus(`Processing... ${(loaded / 1048576).toFixed(1)} MB`);
                }
            }
            
            setStatus("Processing..."); setProgress(95);
            let mimeType = activeTab === 'video' ? 'video/mp4' : 'image/jpeg';
            const blob = new Blob(chunks, { type: mimeType });
            const blobUrl = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = blobUrl;
            let ext = activeTab === 'video' ? 'mp4' : 'jpg';
            a.download = `ToolsEnhance_By_Jexk_${Date.now()}.${ext}`;
            document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(blobUrl);
            
            setStatus("Selesai"); setProgress(100);
        } catch (err) {
            setStatus("Processing..."); window.open(targetUrl, '_blank');
        } finally {
            setTimeout(() => { setStatus(label); setProgress(0); setDisabled(false); }, 3000);
        }
    };

    return (
        <button disabled={disabled} onClick={handleDownload} className="btn-glow w-full py-4 rounded-xl text-[13px] font-bold tracking-wide relative overflow-hidden capitalize-text flex items-center justify-center gap-2">
            <div className="absolute top-0 left-0 h-full bg-black/10 transition-all duration-300" style={{ width: `${progress}%` }}></div>
            <span className="relative z-10 flex items-center gap-2"><i className="fa-solid fa-download"></i> {status}</span>
        </button>
    );
};

const App = () => {
    const [activeTab, setActiveTab] = useState('photo');
    const [resultMedia, setResultMedia] = useState(null);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState('');
    const [statusText, setStatusText] = useState('Processing...');
    const pollRef = useRef(null);

    useEffect(() => { return () => { if (pollRef.current) clearInterval(pollRef.current); }; }, []);

    const handleFileUpload = async (e) => {
        const file = e.target.files[0];
        if (!file) return;
        setLoading(true); setError(''); setResultMedia(null); setStatusText('Processing...');

        try {
            if (activeTab === 'photo') {
                const reader = new FileReader();
                reader.readAsDataURL(file);
                reader.onload = async (event) => {
                    try {
                        const imageBase64 = event.target.result;
                        const res = await fetch('/api/enhance', {
                            method: 'POST', headers: { 'Content-Type': 'application/json' },
                            body: JSON.stringify({ imageBase64 }) 
                        }).then(r => r.json());
                        
                        if (res.error) throw new Error(res.error);
                        setResultMedia(res.output); setLoading(false);
                    } catch (err) { setError(err.message); setLoading(false); }
                };
            } else {
                const init = await fetch('/api/video', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'init' }) }).then(r => r.json());
                if (init.error) throw new Error(init.error);
                
                const upload = await fetch(init.uploadUrl, { method: 'PUT', headers: { 'Content-Type': 'video/mp4' }, body: file });
                if (!upload.ok) throw new Error('Upload Video Gagal');

                const process = await fetch('/api/video', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'process', objectName: init.objectName, productSerial: init.productSerial }) }).then(r => r.json());
                if (process.error) throw new Error(process.error);
                
                startPolling(process.jobId, init.productSerial);
            }
        } catch (err) { setError(err.message); setLoading(false); }
    };

    const startPolling = (jobId, serial) => {
        setStatusText('Processing...');
        pollRef.current = setInterval(async () => {
            try {
                const res = await fetch('/api/video', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'status', jobId, productSerial: serial }) }).then(r => r.json());
                if (res.error) throw new Error(res.error);
                
                if (res.code === 100000 && res.result?.output_url) {
                    clearInterval(pollRef.current); setResultMedia(res.result.output_url); setLoading(false);
                } else if (res.code === 300010 || (res.code === 100000 && !res.result?.output_url)) {
                    setStatusText('Processing...');
                } else {
                    clearInterval(pollRef.current); 
                    const serverReason = res.msg || res.message?.id || res.message?.en || JSON.stringify(res.message || res);
                    throw new Error(`Ditolak Server: ${serverReason}`);
                }
            } catch (err) { clearInterval(pollRef.current); setError(err.message); setLoading(false); }
        }, 10000); 
    };

    return (
        <>
            <video autoPlay loop muted playsInline id="bg-video">
                <source src="https://jexkcdn-production.up.railway.app/file/jexk-cdn/1778159727798-VID-20260507-WA0091.mp4" type="video/mp4" />
            </video>
            <div className="video-overlay"></div>

            <div className="w-full mt-6 md:mt-12 animate-fade-in-up relative z-10 px-4">
                <div className="text-center mb-10">
                    <div className="inline-block px-4 py-2 bg-white/5 border border-white/10 rounded-full text-[10px] font-semibold tracking-widest mb-6 capitalize-text shadow-xl backdrop-blur-sm">
                        Enhance Utility
                    </div>
                    <h1 className="text-4xl md:text-6xl font-extrabold mb-4 tracking-tight shimmer-text capitalize-text">
                        Tools Enhance
                    </h1>
                    <p className="text-gray-400 text-sm font-medium tracking-wide capitalize-text stagger-1">
                        Pixel Enhance
                    </p>
                </div>

                <div className="relative flex p-1.5 bg-white/5 border border-white/10 rounded-[1.5rem] w-fit mx-auto mb-10 backdrop-blur-xl stagger-1">
                    <div className="absolute top-1.5 bottom-1.5 transition-all duration-500 ease-[cubic-bezier(0.34,1.56,0.64,1)] z-0 rounded-2xl btn-glow"
                         style={{ width: 'calc(50% - 9px)', left: activeTab === 'photo' ? '6px' : 'calc(50% + 3px)' }}></div>
                    <button onClick={() => { setActiveTab('photo'); setError(''); setResultMedia(null); }} 
                            className={`relative z-10 px-10 py-3 rounded-2xl text-[13px] font-bold tracking-wide transition-all duration-500 ${activeTab === 'photo' ? 'text-black' : 'text-gray-500 hover:text-gray-300'} capitalize-text`}>
                        <i className="fa-solid fa-image mr-2"></i> Photo
                    </button>
                    <button onClick={() => { setActiveTab('video'); setError(''); setResultMedia(null); }} 
                            className={`relative z-10 px-10 py-3 rounded-2xl text-[13px] font-bold tracking-wide transition-all duration-500 ${activeTab === 'video' ? 'text-black' : 'text-gray-500 hover:text-gray-300'} capitalize-text`}>
                        <i className="fa-solid fa-film mr-2"></i> Video
                    </button>
                </div>

                {!loading && !resultMedia && (
                    <div className="glass-card max-w-2xl mx-auto p-6 md:p-10 rounded-[2rem] mb-8 text-center shine-effect stagger-1">
                        <label className="block w-full rounded-2xl py-12 px-6 cursor-pointer hover:bg-white/5 transition-all border-2 border-dashed border-white/10">
                            <i className={`fa-solid ${activeTab === 'photo' ? 'fa-image' : 'fa-film'} text-4xl mb-4 text-gray-400`}></i>
                            <h3 className="text-xl font-bold mb-2 capitalize-text text-white">Upload {activeTab === 'photo' ? 'Photo' : 'Video'}</h3>
                            <input type="file" className="hidden" onChange={handleFileUpload} accept={activeTab === 'photo' ? 'image/*' : 'video/*'} />
                        </label>
                    </div>
                )}

                {loading && (
                    <div className="glass-card max-w-2xl mx-auto p-10 rounded-[2rem] mb-8 flex flex-col items-center justify-center shine-effect stagger-1">
                        <div className="loader mb-6"></div>
                        <p className="text-white font-medium shimmer-text capitalize-text text-center">{statusText}</p>
                    </div>
                )}

                {error && (
                    <div className="max-w-2xl mx-auto bg-red-500/10 border border-red-500/30 text-red-400 p-5 rounded-2xl mb-6 text-sm text-left animate-fade-in-up backdrop-blur-md stagger-2">
                        <strong className="font-semibold capitalize-text">Information:</strong> <br/> 
                        <span className="normal-text">{error}</span>
                    </div>
                )}

                {resultMedia && !loading && (
                    <div className="glass-card max-w-2xl mx-auto p-5 md:p-8 rounded-[2rem] text-center animate-fade-in-up shine-effect stagger-2">
                        <div className="w-full max-w-2xl mx-auto rounded-2xl overflow-hidden bg-black border border-white/10 relative mb-8 media-float pulse-glow">
                            {activeTab === 'video' ? (
                                <video src={resultMedia} autoPlay loop muted playsInline className="w-full h-auto object-cover opacity-90 hover:opacity-100 transition-opacity duration-500" />
                            ) : (
                                <img src={resultMedia} className="w-full h-auto object-cover opacity-90 hover:opacity-100 transition-opacity duration-500" />
                            )}
                            <div className="absolute inset-0 ring-1 ring-inset ring-white/10 rounded-2xl pointer-events-none"></div>
                        </div>
                        <div className="flex flex-col gap-3 max-w-sm mx-auto">
                            <DownloadButton 
                                label={activeTab === 'photo' ? 'Download Photo' : 'Download Video'} 
                                targetUrl={resultMedia} 
                                activeTab={activeTab} 
                            />
                            <button onClick={() => setResultMedia(null)} className="btn-dark w-full py-4 rounded-xl text-[13px] font-bold tracking-wide flex items-center justify-center gap-2 capitalize-text">
                                <i className="fa-solid fa-rotate-right"></i> Enhance Again
                            </button>
                        </div>
                    </div>
                )}

                <div className="mt-20 flex justify-center gap-4 animate-fade-in-up stagger-3">
                    <a href="https://wa.me/6285212645395" target="_blank" rel="noopener noreferrer" className="social-icon w-12 h-12 rounded-full border border-white/10 flex items-center justify-center text-gray-400 hover:bg-white hover:text-black backdrop-blur-md">
                        <i className="fa-brands fa-whatsapp text-lg"></i>
                    </a>
                    <a href="https://t.me/Jack_pinkman" target="_blank" rel="noopener noreferrer" className="social-icon w-12 h-12 rounded-full border border-white/10 flex items-center justify-center text-gray-400 hover:bg-white hover:text-black backdrop-blur-md">
                        <i className="fa-brands fa-telegram text-lg"></i>
                    </a>
                    <a href="https://github.com/jexkpinkman" target="_blank" rel="noopener noreferrer" className="social-icon w-12 h-12 rounded-full border border-white/10 flex items-center justify-center text-gray-400 hover:bg-white hover:text-black backdrop-blur-md">
                        <i className="fa-brands fa-github text-lg"></i>
                    </a>
                </div>
                
                <footer className="mt-6 py-6 text-gray-500 text-[11px] font-bold tracking-widest text-center capitalize-text w-full animate-fade-in-up stagger-3">
                    © Tools Enhance - <span className="text-white font-semibold normal-text">Powered By Jexk.</span>
                </footer>
            </div>
        </>
    );
};

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