import React, { useEffect, useRef, useState } from 'react';
import Account, {ProfileSetup,PasswordRecovery} from './Account.jsx';
import {supabase,supabaseMode} from './auth.js';
import Workspace from './Workspace.jsx';
import Admin from './Admin.jsx';
import StagingAdmin from './StagingAdmin.jsx';
import { api } from './api.js';
import { createRoot } from 'react-dom/client';
import { ArrowUpRight, Boxes, FileCheck2, MapPin, Menu, Package, Route, ShieldCheck, Truck, X } from 'lucide-react';
import '@fontsource/manrope/400.css';
import '@fontsource/manrope/500.css';
import '@fontsource/manrope/600.css';
import '@fontsource/manrope/700.css';
import '@fontsource/manrope/800.css';
import './styles.css';

function Brand({ light = false, onHome }) {
  return <a className={'brand' + (light ? ' brand-light' : '')} href="#top" onClick={onHome} aria-label="Lugggiztik home"><span className="brand-icon"><Truck size={20} strokeWidth={2} /></span><span>lugggiztik<span className="brand-dot">.</span></span></a>;
}

function Header({ onAccount, onAdmin, user }) {
  const [menu, setMenu] = useState(false);
  return <header className="header" id="top"><div className="header-inner"><Brand /><nav className={'main-nav' + (menu ? ' open' : '')} aria-label="Main navigation">
    <a href="#how-it-works" onClick={() => setMenu(false)}>How it works</a><a href="#who-its-for" onClick={() => setMenu(false)}>Who it’s for</a><a href="#why-lugggiztik" onClick={() => setMenu(false)}>Why Lugggiztik</a>{user?.isAdmin&&<button className="mobile-action account-mobile" onClick={() => {setMenu(false); onAdmin();}}>Operations review <ArrowUpRight size={16}/></button>}<button className="mobile-action account-mobile" onClick={() => {setMenu(false); onAccount();}}>{user ? "Open workspace" : "Sign in / Register"} <ArrowUpRight size={16}/></button>
  </nav><div className="header-actions">{user?.isAdmin&&<button className="header-signin" onClick={onAdmin}>Operations review</button>}<button className="header-button" onClick={onAccount}>{user ? "Open workspace" : "Sign in / Register"} <ArrowUpRight size={16}/></button><button className="menu-button" aria-label={menu ? 'Close menu' : 'Open menu'} aria-expanded={menu} onClick={() => setMenu(!menu)}>{menu ? <X/> : <Menu/>}</button></div></div></header>;
}

function Landing({ onAccount, onAdmin, user }) {
 return <><Header onAccount={onAccount} onAdmin={onAdmin} user={user}/><div className="launch-notice" role="status">Lugggiztik is being prepared for launch. Please do not enter real personal data or make real payments yet.</div><main>
  <section className="hero-wrap" aria-labelledby="hero-title"><div className="hero"><div className="hero-image" role="img" aria-label="Illustrative image of a freight truck on a highway"/><div className="hero-content"><div className="hero-kicker"><span className="kicker-dot"/> MADE FOR MOVEMENT IN NIGERIA</div><h1 id="hero-title">Good things<br/>are going <em>places.</em></h1><p>A simpler way to connect with trucks, compare bids, and move your goods with confidence.</p><div className="hero-actions"><button className="button button-lime" onClick={onAccount}>{user ? "Open your workspace" : "Get started"} <ArrowUpRight size={18}/></button><a className="text-link light-link hero-account" href="#how-it-works">How it works <ArrowUpRight size={17}/></a></div></div><div className="hero-bottom"><div className="hero-caption"><span className="caption-line"/> FROM PICKUP TO DELIVERY<br/><strong>Every journey, a little easier.</strong></div></div><div className="image-credit">Imagery is illustrative</div></div></section>
  <section className="intro-band"><div className="intro-band-inner"><div className="intro-label"><span className="tiny-square"/> A smarter way to move</div><p>Moving goods takes work.<br/><strong>Finding the right truck shouldn’t.</strong></p><div className="intro-note">For the businesses, truck owners, and drivers who keep Nigeria moving. <ArrowUpRight size={18}/></div></div></section>
  <section className="section process-section" id="how-it-works"><div className="section-heading"><div><span className="section-tag"><span/> THE JOURNEY, SIMPLIFIED</span><h2>From here to there,<br/><span>without the guesswork.</span></h2></div><p>One place to find the right fit, stay in the loop, and keep your business moving forward.</p></div><div className="steps"><article className="step"><div className="step-top"><span className="step-number">01</span><span className="step-icon"><Package/></span></div><h3>Tell us what’s moving</h3><p>Share your load, pickup point, and destination. Give carriers the details they need to make an offer.</p><span className="step-foot">POST A LOAD <ArrowUpRight size={14}/></span></article><article className="step"><div className="step-top"><span className="step-number">02</span><span className="step-icon"><Boxes/></span></div><h3>Find your right fit</h3><p>Compare bids and vehicle details, then choose the offer that works for your business.</p><span className="step-foot">REVIEW BIDS <ArrowUpRight size={14}/></span></article><article className="step"><div className="step-top"><span className="step-number">03</span><span className="step-icon"><Route/></span></div><h3>Follow the journey</h3><p>Keep up with delivery milestones from pickup through to the final handover.</p><span className="step-foot">TRACK PROGRESS <ArrowUpRight size={14}/></span></article></div></section>
  <section className="audience-section" id="who-its-for"><div className="section audience-inner"><div className="audience-copy"><span className="section-tag tag-light"><span/> TWO SIDES. ONE JOURNEY.</span><h2>Better together,<br/>on every trip.</h2><p>Whether you’re moving a load or looking for your next one, Lugggiztik brings the pieces together.</p><button className="button button-lime" onClick={onAccount}>Get started <ArrowUpRight size={18}/></button></div><div className="audience-cards"><article><div className="audience-card-icon"><Package size={23}/></div><span>FOR SHIPPERS</span><h3>Your goods.<br/>Your next move.</h3><p>Post what you need moved and find the right truck for the job.</p><ArrowUpRight className="audience-arrow" size={21}/></article><article><div className="audience-card-icon"><Truck size={23}/></div><span>FOR TRUCK OWNERS</span><h3>More opportunity<br/>on the road.</h3><p>Discover loads, submit bids, and put your fleet to work.</p><ArrowUpRight className="audience-arrow" size={21}/></article></div></div></section>
  <section className="section reassurance" id="why-lugggiztik"><div><span className="section-tag"><span/> MADE FOR REAL LIFE</span><h2>A little more clarity.<br/><span>A lot more confidence.</span></h2></div><div className="reassurance-list"><div><span className="reassure-icon"><FileCheck2/></span><div><h3>Details that matter</h3><p>Review vehicle information and documents as you consider a bid.</p></div></div><div><span className="reassure-icon"><MapPin/></span><div><h3>Progress you can follow</h3><p>See delivery milestones in one easy-to-understand timeline.</p></div></div><div><span className="reassure-icon"><ShieldCheck/></span><div><h3>Designed around trust</h3><p>Thoughtful workflows for every step, from your first bid to the final delivery.</p></div></div></div></section>
  <section className="closing"><div className="closing-inner"><div><span className="section-tag"><span/> LET’S GET MOVING</span><h2>There’s a better road ahead.</h2><p>Bring your next move together in one place.</p></div><button className="button button-dark" onClick={onAccount}>{user ? "Open workspace" : "Get started"} <ArrowUpRight size={18}/></button></div></section>
 </main><footer className="footer"><div className="footer-inner"><div><Brand light/><p>Helping good things get where they need to go.</p></div><div className="footer-right"><span>Designed for movement in Nigeria.</span><span>© {new Date().getFullYear()} Lugggiztik</span></div></div></footer></>;
}

