const { useState, useEffect, useRef } = React;

const Navbar = ({ onOpenModal }) => {
    const [scrolled, setScrolled] = useState(false);

    useEffect(() => {
        const handleScroll = () => {
            setScrolled(window.scrollY > 50);
        };
        window.addEventListener('scroll', handleScroll);
        return () => window.removeEventListener('scroll', handleScroll);
    }, []);

    const handleScrollTo = (e, id) => {
        e.preventDefault();
        const element = document.getElementById(id);
        if (element) {
            element.scrollIntoView({ behavior: 'smooth', block: 'start' });
        }
    };

    return (
        <nav className={`navbar ${scrolled ? 'scrolled' : ''}`}>
            <div className="nav-content">
                <div className="logo-wrapper">
                    <img src="assets/logo.png" alt="Lemmly Logo" className="logo" />
                    <span className="brand-name">Lemmly</span>
                </div>
                <button onClick={onOpenModal} className="btn-primary">Prenotati Ora</button>
            </div>
        </nav>
    );
};

const NeuralMeshCanvas = () => {
    const canvasRef = useRef(null);

    useEffect(() => {
        const canvas = canvasRef.current;
        const ctx = canvas.getContext('2d');
        let animationFrameId;

        const resize = () => {
            const parent = canvas.parentElement;
            canvas.width = parent.clientWidth;
            canvas.height = parent.clientHeight;
        };
        window.addEventListener('resize', resize);
        resize();

        // Node properties
        const numNodes = 70;
        const nodes = [];
        
        for (let i = 0; i < numNodes; i++) {
            nodes.push({
                x: (Math.random() - 0.5) * 400,
                y: (Math.random() - 0.5) * 400,
                z: (Math.random() - 0.5) * 400,
                vx: (Math.random() - 0.5) * 0.5,
                vy: (Math.random() - 0.5) * 0.5,
                vz: (Math.random() - 0.5) * 0.5,
                color: Math.random() > 0.5 ? '#4F46E5' : '#3B82F6'
            });
        }

        let mouse = { x: 0, y: 0 };
        let targetRotateX = 0;
        let targetRotateY = 0;
        let currentRotateX = 0;
        let currentRotateY = 0;

        const handleMouseMove = (e) => {
            const rect = canvas.getBoundingClientRect();
            mouse.x = e.clientX - rect.left - canvas.width / 2;
            mouse.y = e.clientY - rect.top - canvas.height / 2;
            targetRotateY = mouse.x * 0.001;
            targetRotateX = mouse.y * 0.001;
        };
        
        canvas.addEventListener('mousemove', handleMouseMove);

        let time = 0;

        const draw = () => {
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            
            const centerX = canvas.width / 2;
            const centerY = canvas.height / 2;
            const fov = 350;

            time += 0.002;
            
            // Smooth mouse rotation interpolation
            currentRotateX += (targetRotateX - currentRotateX) * 0.05;
            currentRotateY += (targetRotateY - currentRotateY) * 0.05;

            // Global rotation
            const rotY = time + currentRotateY;
            const rotX = Math.PI / 8 + currentRotateX; // slight tilt

            // Update & Project Nodes
            const projectedNodes = [];

            nodes.forEach(node => {
                // Drift
                node.x += node.vx;
                node.y += node.vy;
                node.z += node.vz;

                // Bounce
                if (node.x > 200 || node.x < -200) node.vx *= -1;
                if (node.y > 200 || node.y < -200) node.vy *= -1;
                if (node.z > 200 || node.z < -200) node.vz *= -1;

                // Rotate Y
                let x1 = node.x * Math.cos(rotY) - node.z * Math.sin(rotY);
                let z1 = node.z * Math.cos(rotY) + node.x * Math.sin(rotY);
                let y1 = node.y;

                // Rotate X
                let y2 = y1 * Math.cos(rotX) - z1 * Math.sin(rotX);
                let z2 = z1 * Math.cos(rotX) + y1 * Math.sin(rotX);
                let x2 = x1;

                const scale = fov / (fov + z2 + 200);
                const screenX = centerX + x2 * scale;
                const screenY = centerY + y2 * scale;

                projectedNodes.push({
                    orig: node,
                    x: screenX,
                    y: screenY,
                    z: z2,
                    scale: scale,
                    color: node.color
                });
            });

            // Draw lines
            for (let i = 0; i < projectedNodes.length; i++) {
                for (let j = i + 1; j < projectedNodes.length; j++) {
                    const p1 = projectedNodes[i];
                    const p2 = projectedNodes[j];
                    
                    const dx = p1.orig.x - p2.orig.x;
                    const dy = p1.orig.y - p2.orig.y;
                    const dz = p1.orig.z - p2.orig.z;
                    const distSq = dx*dx + dy*dy + dz*dz;

                    // Connect if close in 3D space
                    if (distSq < 15000) {
                        const opacity = 1 - (distSq / 15000);
                        // Fade lines that go back into fog
                        const avgZ = (p1.z + p2.z) / 2;
                        const depthFade = Math.max(0.1, 1 - Math.max(0, avgZ) / 200);
                        
                        ctx.beginPath();
                        ctx.moveTo(p1.x, p1.y);
                        ctx.lineTo(p2.x, p2.y);
                        ctx.strokeStyle = `rgba(79, 70, 229, ${opacity * depthFade * 0.5})`;
                        ctx.lineWidth = 1.0 * ((p1.scale + p2.scale)/2);
                        ctx.stroke();
                    }
                }
            }

            // Draw nodes
            projectedNodes.sort((a, b) => b.z - a.z).forEach(p => {
                ctx.beginPath();
                ctx.arc(p.x, p.y, 4 * p.scale, 0, Math.PI * 2);
                ctx.fillStyle = p.color;
                
                const depthOp = Math.max(0, 1 - Math.max(0, p.z) / 200);
                ctx.globalAlpha = depthOp;
                
                ctx.shadowBlur = 10;
                ctx.shadowColor = p.color;
                ctx.fill();
                ctx.fill(); // double fill for solid center
                ctx.shadowBlur = 0;
                ctx.globalAlpha = 1;
            });

            animationFrameId = window.requestAnimationFrame(draw);
        };

        draw();

        return () => {
            window.removeEventListener('resize', resize);
            canvas.removeEventListener('mousemove', handleMouseMove);
            window.cancelAnimationFrame(animationFrameId);
        };
    }, []);

    return <canvas ref={canvasRef} style={{ width: '100%', height: '100%', minHeight:'300px', display: 'block', cursor: 'crosshair' }} />;
};

