import React, { useState, useEffect } from 'react';
import { Camera, Shield, ShieldCheck, Heart, Info, Box } from 'lucide-react';
import { motion } from 'motion/react';
import CameraView from './components/CameraView';
import MetricRadar from './components/MetricRadar';
import AuraControl from './components/AuraControl';
import AutomationFeed from './components/AutomationFeed';
import OBSViewer from './components/OBSViewer';
import { TUNNEL_URL } from './tunnelConfig';

export default function App() {
  const [cloakEnabled, setCloakEnabled] = useState(false);
  const [cloakIntensity, setCloakIntensity] = useState(30);
  const [cloakMode, setCloakMode] = useState<'obfuscate' | 'refine'>('obfuscate');
  const [sourceType, setSourceType] = useState<'camera' | 'image'>('camera');
  const [testImage, setTestImage] = useState<string | null>(null);
  const [targetImage, setTargetImage] = useState<string | null>(null);
  const [mobileTab, setMobileTab] = useState<'feed' | 'controls' | 'metrics'>('feed');
  const [metrics, setMetrics] = useState<any>({
    native: { symmetry: 34, eyes: -0.8, jawline: 0.6, midface: 0.44, cheekbones: 1.2, eyeAspect: 0.34, harmony: 7, overall: 5 },
    cloaked: { symmetry: 34, eyes: -0.8, jawline: 0.6, midface: 0.44, cheekbones: 1.2, eyeAspect: 0.34, harmony: 7, overall: 5 }
  });
  const [isBroadcasting, setIsBroadcasting] = useState(false);
  const [tunnelSignalUrl, setTunnelSignalUrl] = useState('');

  useEffect(() => {
    // Attempt to auto-fetch tunnel info from server
    const fetchTunnelInfo = async () => {
      try {
        const res = await fetch('/api/tunnel-info');
        const data = await res.json();
        if (data.url) {
          setTunnelSignalUrl(data.url);
        }
      } catch (e) {
        console.error("Failed to fetch tunnel info:", e);
      }
    };
    fetchTunnelInfo();
    const interval = setInterval(fetchTunnelInfo, 5000);
    return () => clearInterval(interval);
  }, []);

  // OBS / Virtual Camera Routing logic
  const urlParams = new URLSearchParams(window.location.search);
  const isVirtualView = urlParams.get('view') === 'virtual';

  if (isVirtualView) {
    const overrideUrl = urlParams.get('signal');
    return <OBSViewer signalUrl={overrideUrl || tunnelSignalUrl} />;
  }

  const baseUrl = window.location.origin;
  const virtualCamUrl = `${baseUrl}${window.location.pathname}?view=virtual${tunnelSignalUrl ? `&signal=${encodeURIComponent(tunnelSignalUrl)}` : ''}`;

  const handleFileUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = (event) => {
        setTestImage(event.target?.result as string);
        setSourceType('image');
      };
      reader.readAsDataURL(file);
    }
  };

  const handleTargetUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = (event) => setTargetImage(event.target?.result as string);
      reader.readAsDataURL(file);
    }
  };

  return (
    <div className="h-[100dvh] bg-bg-primary text-[#e0e0e0] flex flex-col overflow-hidden font-sans">
      {/* Header */}
      <header className="h-16 border-b border-white/10 flex items-center justify-between px-4 md:px-8 bg-bg-secondary shrink-0">
        <div className="flex items-center gap-4">
          <div className="w-3 h-3 bg-aura-500 rounded-full shadow-[0_0_8px_#00FF9C]"></div>
          <h1 className="font-serif italic text-lg md:text-xl tracking-wide">
            De-Mog <span className="hidden md:inline text-xs font-mono text-white/40 ml-2">v1.0.4 - Protection Active</span>
          </h1>
        </div>

        {/* Mobile Tabs */}
        <div className="flex lg:hidden bg-white/5 rounded-lg p-1">
          <button 
            onClick={() => setMobileTab('feed')}
            className={`px-3 py-1 font-mono text-[10px] uppercase rounded ${mobileTab === 'feed' ? 'bg-white/10 text-white' : 'text-white/40'}`}
          >
            Feed
          </button>
          <button 
            onClick={() => setMobileTab('controls')}
            className={`px-3 py-1 font-mono text-[10px] uppercase rounded ${mobileTab === 'controls' ? 'bg-white/10 text-white' : 'text-white/40'}`}
          >
            Controls
          </button>
          <button 
            onClick={() => setMobileTab('metrics')}
            className={`px-3 py-1 font-mono text-[10px] uppercase rounded ${mobileTab === 'metrics' ? 'bg-white/10 text-white' : 'text-white/40'}`}
          >
            Metrics
          </button>
        </div>

        <div className="hidden lg:flex gap-4 md:gap-6 text-[10px] md:text-[11px] font-mono uppercase tracking-widest text-white/60">
          <span className="hidden sm:inline">Session: 04:12:09</span>
          <span className={cloakEnabled ? "text-aura-500" : "text-white/40"}>
            {cloakEnabled ? "Target Cloaked" : "System Vulnerable"}
          </span>
        </div>
      </header>

      <main className="flex-1 flex flex-col lg:flex-row overflow-hidden">
        
        {/* Left Sidebar: Controls */}
        <aside className={`${mobileTab === 'controls' ? 'flex' : 'hidden'} lg:flex flex-1 min-h-0 lg:flex-none w-full lg:w-72 border-r border-white/10 p-4 md:p-6 flex-col gap-6 bg-bg-tertiary shrink-0 overflow-y-auto`}>
          <section>
            <p className="text-[10px] uppercase tracking-tighter text-white/40 mb-3 font-mono">Source Input</p>
            <div className="flex gap-2 mb-3 bg-white/5 p-1 rounded-lg">
              <button 
                onClick={() => setSourceType('camera')}
                className={`flex-1 py-1.5 text-xs font-mono rounded ${sourceType === 'camera' ? 'bg-white/10 text-white' : 'text-white/40 hover:text-white/80'}`}
              >
                Camera
              </button>
              <button 
                onClick={() => setSourceType('image')}
                className={`flex-1 py-1.5 text-xs font-mono rounded ${sourceType === 'image' ? 'bg-white/10 text-white' : 'text-white/40 hover:text-white/80'}`}
              >
                Static Image
              </button>
            </div>
            
            {sourceType === 'image' && (
              <label className="aspect-square bg-white/5 border border-dashed border-white/20 rounded-lg flex flex-col items-center justify-center p-4 text-center group cursor-pointer hover:border-aura-500/50 transition-colors">
                <input type="file" accept="image/*" onChange={handleFileUpload} className="hidden" />
                {testImage ? (
                  <div className="relative w-full h-full p-2 bg-white/5">
                    <img src={testImage} alt="Test" className="w-full h-full object-contain rounded" />
                    <button 
                      onClick={(e) => { e.preventDefault(); setTestImage(null); }}
                      className="absolute -top-1 -right-1 bg-red-500 text-white w-5 h-5 rounded-full text-[10px] flex items-center justify-center border border-white/20 hover:bg-red-600 transition-colors"
                    >
                      ✕
                    </button>
                  </div>
                ) : (
                  <>
                    <div className="w-10 h-10 border border-white/10 rounded-full mb-3 flex items-center justify-center group-hover:border-aura-500 transition-colors">
                      <Box className="w-4 h-4 text-white/40 group-hover:text-aura-500" />
                    </div>
                    <p className="text-xs font-serif italic">Upload Source Image</p>
                    <p className="text-[9px] text-white/30 mt-2 font-mono italic">Static neural testing</p>
                  </>
                )}
              </label>
            )}
          </section>

          {cloakMode === 'obfuscate' && (
            <section>
              <p className="text-[10px] uppercase tracking-tighter text-white/40 mb-3 font-mono">Target Identity (Obfuscate)</p>
              <label className="aspect-video bg-white/5 border border-dashed border-white/20 rounded-lg flex flex-col items-center justify-center p-4 text-center group cursor-pointer hover:border-aura-500/50 transition-colors">
                <input type="file" accept="image/*" onChange={handleTargetUpload} className="hidden" />
                {targetImage ? (
                  <div className="relative w-full h-full p-2 bg-white/5">
                    <img src={targetImage} alt="Target" className="w-full h-full object-cover rounded" />
                    <button 
                      onClick={(e) => { e.preventDefault(); setTargetImage(null); }}
                      className="absolute -top-1 -right-1 bg-red-500 text-white w-5 h-5 rounded-full text-[10px] flex items-center justify-center border border-white/20 hover:bg-red-600 transition-colors"
                    >
                      ✕
                    </button>
                  </div>
                ) : (
                  <>
                    <div className="w-8 h-8 border border-white/10 rounded-full mb-2 flex items-center justify-center group-hover:border-aura-500 transition-colors">
                      <Box className="w-4 h-4 text-white/40 group-hover:text-aura-500" />
                    </div>
                    <p className="text-[10px] font-serif italic text-white/60">Upload Face Swap Target</p>
                  </>
                )}
              </label>
            </section>
          )}

          <section>
            <AuraControl 
                enabled={cloakEnabled} 
                setEnabled={setCloakEnabled}
                intensity={cloakIntensity}
                setIntensity={setCloakIntensity}
                mode={cloakMode}
                setMode={setCloakMode}
            />
          </section>

          <section className="bg-white/5 border border-white/10 p-3 rounded space-y-2">
            <div className="flex items-center justify-between">
                <div className="flex items-center gap-2 text-[10px] font-mono text-white/40 uppercase tracking-widest">
                  <Camera className="w-3 h-3" />
                  <span>Signal Server (Borepub)</span>
                </div>
                {tunnelSignalUrl ? (
                  <span className="flex items-center gap-1 text-[8px] font-mono text-aura-500">
                    <span className="w-1.5 h-1.5 bg-aura-500 rounded-full animate-pulse" />
                    LIVE
                  </span>
                ) : (
                  <span className="flex items-center gap-1 text-[8px] font-mono text-white/20">
                    <div className="w-3 h-3 border border-white/20 border-t-white/50 rounded-full animate-spin" />
                    STARTING
                  </span>
                )}
            </div>
            <p className="text-[9px] text-white/40 font-mono italic leading-tight">
              Signaling server URL. Bypasses HuggingFace proxy for stable WebRTC.
            </p>
            <div className="flex gap-1">
              <input 
                readOnly
                type="text"
                value={tunnelSignalUrl || 'Detecting tunnel...'} 
                className="flex-1 bg-black/50 border border-white/10 p-1.5 text-[9px] font-mono text-aura-500 rounded outline-none"
              />
              <button 
                onClick={() => {
                  navigator.clipboard.writeText(tunnelSignalUrl);
                  alert("Tunnel URL copied! Use this for 'SETUP_TARGET' in Tampermonkey.");
                }}
                className="px-3 bg-white/5 border border-white/10 text-white/40 hover:bg-white/10 text-[9px] font-mono rounded"
              >
                COPY
              </button>
            </div>
            
            <div className="h-px bg-white/5 my-2" />
            
            <div className="flex items-center gap-2 text-[10px] font-mono text-white/40 uppercase tracking-widest">
              <span>OBS Browser Source</span>
            </div>
            <input 
              readOnly 
              value={virtualCamUrl} 
              className="w-full bg-black/50 border border-white/10 p-1.5 text-[9px] font-mono text-white/40 rounded outline-none"
            />
            <button 
              onClick={() => {
                navigator.clipboard.writeText(virtualCamUrl);
              }}
              className="w-full py-1.5 text-[9px] font-mono uppercase tracking-widest bg-aura-500/10 text-aura-500 border border-aura-500/20 hover:bg-aura-500/20 transition-colors rounded"
            >
              Copy Source URL
            </button>
          </section>

          <button 
            onClick={() => setCloakEnabled(!cloakEnabled)}
            className="w-full py-4 bg-white text-black font-serif italic text-sm rounded hover:bg-aura-500 transition-all active:scale-[0.98] shrink-0"
          >
            {cloakEnabled ? 'Deactivate Cloak' : 'Initialize Cloak'}
          </button>
        </aside>

        {/* Center: Camera Feed */}
        <section className={`${mobileTab === 'feed' ? 'flex' : 'hidden'} lg:flex flex-1 p-4 md:p-8 flex-col gap-6 overflow-hidden bg-black relative`}>
          <div className="relative flex-1 rounded-2xl overflow-hidden border border-white/10 shadow-2xl bg-black">
            <CameraView 
              cloakEnabled={cloakEnabled} 
              cloakIntensity={cloakIntensity}
              cloakMode={cloakMode}
              testImage={testImage}
              targetImage={targetImage}
              sourceType={sourceType}
              onMetricsUpdate={setMetrics}
              setIsBroadcasting={setIsBroadcasting}
              signalUrl={tunnelSignalUrl}
            />
            
            <div className="absolute bottom-6 left-6 md:bottom-8 md:left-8 z-20 pointer-events-none">
              <div className="text-2xl md:text-4xl font-serif italic mb-1 text-white">
                {testImage ? 'Static Buffer' : 'Protected Feed'}
              </div>
              <div className="text-[9px] md:text-[10px] font-mono text-white/50 tracking-tighter">
                {testImage ? 'DIAGNOSTIC STATIC INTERVENTION' : 'ADVFACES CLOAKING ENGINE // REAL-TIME INTERVENTION'}
              </div>
            </div>
          </div>
        </section>

        {/* Right Sidebar: Metrics */}
        <aside className={`${mobileTab === 'metrics' ? 'flex' : 'hidden'} lg:flex flex-1 min-h-0 lg:flex-none w-full lg:w-80 border-l border-white/10 p-4 md:p-6 bg-bg-tertiary shrink-0 overflow-y-auto flex-col overflow-x-hidden gap-8`}>
          <MetricRadar metrics={metrics} cloakEnabled={cloakEnabled} />
          
          <AutomationFeed />
          
          <div className="mt-auto pt-8 border-t border-white/5">
            <p className="text-[10px] uppercase tracking-tighter text-white/40 mb-4 font-mono">Bypass Status</p>
            <div className="space-y-3 font-mono text-[10px]">
              <div className="flex gap-3 items-center text-aura-500">
                <span className="w-1.5 h-1.5 rounded-full bg-aura-500 shadow-[0_0_4px_currentColor]"></span>
                <span>MESH COORDINATES JITTERED</span>
              </div>
              <div className={`flex gap-3 items-center transition-colors ${cloakEnabled ? 'text-aura-500' : 'text-white/20'}`}>
                <span className={`w-1.5 h-1.5 rounded-full ${cloakEnabled ? 'bg-aura-500 shadow-[0_0_4px_currentColor]' : 'bg-white/20'}`}></span>
                <span>RATING BOT BYPASSED</span>
              </div>
            </div>
          </div>

          <div className="mt-8 p-4 border border-aura-500/20 bg-aura-500/5">
            <p className="text-xs font-serif italic text-aura-500 mb-1">Human Perception Check</p>
            <p className="text-[10px] text-white/60 leading-relaxed font-mono">
              Adversarial noise is currently optimized. The face remains natural to human viewers while breaking machine vision models.
            </p>
          </div>
        </aside>
      </main>

      {/* Mobile Footer Status */}
      <div className="lg:hidden h-10 border-t border-white/10 bg-bg-secondary flex items-center px-4 justify-between">
         <span className="text-[9px] font-mono text-aura-500 uppercase tracking-widest">
           Status: {cloakEnabled ? 'CLOAK_ACTIVE' : 'MONITORING'}
         </span>
         <span className={`text-[9px] font-mono uppercase ${isBroadcasting ? 'text-aura-500' : 'text-white/20'}`}>
           BROADCAST: {isBroadcasting ? 'LIVE' : 'OFFLINE'}
         </span>
      </div>

      {/* Footer */}
      <footer className="hidden sm:flex h-10 bg-black border-t border-white/5 px-8 items-center justify-between text-[10px] font-mono text-white/30 shrink-0">
        <div className="flex gap-4 items-center">
          <span>ENC_KEY: 88f2-x921-adv-p32</span>
          <span className="w-px h-3 bg-white/10" />
          <span className={isBroadcasting ? 'text-aura-500' : 'text-white/10'}>
            SIGNAL: {isBroadcasting ? 'ACTIVE' : 'OFFLINE'}
          </span>
        </div>
        <div className="flex gap-8 uppercase tracking-widest">
          <span className="hover:text-white cursor-pointer transition-colors">Safety Guidelines</span>
          <span className="hover:text-white cursor-pointer transition-colors text-aura-500 font-bold">AdvFaces Protocol v4</span>
        </div>
      </footer>
    </div>
  );
}
