import React, { useState, useEffect } from 'react';
import ReactDOM from 'react-dom/client';
import { 
  Menu, X, Compass, ArrowRight, Brain, Map as MapIcon, 
  ShieldCheck, Mountain, Navigation, Zap, 
  Check, ExternalLink, Cpu, Database, Users, Heart, Camera, Activity
} from 'lucide-react';
import { initializeApp } from "firebase/app";
import { getAnalytics, isSupported } from "firebase/analytics";

// --- CONFIG & FIREBASE ---
const firebaseConfig = {
  apiKey: "AIzaSyC2wvAg95Se6OsFj2hMpMZnnUM6W8o5fRk",
  authDomain: "fricamp-hjemmeside.firebaseapp.com",
  projectId: "fricamp-hjemmeside",
  storageBucket: "fricamp-hjemmeside.firebasestorage.app",
  messagingSenderId: "573618186606",
  appId: "1:573618186606:web:1e5c8fe29c50a7dec4b97f",
  measurementId: "G-VDSJGLLR9H"
};

const app = initializeApp(firebaseConfig);
if (typeof window !== 'undefined') {
  isSupported().then(supported => {
    if (supported) getAnalytics(app);
  }).catch(e => console.log('Analytics not supported'));
}

// --- COMPONENTS ---

const Navbar = () => {
  const [isOpen, setIsOpen] = useState(false);
  const [scrolled, setScrolled] = useState(false);
  const [logoError, setLogoError] = useState(false);

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

  const handleNavClick = (e: any, href: string) => {
    if (href.startsWith('#')) {
      e.preventDefault();
      const element = document.querySelector(href);
      if (element) {
        element.scrollIntoView({ behavior: 'smooth' });
        setIsOpen(false);
      }
    }
  };

  return (
    <nav className={`fixed w-full z-50 transition-all duration-300 ${scrolled ? 'bg-military-900/95 backdrop-blur-md shadow-lg py-4' : 'bg-transparent py-6'}`}>
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 flex items-center justify-between">
        <div className="flex items-center gap-3 cursor-pointer" onClick={() => window.scrollTo({ top: 0, behavior: 'smooth' })}>
          {!logoError ? (
            <img 
              src="https://storage.googleapis.com/ai-studio-bucket-188950506753-us-west1/services/villmarksspeideren/Fricamp%20logo.png" 
              className="h-10 md:h-12 w-auto rounded-xl shadow-lg" 
              alt="Logo" 
              onError={() => setLogoError(true)}
            />
          ) : (
            <Compass className="h-8 w-8 text-earth-500" />
          )}
          <span className="text-xl md:text-2xl font-bold text-white tracking-tight">Fricamp</span>
        </div>
        
        <div className="hidden md:flex items-center space-x-8">
          {[
            {name: 'Kartlag', href: '#tech'}, 
            {name: 'Fellesskap', href: '#community'}, 
            {name: 'AI-Analyse', href: '#features'}, 
            {name: 'Pris', href: '#pricing'}
          ].map(item => (
            <a 
              key={item.name} 
              href={item.href} 
              onClick={(e) => handleNavClick(e, item.href)}
              className="text-military-100 hover:text-earth-500 transition-colors text-sm font-medium uppercase tracking-widest cursor-pointer"
            >
              {item.name}
            </a>
          ))}
          <a href="https://fricamp.takleconsulting.com" className="bg-earth-500 hover:bg-earth-900 text-white px-6 py-2 rounded-full font-bold transition-all text-sm uppercase shadow-lg hover:shadow-earth-500/20">Last ned</a>
        </div>
        
        <button className="md:hidden text-white" onClick={() => setIsOpen(!isOpen)}>
          {isOpen ? <X /> : <Menu />}
        </button>
      </div>
      {isOpen && (
        <div className="md:hidden bg-military-900 p-4 space-y-4 border-t border-military-800">
          {[
            {name: 'Kartlag', href: '#tech'}, 
            {name: 'Fellesskap', href: '#community'}, 
            {name: 'AI-Analyse', href: '#features'}, 
            {name: 'Pris', href: '#pricing'}
          ].map(item => (
            <a key={item.name} href={item.href} onClick={(e) => handleNavClick(e, item.href)} className="block text-military-100 py-2">{item.name}</a>
          ))}
        </div>
      )}
    </nav>
  );
};