const Countdown = () => {
    const calculateTimeLeft = () => {
        const difference = +new Date("2026-04-25T10:00:00") - +new Date();
        let timeLeft = {};

        if (difference > 0) {
            timeLeft = {
                giorni: Math.floor(difference / (1000 * 60 * 60 * 24)),
                ore: Math.floor((difference / (1000 * 60 * 60)) % 24),
                minuti: Math.floor((difference / 1000 / 60) % 60),
                secondi: Math.floor((difference / 1000) % 60)
            };
        }
        return timeLeft;
    };

    const [timeLeft, setTimeLeft] = useState(calculateTimeLeft());

    useEffect(() => {
        const timer = setTimeout(() => {
            setTimeLeft(calculateTimeLeft());
        }, 1000);
        return () => clearTimeout(timer);
    });

    const timerComponents = [];

    Object.keys(timeLeft).forEach((interval) => {
        timerComponents.push(
            <div className="countdown-item" key={interval}>
                <span className="countdown-value">{timeLeft[interval].toString().padStart(2, '0')}</span>
                <span className="countdown-label">{interval}</span>
            </div>
        );
    });

    return (
        <div className="countdown-container">
            <div className="countdown-header">Lancio per la Libertà Digitale — 25 Aprile</div>
            <div className="countdown-timer">
                {timerComponents.length ? timerComponents : <span>Lancio in corso!</span>}
            </div>
            <p style={{fontSize: '0.8rem', color: 'var(--clr-text-muted)', marginTop: '0.8rem', opacity: 0.8}}>
                Privacy assoluta per la tua libertà professionale.
            </p>
        </div>
    );
};

const HeroSection = ({ onOpenModal }) => {
    const handleScrollTo = (e, id) => {
        e.preventDefault();
        const element = document.getElementById(id);
        if (element) {
            element.scrollIntoView({ behavior: 'smooth', block: 'start' });
        }
    };

    return (
        <header className="hero-section">
            <div className="hero-content">
                <div className="badge">Esclusiva macOS</div>
                <h1 className="hero-title">
                    L'App definitiva per <br /> <span className="text-gradient">Ingegneri Brillanti.</span>
                </h1>
                <p className="hero-subtitle">
                    Velocità estrema, zero distrazioni. Ottimizzata nativamente per Apple Silicon e progettata per farti lavorare 100% offline.
                </p>
                
                <Countdown />

                <div className="hero-actions">
                    <a href="#features" onClick={(e) => handleScrollTo(e, 'features')} className="btn-secondary">Scopri i dettagli</a>
                    <button onClick={onOpenModal} className="btn-primary">Prenotati Ora</button>
                </div>
            </div>
            <div className="hero-visual">
                <div className="mockup-frame">
                    <div className="mockup-screen">
                        <NeuralMeshCanvas />
                    </div>
                </div>
            </div>
        </header>
    );
};

