/**
 * @license
 * SPDX-License-Identifier: Apache-2.0
 */

import React, { useState } from 'react';
import { 
  ArrowRight, 
  Bell, 
  ShieldCheck, 
  Instagram,
  Facebook,
  Wrench,
  Boxes,
  Zap,
  ChevronRight,
  Cpu,
  Globe
} from 'lucide-react';

const TikTok = ({ className }: { className?: string }) => (
  <svg 
    xmlns="http://www.w3.org/2000/svg" 
    width="16" 
    height="16" 
    viewBox="0 0 24 24" 
    fill="none" 
    stroke="currentColor" 
    strokeWidth="2" 
    strokeLinecap="round" 
    strokeLinejoin="round" 
    className={className}
  >
    <path d="M9 12a4 4 0 1 0 4 4V4a5 5 0 0 0 5 5" />
  </svg>
);

import { motion, AnimatePresence } from 'motion/react';
import { db } from './lib/firebase';
import { doc, setDoc, serverTimestamp } from 'firebase/firestore';
import { Spinner, ProgressBar } from './components/ui/Loading';

export default function App() {
  const [email, setEmail] = useState('');
  const [name, setName] = useState('');
  const [subscribed, setSubscribed] = useState(false);
  const [loading, setLoading] = useState(false);
  const [nameError, setNameError] = useState("");
  const [emailError, setEmailError] = useState("");
  const [errorMsg, setErrorMsg] = useState("");

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setNameError("");
    setEmailError("");
    setErrorMsg("");

    let isValid = true;
    if (!name.trim()) {
      setNameError("Operator Identification Required");
      isValid = false;
    }
    if (!email.trim() || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
      setEmailError("Valid Comms Line Required");
      isValid = false;
    }

    if (!isValid) return;

    setLoading(true);

    try {
      const entryId = crypto.randomUUID();
      await setDoc(doc(db, "waitlist", entryId), {
        name,
        email,
        createdAt: serverTimestamp()
      });

      let endpoint = '/api/waitlist';
      if (window.location.hostname !== 'localhost' && !window.location.hostname.includes('run.app')) {
        endpoint = './index.php'; 
      }

      const res = await fetch(endpoint, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name, email }),
      });

      if (!res.ok) throw new Error('Network Protocol Interrupted');

      setSubscribed(true);
      setEmail('');
      setName('');
    } catch (err: any) {
      setErrorMsg(err.message || 'Transmission Error');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen grid grid-cols-1 lg:grid-cols-2 bg-background-light selection:bg-primary/20">
      <ProgressBar isFetching={loading} />

      {/* LEFT PANE: Editorial Hero */}
      <section className="relative flex flex-col justify-between p-8 lg:p-20 overflow-hidden border-r brutal-border">
        {/* Nav Rail */}
        <div className="absolute top-0 right-0 h-full hidden lg:flex flex-col justify-center gap-12 pointer-events-none">
          <span className="rail-text">PROTOCOL V.2026.01</span>
          <span className="rail-text">KATHMANDU VALLEY HUB</span>
          <span className="rail-text">SECURE ACCESS GRANTED</span>
        </div>

        {/* Branding */}
        <header className="flex items-center gap-6 z-10">
          <div className="h-14 w-14 bg-background-dark flex items-center justify-center border brutal-border-light rounded-2xl rotate-3">
             <img 
                src="https://image2url.com/r2/default/images/1775386504064-84a7f6df-f17a-45e2-96fd-db4b2663dc89.jpg" 
                alt="WL" 
                className="h-full w-full object-cover rounded-xl" 
                referrerPolicy="no-referrer"
              />
          </div>
          <div>
            <h1 className="text-2xl font-black uppercase tracking-tighter text-white">Work Lab</h1>
            <span className="text-[10px] font-mono uppercase tracking-[0.3em] text-white/40">Hardware & Utility Ecosystem</span>
          </div>
        </header>

        {/* Massive Headline */}
        <div className="relative z-10 py-32 lg:py-0">
          <motion.div 
            initial={{ opacity: 0, x: -20 }}
            animate={{ opacity: 1, x: 0 }}
            transition={{ duration: 0.8 }}
            className="flex items-center gap-4 mb-8"
          >
            <div className="h-[1px] w-12 bg-primary" />
            <span className="font-mono text-[10px] uppercase tracking-[0.4em] text-primary">Nepal's First On-Demand / Coming Soon</span>
          </motion.div>
          <motion.div 
            initial={{ opacity: 0, y: 50 }}
            animate={{ opacity: 1, y: 0 }}
            className="text-massive mb-12 text-white"
          >
            The <br />
            <span className="text-outline text-primary">Master</span> <br />
            Tool.
          </motion.div>
          <p className="text-xl lg:text-2xl font-serif italic text-white/50 max-w-lg leading-relaxed">
            Professional servicing and genuine parts sourcing. Managed with technical precision in Kathmandu, Nepal.
          </p>
        </div>

        {/* Footer Micro-Labels */}
        <footer className="z-10 flex gap-12">
          <div className="flex flex-col gap-1">
            <span className="col-header">Region</span>
            <span className="font-mono text-xs font-bold">AS-S1 / NP-KTM</span>
          </div>
          <div className="flex flex-col gap-1">
            <span className="col-header">Status</span>
            <span className="font-mono text-xs font-bold text-green-600">LIVE / DEPLOYED</span>
          </div>
        </footer>

        {/* Abstract Background Element */}
        <div className="absolute -bottom-32 -left-32 w-96 h-96 bg-primary/5 rounded-full blur-[120px] pointer-events-none" />
      </section>

      {/* RIGHT PANE: Technical Utility */}
      <section className="bg-background-dark text-ink-light flex flex-col justify-center p-8 lg:p-24 relative overflow-hidden">
        {/* Glow Effects */}
        <div className="absolute top-0 right-0 w-96 h-96 bg-primary/10 rounded-full blur-[150px] pointer-events-none" />
        <div className="scanline" />

        <div className="max-w-xl w-full mx-auto perspective-container relative z-10">
          <motion.div 
            initial={{ rotateX: 10, rotateY: -10, opacity: 0 }}
            animate={{ rotateX: 0, rotateY: 0, opacity: 1 }}
            transition={{ duration: 1 }}
            className="hardware-card bg-white/[0.03] brutal-border-light rounded-[40px] p-8 lg:p-12 backdrop-blur-3xl shadow-2xl"
          >
            <AnimatePresence mode="wait">
              {!subscribed ? (
                <motion.div 
                  key="form"
                  exit={{ opacity: 0, scale: 0.95 }}
                >
                  <div className="flex items-center justify-between mb-16">
                    <div className="flex items-center gap-4">
                      <div className="h-4 w-4 bg-primary rounded-full animate-pulse" />
                      <span className="font-mono text-[10px] uppercase tracking-[0.4em] text-primary">Priority Queue Entry</span>
                    </div>
                    <Globe className="h-5 w-5 text-white/20" />
                  </div>

                  <form onSubmit={handleSubmit} className="space-y-12">
                    <div className="relative group">
                      <label className="col-header text-white/30 mb-4 block group-focus-within:text-primary transition-colors">Operator Full Name</label>
                      <input 
                        type="text" 
                        value={name}
                        onChange={(e) => setName(e.target.value)}
                        className="w-full bg-transparent border-b brutal-border-light pb-4 text-2xl lg:text-3xl font-black outline-none focus:border-primary transition-colors placeholder:text-white/5"
                        placeholder="ID REQUIRED"
                      />
                      {nameError && <p className="font-mono text-[10px] text-red-400 uppercase mt-4">{nameError}</p>}
                    </div>

                    <div className="relative group">
                      <label className="col-header text-white/30 mb-4 block group-focus-within:text-primary transition-colors">Digital Comms Line</label>
                      <input 
                        type="email" 
                        value={email}
                        onChange={(e) => setEmail(e.target.value)}
                        className="w-full bg-transparent border-b brutal-border-light pb-4 text-2xl lg:text-3xl font-black outline-none focus:border-primary transition-colors placeholder:text-white/5"
                        placeholder="SECURE EMAIL"
                      />
                      {emailError && <p className="font-mono text-[10px] text-red-400 uppercase mt-4">{emailError}</p>}
                    </div>

                    {errorMsg && <div className="p-4 bg-red-400/10 border border-red-400/20 text-red-400 font-mono text-[10px] uppercase rounded-xl">{errorMsg}</div>}

                    <button 
                      type="submit"
                      disabled={loading}
                      className="w-full h-24 bg-primary text-white font-black text-sm uppercase tracking-[0.6em] rounded-3xl flex items-center justify-center gap-6 group hover:bg-white hover:text-black transition-all"
                    >
                      {loading ? <Spinner className="h-6 w-6 border-white/20 border-t-white" /> : (
                        <>
                          <span>Establish Link</span>
                          <ArrowRight className="h-6 w-6 group-hover:translate-x-2 transition-transform" />
                        </>
                      )}
                    </button>
                  </form>
                </motion.div>
              ) : (
                <motion.div 
                  key="success"
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  className="py-20 text-center"
                >
                  <div className="h-32 w-32 bg-primary/10 rounded-full flex items-center justify-center mx-auto mb-12 border border-primary/20">
                     <ShieldCheck className="h-16 w-16 text-primary" />
                  </div>
                  <h3 className="text-4xl font-black uppercase tracking-tighter mb-4">Linked.</h3>
                  <p className="font-serif italic text-white/40 text-lg mb-12">Your operational profile has been verified and added to the Kathmandu hub.</p>
                  <button 
                    onClick={() => setSubscribed(false)}
                    className="font-mono text-[10px] uppercase tracking-[0.4em] text-primary hover:text-white transition-colors"
                  >
                    Generate New Protocol
                  </button>
                </motion.div>
              )}
            </AnimatePresence>
          </motion.div>
        </div>

        {/* Directory Links as Data Grid */}
        <div className="max-w-xl w-full mx-auto mt-24">
          <div className="flex items-center justify-between mb-8 border-b brutal-border-light pb-4">
             <span className="col-header text-white/50">Service Matrix</span>
             <Boxes className="h-4 w-4 text-white/20" />
          </div>
          
          <div className="space-y-2">
            {[
              { id: '01', title: 'Servicing Protocol', icon: Wrench, details: 'Verified Tech Dispatch' },
              { id: '02', title: 'Hardware Catalog', icon: Cpu, details: 'Genuine Global Sourcing' }
            ].map((service) => (
              <div key={service.id} className="group flex items-center justify-between p-6 bg-white/[0.02] border brutal-border-light rounded-2xl hover:bg-primary hover:border-transparent transition-all cursor-pointer">
                <div className="flex items-center gap-6">
                  <span className="font-mono text-xs text-primary group-hover:text-white/40">{service.id}</span>
                  <div>
                    <h4 className="font-black uppercase tracking-tighter group-hover:text-white">{service.title}</h4>
                    <p className="text-[10px] font-mono text-white/30 uppercase tracking-widest group-hover:text-white/60">{service.details}</p>
                  </div>
                </div>
                <service.icon className="h-5 w-5 opacity-20 group-hover:opacity-100 group-hover:scale-110 transition-all" />
              </div>
            ))}
          </div>
        </div>

        {/* Social Comms */}
        <div className="mt-24 max-w-xl w-full mx-auto flex justify-between items-center opacity-40">
           <div className="flex gap-8">
              <a href="https://www.facebook.com/worklabnp" className="hover:text-primary transition-colors"><Facebook className="h-5 w-5" /></a>
              <a href="https://www.instagram.com/worklabnp" className="hover:text-primary transition-colors"><Instagram className="h-5 w-5" /></a>
              <a href="https://www.tiktok.com/@worklabnp" className="hover:text-primary transition-colors"><TikTok className="h-5 w-5" /></a>
           </div>
           <Zap className="h-4 w-4 text-primary animate-pulse" />
        </div>
      </section>
    </div>
  );
}