const Hero = () => (
  <div className="relative h-screen flex items-center justify-center overflow-hidden bg-military-900">
    <div className="absolute inset-0 z-0">
      <div className="absolute inset-0 bg-military-900/40 z-10"></div>
      <img src="https://storage.googleapis.com/ai-studio-bucket-188950506753-us-west1/services/fricamp/version-1/Public/dji_fly_20250822_212418_231_1755890876555_video.gif" className="w-full h-full object-cover" alt="Background" />
    </div>
    <div className="relative z-20 text-center px-4 animate-fade-in-up">
      <div className="inline-flex items-center gap-2 px-4 py-2 rounded-full bg-military-900/80 border border-military-600 mb-8 backdrop-blur-md">
        <Activity className="h-4 w-4 text-earth-500" />
        <span className="text-earth-100 text-xs font-semibold uppercase tracking-widest">Norsk Natur • AI-Presisjon • Allemannsretten</span>
      </div>
      <h1 className="text-5xl md:text-7xl font-bold text-white mb-6 leading-tight drop-shadow-2xl">Frihet med <br/><span className="text-earth-500">oversikt</span></h1>
      <p className="max-w-2xl mx-auto text-xl text-white/90 font-light mb-10">Fricamp aggregerer data fra NVDB, Nobil og Statens Kartverk for å gi deg et komplett situasjonsbilde av terrenget.</p>
      <div className="flex flex-col sm:flex-row gap-4 justify-center">
        <a href="https://fricamp.takleconsulting.com" className="px-8 py-4 bg-earth-500 hover:bg-earth-900 text-white rounded-lg font-bold flex items-center justify-center gap-2 transition-all shadow-lg">Utforsk kartet <ArrowRight className="h-5 w-5" /></a>
        <a href="#tech" onClick={(e) => { e.preventDefault(); document.getElementById('tech')?.scrollIntoView({behavior: 'smooth'})}} className="px-8 py-4 bg-military-900/60 border border-white/20 text-white rounded-lg font-bold backdrop-blur-sm cursor-pointer hover:bg-military-800 transition-colors">Se kartlag</a>
      </div>
    </div>
  </div>
);

const TechStack = () => (
  <section id="tech" className="py-24 bg-military-800 border-y border-military-700">
    <div className="max-w-7xl mx-auto px-4 grid lg:grid-cols-2 gap-16 items-center">
      <div className="order-2 lg:order-1">
        <h2 className="text-earth-500 font-bold tracking-wider uppercase text-sm mb-3">Oversikt over Kartlag</h2>
        <h3 className="text-3xl md:text-4xl font-bold text-white mb-6">Aggregerte data for tryggere turer</h3>
        <p className="text-military-100 mb-8 leading-relaxed">Fricamp er et dynamisk beslutningsverktøy som kombinerer data fra en rekke offentlige kilder:</p>
        <div className="space-y-6">
          <div className="flex items-start gap-4">
            <div className="bg-military-900 p-3 rounded-lg text-earth-500"><MapIcon className="h-6 w-6" /></div>
            <div>
              <h4 className="text-white font-bold">Avanserte Kartlag</h4>
              <p className="text-sm text-military-100">Veksle mellom topografiske høydekurver fra Kartverket og høyoppløselige satellittbilder for å vurdere planhet.</p>
            </div>
          </div>
          <div className="flex items-start gap-4">
            <div className="bg-military-900 p-3 rounded-lg text-earth-500"><Navigation className="h-6 w-6" /></div>
            <div>
              <h4 className="text-white font-bold">NVDB (Statens Vegvesen)</h4>
              <p className="text-sm text-military-100">Offisielle rasteplasser med fasilitetsdata (toalett, møbler), vinterstengte veier og verifiserte snuplasser.</p>
            </div>
          </div>
          <div className="flex items-start gap-4">
            <div className="bg-military-900 p-3 rounded-lg text-earth-500"><Zap className="h-6 w-6" /></div>
            <div>
              <h4 className="text-white font-bold">Fasiliteter & Lading</h4>
              <p className="text-sm text-military-100">Drikkevann, gapahuker og bålplasser fra OSM. Sanntidsdata for elbil-lading via Nobil langs ruten din.</p>
            </div>
          </div>
          <div className="flex items-start gap-4">
            <div className="bg-military-900 p-3 rounded-lg text-earth-500"><Activity className="h-6 w-6" /></div>
            <div>
              <h4 className="text-white font-bold">Vegsperringer & Maritime lag</h4>
              <p className="text-sm text-military-100">Sanntidsvisning av bommer og sperringer. Oversikt over kaier og marinaer for kystreisende.</p>
            </div>
          </div>
        </div>
      </div>
      <div className="relative group order-1 lg:order-2">
        <div className="absolute inset-0 bg-earth-500/10 rounded-2xl transform rotate-3 transition-transform group-hover:rotate-6"></div>
        <img src="https://storage.googleapis.com/ai-studio-bucket-188950506753-us-west1/services/fricamp/version-1/Public/PXL_20260131_143205909.RAW-01.COVER.jpg" alt="Analyse" className="relative rounded-2xl shadow-2xl border border-military-600 w-full object-cover h-[500px]" />
        
        {/* Floating Info Card */}
        <div className="absolute -bottom-6 -right-6 bg-military-900 p-6 rounded-xl border border-military-600 shadow-2xl z-10 hidden sm:block">
          <div className="flex items-center gap-3 mb-3">
            <div className="w-3 h-3 rounded-full bg-green-500 animate-pulse"></div>
            <span className="text-white font-mono text-xs uppercase tracking-tighter">System: Online</span>
          </div>
          <div className="text-[10px] text-military-100 font-mono space-y-1.5 uppercase">
            <p className="flex justify-between gap-4"><span>NVDB API:</span> <span className="text-earth-500">Live</span></p>
            <p className="flex justify-between gap-4"><span>Nobil Data:</span> <span className="text-earth-500">Aktiv</span></p>
            <p className="flex justify-between gap-4"><span>Maritime lag:</span> <span className="text-earth-500">Ok</span></p>
            <p className="flex justify-between gap-4"><span>Rutebygger:</span> <span className="text-earth-500">Klar</span></p>
          </div>
        </div>
      </div>
    </div>
  </section>
);