const FeatureCard = ({ iconPath, title, description }) => {
    const cardRef = useRef(null);

    const handleMouseMove = (e) => {
        const card = cardRef.current;
        if (!card) return;
        const rect = card.getBoundingClientRect();
        const x = e.clientX - rect.left;
        const y = e.clientY - rect.top;
        const centerX = rect.width / 2;
        const centerY = rect.height / 2;
        const rotateX = ((y - centerY) / centerY) * -5;
        const rotateY = ((x - centerX) / centerX) * 5;
        card.style.transform = `perspective(1000px) rotateX(${rotateX}deg) rotateY(${rotateY}deg) translateY(-8px)`;
    };

    const handleMouseLeave = () => {
        const card = cardRef.current;
        if (!card) return;
        card.style.transform = `perspective(1000px) rotateX(0) rotateY(0) translateY(0)`;
    };

    return (
        <div 
            className="feature-card" 
            ref={cardRef} 
            onMouseMove={handleMouseMove} 
            onMouseLeave={handleMouseLeave}
        >
            <div className="icon-wrapper">
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" className="feature-icon">
                    <path d={iconPath} stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
                </svg>
            </div>
            <h3>{title}</h3>
            <p>{description}</p>
        </div>
    );
};

const FeaturesSection = () => {
    return (
        <section id="features" className="features-section">
            <h2 className="section-title">Ripensa la tua <span className="text-gradient">Metodologia</span></h2>
            <div className="features-grid">
                <FeatureCard 
                    iconPath="M12 21a9 9 0 100-18 9 9 0 000 18zM12 11V7M12 15h.01"
                    title="100% Offline Base"
                    description="I tuoi progetti, la tua conoscenza. Tutto viaggia in locale per garantire privacy assoluta e zero lag. Niente dipendenze cloud."
                />
                <FeatureCard 
                    iconPath="M21 12l-9 9-9-9M21 4l-9 9-9-9"
                    title="Ottimizzazione vDSP"
                    description="Architettura studiata per massimizzare le prestazioni hardware su Apple Silicon. Analisi dati veloci come il pensiero."
                />
                <FeatureCard 
                    iconPath="M2 12h4l3-9 5 18 3-9h5"
                    title="Nata per l'Ingegneria"
                    description="Tool specifici, workspace split-view e debouncing integrato per supportare sessioni intensive senza cali di memoria."
                />
            </div>
        </section>
    );
};

const ReservationModal = ({ isOpen, onClose }) => {
    const [formData, setFormData] = useState({
        name: '',
        email: '',
        studyCourse: ''
    });

    const handleSubmit = (e) => {
        e.preventDefault();
        console.log('Reservation Submitted:', formData);
        alert('Richiesta inviata con successo! Verrai ricontattato entro il lancio.');
        onClose();
    };

    return (
        <div className={`modal-overlay ${isOpen ? 'active' : ''}`} onClick={onClose}>
            <div className="modal-container" onClick={e => e.stopPropagation()}>
                <button className="modal-close" onClick={onClose}>
                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                        <path d="M18 6L6 18M6 6l12 12" />
                    </svg>
                </button>
                
                <div className="modal-header">
                    <span className="modal-subtitle">Posti Limitati</span>
                    <h2 className="modal-title text-gradient">Prenota Lemmly</h2>
                </div>

                <form className="reservation-form" onSubmit={handleSubmit}>
                    <div className="form-group">
                        <label>Nome Completo</label>
                        <input 
                            type="text" 
                            required 
                            className="form-input" 
                            placeholder="Mario Rossi"
                            value={formData.name}
                            onChange={e => setFormData({...formData, name: e.target.value})}
                        />
                    </div>
                    <div className="form-group">
                        <label>Email Universitaria</label>
                        <input 
                            type="email" 
                            required 
                            className="form-input" 
                            placeholder="mario.rossi@studenti.uni.it"
                            value={formData.email}
                            onChange={e => setFormData({...formData, email: e.target.value})}
                        />
                    </div>
                    <div className="form-group">
                        <label>Indirizzo di Studi</label>
                        <input 
                            type="text" 
                            required 
                            className="form-input" 
                            placeholder="Ingegneria Meccanica"
                            value={formData.studyCourse}
                            onChange={e => setFormData({...formData, studyCourse: e.target.value})}
                        />
                    </div>
                    <button type="submit" className="btn-primary" style={{marginTop: '1rem'}}>Conferma Prenotazione</button>
                </form>

                <div className="modal-footer-info">
                    <span className="highlight-info">Free per 3 mesi con system personalizzato</span>
                    <span className="release-info">Release entro 14 giorni</span>
                    <div style={{marginTop: '1rem', fontSize: '0.8rem'}}>
                        Problemi con la prenotazione? <a href="mailto:info@lemmly.it" style={{color: 'var(--clr-brand-2)', textDecoration: 'none'}}>Contattaci</a>
                    </div>
                </div>
            </div>
        </div>
    );
};