function App(){
 const [screen,setScreen]=useState('landing'); const [user,setUser]=useState(null); const [authError,setAuthError]=useState('');const recovery=useRef(false),authEpoch=useRef(0);
 const go=(s)=>{setScreen(s);window.scrollTo(0,0)};
 const authenticated=(u,profileRequired)=>{authEpoch.current++;setAuthError('');setUser(u);go(profileRequired?'profile':'workspace')};
 useEffect(()=>{
  if(!supabaseMode){api('/auth/session').then(r=>setUser(r.user)).catch(()=>{});return;}
  let alive=true;
  const {data:{subscription}}=supabase.auth.onAuthStateChange((event,session)=>{
   if(!alive)return;
   const current=++authEpoch.current;
   if(event==='PASSWORD_RECOVERY'){recovery.current=true;setUser(null);setScreen('recovery');return;}
   if(event==='SIGNED_OUT'){setUser(null);setScreen(s=>['workspace','profile'].includes(s)?'landing':s);return;}
   if(session && !recovery.current){
    // Defer Auth-dependent work outside the SDK callback.
    setTimeout(async()=>{if(!alive||recovery.current||current!==authEpoch.current)return;try{const r=await api('/auth/session');if(!alive||recovery.current||current!==authEpoch.current)return;setAuthError('');setUser(r.user);if(r.profileRequired)setScreen('profile');else if(r.user)setScreen(s=>s==='account'?'workspace':s);}catch{if(alive&&current===authEpoch.current)setAuthError('Account service is unavailable. Please try again.');}},0);
   }
  });
  return ()=>{alive=false;subscription.unsubscribe()};
 },[]);
 if(screen==='recovery'&&supabaseMode)return <PasswordRecovery onDone={()=>{recovery.current=false;setUser(null);go('account')}}/>;
 if(screen==='profile'&&supabaseMode)return <ProfileSetup onBack={()=>{setUser(null);go('landing')}} onAuthenticated={authenticated}/>;
 if(screen==='account') return <Account onBack={()=>go('landing')} onAuthenticated={authenticated}/>;
 if(screen==='admin' && user?.isAdmin) return user.backend==='postgres-staging'?<StagingAdmin onBack={()=>go('landing')}/>:<Admin onBack={()=>go('landing')}/>;
 if(screen==='workspace' && user) return <Workspace user={user} onBack={()=>go('landing')} onLogout={()=>{setUser(null);go('landing')}}/>;
 return <>{authError&&<div className="launch-notice" role="alert">{authError}</div>}<Landing user={user} onAccount={()=>go(user?'workspace':'account')} onAdmin={()=>go('admin')}/></>;
}

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