const Features = () => {
  const items = [
    { title: "Lovlighetsvurdering", description: "AI-en tolker Allemannsretten mot punktet og gir råd som 'LOVLIG', 'FORBUDT' eller 'SJEKK SKILT'.", icon: <ShieldCheck /> },
    { title: "Kvalitetsscore", description: "En score fra 1–10 basert på avstand til bebyggelse, støynivå, terrengform og nærhet til vann/utsikt.", icon: <Zap /> },
    { title: "Rutebygger", description: "Klikk på veisegmenter for å sy sammen egne ruter. AI-en finner alle fasiliteter innen 1,5 km fra veikanten.", icon: <Navigation /> },
    { title: "Kjøretøysprofiler", description: "Systemet tar hensyn til om du kjører 'Standard' bobil eller 'Offroad' 4x4, og filtrerer veitilgang deretter.", icon: <Mountain /> },
    { title: "Vis Veg & Høydeprofil", description: "Beregner rute fra GPS-posisjon og genererer dynamisk høydeprofil med stigningsdata.", icon: <Activity /> },
    { title: "AI-Drevet Analyse", description: "Dyp-analyse av terrenget ved hjelp av Google Gemini for å vurdere vegetasjon og planhet.", icon: <Brain /> }
  ];
  return (
    <section id="features" className="py-24 bg-military-900">
      <div className="max-w-7xl mx-auto px-4">
        <div className="text-center mb-16">
          <h2 className="text-earth-500 font-bold uppercase tracking-widest text-sm mb-3">AI & Funksjonalitet</h2>
          <h3 className="text-3xl md:text-5xl font-bold text-white">Smart beslutningsstøtte i felt</h3>
        </div>
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {items.map((f, i) => (
            <div key={i} className="p-8 rounded-2xl bg-military-800/50 border border-military-700 hover:border-earth-500 transition-all group">
              <div className="w-12 h-12 rounded-lg bg-military-900 flex items-center justify-center mb-6 text-earth-500 group-hover:scale-110 transition-transform">{f.icon}</div>
              <h4 className="text-xl font-bold text-white mb-3">{f.title}</h4>
              <p className="text-military-100 text-sm leading-relaxed">{f.description}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
};

const Community = () => (
  <section id="community" className="py-24 bg-military-800/30">
    <div className="max-w-7xl mx-auto px-4">
      <div className="grid lg:grid-cols-2 gap-16 items-center">
        <div className="grid grid-cols-2 gap-4">
          <img src="https://storage.googleapis.com/ai-studio-bucket-188950506753-us-west1/services/fricamp/version-1/Public/IMG_0505-EDIT.jpg" className="rounded-xl shadow-lg w-full h-48 object-cover" alt="Community 1" />
          <img src="https://storage.googleapis.com/ai-studio-bucket-188950506753-us-west1/services/fricamp/version-1/Public/IMG_20210418_084108-EDIT.jpg" className="rounded-xl shadow-lg w-full h-48 object-cover mt-8" alt="Community 2" />
          <img src="https://storage.googleapis.com/ai-studio-bucket-188950506753-us-west1/services/fricamp/version-1/Public/20230804_204636.jpg" className="rounded-xl shadow-lg w-full h-48 object-cover" alt="Community 3" />
          <img src="https://storage.googleapis.com/ai-studio-bucket-188950506753-us-west1/services/fricamp/version-1/Public/20220723_203004.jpg" className="rounded-xl shadow-lg w-full h-48 object-cover mt-8" alt="Community 4" />
        </div>
        <div>
          <h2 className="text-earth-500 font-bold tracking-wider uppercase text-sm mb-3">Brukerkonto & Fellesskap</h2>
          <h3 className="text-3xl md:text-4xl font-bold text-white mb-6">Din personlige turdagbok</h3>
          <p className="text-military-100 mb-8 leading-relaxed">Ved å opprette en profil blir Fricamp ditt aktive verktøy for forvaltning av natur og egne opplevelser.</p>
          
          <div className="space-y-6">
            <div className="flex gap-4">
              <div className="text-earth-500 mt-1"><Heart /></div>
              <div>
                <h4 className="text-white font-bold">Personlig Arkiv</h4>
                <p className="text-sm text-military-100">Lagre "perler" som kun er synlige for deg. Organiser lagrede ruter og GPX-filer etter region for rask tilgang.</p>
              </div>
            </div>
            <div className="flex gap-4">
              <div className="text-earth-500 mt-1"><Camera /></div>
              <div>
                <h4 className="text-white font-bold">Bidrag til Fellesskapet</h4>
                <p className="text-sm text-military-100">Legg inn anmeldelser og bilder. Hjelp andre å vite om en plass er overfylt eller om utsikten holder mål.</p>
              </div>
            </div>
            <div className="flex gap-4">
              <div className="text-earth-500 mt-1"><Users /></div>
              <div>
                <h4 className="text-white font-bold">Speider-verifisering</h4>
                <p className="text-sm text-military-100">Som bruker kan du godkjenne AI-punkter eller foreslå fjerning av plasser som bryter 150-metersregelen.</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </section>
);

const CinematicDivider = () => (
  <section className="relative h-[60vh] flex items-center justify-center overflow-hidden">
    <div className="absolute inset-0 z-0">
      <div className="absolute inset-0 bg-military-950/50 z-10"></div>
      <img src="https://storage.googleapis.com/ai-studio-bucket-188950506753-us-west1/services/fricamp/version-1/Public/skogvideo_2.gif" alt="Divider" className="w-full h-full object-cover" />
    </div>
    <div className="relative z-20 text-center px-4">
      <h3 className="text-3xl md:text-5xl font-bold text-white mb-4 italic tracking-tight">"Eventyret venter rundt neste sving"</h3>
      <div className="w-24 h-1 bg-earth-500 mx-auto rounded-full"></div>
    </div>
  </section>
);

const Pricing = () => {
  const tiers = [
    { name: "Gratisbruker", price: "0 kr", features: ["Grunnleggende kartlag", "Søk etter steder", "Begrenset AI-analyse", "Se offentlige rasteplasser"] },
    { name: "Abonnement", price: "49 kr", features: ["Ubegrenset AI-analyse", "Offroad-modus", "Lagre ruter og favoritter", "Se detaljerte eiendomsgrenser", "Værvarsel og farevarsler", "Offline kart"], recommended: true },
    { name: "Tester", price: "Invite only", features: ["Søk om å bli testbruker", "Tidlig tilgang", "Direkte linje til utviklere", "Bidra til AI-trening", "Alle Pro-funksjoner", "Moderator-status"] }
  ];
  return (
    <section id="pricing" className="py-24 bg-military-900">
      <div className="max-w-7xl mx-auto px-4 text-center">
        <h2 className="text-earth-500 font-bold tracking-wider uppercase text-sm mb-3">Profiler</h2>
        <h3 className="text-3xl md:text-5xl font-bold text-white mb-16">Velg din reisevei</h3>
        <div className="grid md:grid-cols-3 gap-8 max-w-5xl mx-auto items-center">
          {tiers.map((tier, i) => (
            <div key={i} className={`relative p-8 rounded-2xl transition-all duration-300 flex flex-col h-full ${tier.recommended ? 'bg-military-800 border-2 border-earth-500 shadow-2xl scale-105 z-10' : 'bg-military-900 border border-military-700'}`}>
              {tier.recommended && <div className="absolute top-0 left-1/2 transform -translate-x-1/2 -translate-y-1/2"><span className="bg-earth-500 text-white px-4 py-1 rounded-full text-xs font-bold uppercase">Anbefalt</span></div>}
              <h3 className="text-xl font-bold text-white mb-2">{tier.name}</h3>
              <div className="mb-6"><span className="text-4xl font-bold text-white">{tier.price}</span><span className="text-military-100 text-sm">/mnd</span></div>
              <ul className="space-y-4 mb-8 flex-1">{tier.features.map((f, idx) => (<li key={idx} className="flex items-start gap-3"><Check className="h-5 w-5 text-earth-500 flex-shrink-0" /><span className="text-sm text-military-100">{f}</span></li>))}</ul>
              <a href="https://fricamp.takleconsulting.com" className={`block w-full text-center py-3 rounded-lg font-bold transition-colors shadow-lg ${tier.recommended ? 'bg-earth-500 hover:bg-earth-900 text-white shadow-earth-500/10' : 'bg-military-800 hover:bg-military-700 text-white'}`}>Velg {tier.name}</a>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
};

const Footer = () => (
  <footer id="footer" className="bg-military-950 text-military-100 border-t border-military-800">
    <div className="max-w-7xl mx-auto px-4 py-12">
      <div className="grid md:grid-cols-4 gap-8">
        <div className="col-span-1 md:col-span-2">
          <div className="flex items-center gap-2 mb-4"><img src="https://storage.googleapis.com/ai-studio-bucket-188950506753-us-west1/services/villmarksspeideren/Fricamp%20logo.png" alt="Logo" className="h-10 w-auto rounded-lg" /></div>
          <p className="text-sm leading-relaxed max-w-sm mb-6 opacity-80">Fricamp balanserer teknologisk presisjon med menneskelig erfaring. Sammen gjør vi fricamping i Norge bedre.</p>
        </div>
        <div>
          <h3 className="text-white font-bold uppercase tracking-wider text-sm mb-4">Utforsk</h3>
          <ul className="space-y-2 text-sm">{['Kartlag', 'Fellesskap', 'AI-Analyse', 'Pris'].map(l => <li key={l}><a href={`#${l.toLowerCase().replace(' ', '-')}`} className="hover:text-earth-500 transition-colors">{l}</a></li>)}</ul>
        </div>
        <div>
          <h3 className="text-white font-bold uppercase tracking-wider text-sm mb-4">Utvikler</h3>
          <p className="text-sm mb-2 opacity-80">Utviklet av Takle Consulting.</p>
          <a href="https://www.takleconsulting.com" target="_blank" className="inline-flex items-center text-earth-500 hover:text-earth-100 text-sm font-medium">Besøk nettsiden <ExternalLink className="ml-1 h-3 w-3" /></a>
        </div>
      </div>
      <div className="border-t border-military-800 mt-12 pt-8 flex flex-col md:flex-row justify-between items-center text-xs opacity-60">
        <p>&copy; {new Date().getFullYear()} Fricamp. Utforsk naturen med respekt.</p>
        <div className="flex space-x-6 mt-4 md:mt-0"><a href="#" className="hover:text-white">Personvern</a><a href="#" className="hover:text-white">Vilkår</a></div>
      </div>
    </div>
  </footer>
);

function App() {
  return (
    <div className="min-h-screen bg-military-900 font-sans selection:bg-earth-500 selection:text-white">
      <Navbar />
      <main>
        <Hero />
        <TechStack />
        <Community />
        <CinematicDivider />
        <Features />
        <Pricing />
      </main>
      <Footer />
    </div>
  );
}

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