const ComingSoonSection = () => {
    return (
        <section id="coming-soon" className="coming-soon-section">
            <div className="glass-card full-width">
                <div className="teaser-content">
                    <span className="badge neon-badge">Coming Soon</span>
                    <h2 className="section-title">Oltre i confini dell'Ingegneria.</h2>
                    <p className="teaser-text">
                        Stiamo estendendo la potenza di Lemmly a nuove discipline. Presto disponibile l'ecosistema dedicato a: <br/>
                        <strong>Scienze Matematiche</strong>, <strong>Fisiche</strong>, <strong>Naturali</strong> e <strong>Biologia</strong>.
                        <br/><br/>
                        Hai domande? Scrivici a <a href="mailto:info@lemmly.it" className="text-gradient" style={{fontWeight: 600, textDecoration: 'none'}}>info@lemmly.it</a>
                    </p>
                    <div className="notify-form">
                        <input type="email" placeholder="La tua email universitaria" className="glass-input" />
                        <button className="btn-primary">Avvisami al lancio!</button>
                    </div>
                </div>
            </div>
        </section>
    );
};

const Footer = () => {
    return (
        <footer className="footer" id="contact">
            <div className="footer-content">
                <div className="footer-brand">
                    <img src="assets/logo.png" alt="Lemmly Logo" className="logo-small" />
                    <span>Lemmly © 2026 — <a href="mailto:info@lemmly.it" className="footer-email">info@lemmly.it</a></span>
                </div>
                <div className="footer-links">
                    <a href="#">Privacy Policy</a>
                    <a href="#">Terms of Service</a>
                    <a href="mailto:info@lemmly.it">Supporto</a>
                </div>
            </div>
        </footer>
    );
};

const CookieConsent = () => {
    const [isVisible, setIsVisible] = useState(false);

    useEffect(() => {
        const consent = localStorage.getItem('lemmly-cookie-consent');
        if (!consent) {
            // Delay appearance for better UX
            const timer = setTimeout(() => setIsVisible(true), 1500);
            return () => clearTimeout(timer);
        }
    }, []);

    const handleAccept = () => {
        localStorage.setItem('lemmly-cookie-consent', 'accepted');
        setIsVisible(false);
    };

    const handleDecline = () => {
        localStorage.setItem('lemmly-cookie-consent', 'declined');
        setIsVisible(false);
    };

    if (!isVisible) return null;

    return (
        <div className="cookie-banner-wrapper">
            <div className="cookie-banner">
                <div className="cookie-content">
                    <div className="cookie-icon">
                        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                            <path d="M12 2a10 10 0 1 0 10 10 4 4 0 0 1-5-5 4 4 0 0 1-5-5" />
                            <path d="M8.5 8.5v.01M16 15.5v.01M12 12v.01M11 17v.01M7 13v.01" />
                        </svg>
                    </div>
                    <div className="cookie-text">
                        <h4>Gestione Cookie</h4>
                        <p>Utilizziamo i cookie per migliorare la tua esperienza su Lemmly. Proseguendo accetti la nostra <a href="#">Cookie Policy</a>.</p>
                    </div>
                </div>
                <div className="cookie-actions">
                    <button onClick={handleDecline} className="btn-cookie-secondary">Rifiuta</button>
                    <button onClick={handleAccept} className="btn-cookie-primary">Accetta Tutto</button>
                </div>
            </div>
        </div>
    );
};

const App = () => {
    const [isModalOpen, setIsModalOpen] = useState(false);

    const openModal = () => setIsModalOpen(true);
    const closeModal = () => setIsModalOpen(false);

    return (
        <>
            <div className="blob-bg"></div>
            <Navbar onOpenModal={openModal} />
            <main>
                <HeroSection onOpenModal={openModal} />
                <FeaturesSection />
                <ComingSoonSection />
            </main>
            <Footer />
            <ReservationModal isOpen={isModalOpen} onClose={closeModal} />
            <CookieConsent />
        </>
    );
};

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