/* global React, ReactDOM */
const { useState, useEffect } = React;

// ─────────── Applicant Sidebar ───────────
const ApplicantSidebar = ({ view, setView }) => {
  const items = [
    { k:'dashboard', label:'My application', icon:'grid' },
    { k:'intake', label:'Smart intake', icon:'chat', badge:'100%' },
    { k:'contradiction', label:'Resolve conflicts', icon:'warn', tone:'warn' },
    { k:'checklist', label:'Documents', icon:'folder', badge:'5/7' },
    { k:'messages', label:'Messages', icon:'mail', count:1 },
    { k:'draft', label:'Draft preview', icon:'doc' },
    { k:'final', label:'Final review', icon:'check' },
    { k:'delivery', label:'Filing & delivery', icon:'send' },
    { k:'audit', label:'My audit log', icon:'clock' },
    { k:'retention', label:'Retention & data', icon:'shield' },
  ];
  return (
    <aside className="sidebar">
      <div className="sidebar-section">Your case</div>
      <div style={{padding:'4px 10px 12px'}}>
        <div style={{padding:'10px 12px', background:'var(--accent-soft)', borderRadius:10}}>
          <div className="mono tiny" style={{color:'var(--accent-ink)', letterSpacing:'.12em', textTransform:'uppercase', fontSize:10}}>Case ID</div>
          <div className="mono" style={{fontSize:13, fontWeight:500, color:'var(--accent-ink)', marginTop:2}}>GE-2026-4782</div>
          <div className="tiny" style={{marginTop:6}}>SSDI · started Apr 21</div>
        </div>
      </div>
      <div className="sidebar-section">Application</div>
      {items.map(it => (
        <div key={it.k} className={`nav-item ${view===it.k?'on':''} ${it.tone||''}`} onClick={()=>setView(it.k)}>
          <Icon name={it.icon} size={15}/> <span>{it.label}</span>
          {it.badge && <span className="count">{it.badge}</span>}
          {it.count && <span className="count" style={{background:'var(--warn)', color:'#fff'}}>{it.count}</span>}
        </div>
      ))}
    </aside>
  );
};

// ─────────── Applicant shell router ───────────
const ApplicantApp = ({ homeNonce }) => {
  const [view, setView] = useState(() => localStorage.getItem('govease_av') || 'landing');
  useEffect(() => { localStorage.setItem('govease_av', view); }, [view]);
  useEffect(() => {
    setView('landing');
  }, [homeNonce]);

  // Pre-auth flow
  if (view === 'landing') return <ApplicantLanding onStart={(next = 'signin')=>setView(next === 'signup' ? 'lang-signup' : 'lang-signin')}/>;
  if (view === 'lang-signin') return <LanguageGate onDone={()=>setView('signin')}/>;
  if (view === 'lang-signup') return <LanguageGate onDone={()=>setView('signup')}/>;
  if (view === 'signin') return <ApplicantAuth mode="signin" onDone={()=>setView('mfa')} onForgot={()=>setView('forgot')} onSwitch={(next)=>setView(next)}/>;
  if (view === 'signup') return <ApplicantAuth mode="signup" onDone={()=>setView('mfa')} onSwitch={(next)=>setView(next)}/>;
  if (view === 'mfa') return <ApplicantMFA onDone={()=>setView('consent')}/>;
  if (view === 'forgot') return <ApplicantForgot onDone={()=>setView('signin')} onBack={()=>setView('signin')}/>;
  if (view === 'consent') return <ApplicantConsent onDone={()=>setView('casetype')}/>;
  if (view === 'casetype') return <CaseTypeSelect onDone={()=>setView('preflight')}/>;
  if (view === 'preflight') return <PreFlight onDone={()=>setView('intake')}/>;

  // Authed navigable app
  return (
    <div className="app-frame">
      <ApplicantSidebar view={view} setView={setView}/>
      {view === 'intake' && <SmartIntake onDone={()=>setView('contradiction')} onMessages={()=>setView('messages')}/>}
      {view === 'contradiction' && <ContradictionScreen onDone={()=>setView('checklist')} onBack={()=>setView('intake')}/>}
      {view === 'checklist' && <DocChecklist onUpload={()=>setView('upload')} onDone={()=>setView('dashboard')}/>}
      {view === 'upload' && <DocUpload onDone={()=>setView('review')} onBack={()=>setView('checklist')}/>}
      {view === 'docupload' && <DocUpload onDone={()=>setView('review')} onBack={()=>setView('dashboard')}/>}
      {view === 'review' && <UploadReview onDone={()=>setView('dashboard')} onBack={()=>setView('upload')}/>}
      {view === 'dashboard' && <ApplicantDashboard nav={setView}/>}
      {view === 'messages' && <ApplicantMessages onBack={()=>setView('dashboard')}/>}
      {view === 'draft' && <DraftPreview onDone={()=>setView('final')} onBack={()=>setView('dashboard')}/>}
      {view === 'final' && <FinalReview onDone={()=>setView('delivery')} onBack={()=>setView('draft')}/>}
      {view === 'delivery' && <DeliveryScreen onDone={()=>setView('dashboard')}/>}
      {view === 'audit' && <ApplicantAudit onBack={()=>setView('dashboard')}/>}
      {view === 'retention' && <RetentionScreen onBack={()=>setView('dashboard')}/>}
    </div>
  );
};

// ─────────── Reviewer shell router ───────────
const ReviewerApp = () => {
  const [view, setView] = useState(() => localStorage.getItem('govease_rv') || 'login');
  const [modal, setModal] = useState(null);
  useEffect(() => { localStorage.setItem('govease_rv', view); }, [view]);

  if (view === 'login') return <ReviewerLogin onDone={()=>setView('queue')}/>;

  return (
    <div className="app-frame">
      <ReviewerSidebar view={view} setView={setView}/>
      {view === 'queue' && <ReviewerQueue onOpen={()=>setView('workspace')}/>}
      {view === 'unassigned' && <ReviewerQueue onOpen={()=>setView('workspace')}/>}
      {view === 'waiting' && <ReviewerQueue onOpen={()=>setView('workspace')}/>}
      {view === 'escalated' && <ReviewerQueue onOpen={()=>setView('workspace')}/>}
      {view === 'workspace' && <ReviewerWorkspace
        onDiff={()=>setView('diff')}
        onDocReview={()=>setView('docreview')}
        onAudit={()=>setView('audit')}
        onRequestInfo={()=>setModal('info')}
        onApprove={()=>setModal('approve')}
        onEscalate={()=>setModal('escalate')}
      />}
      {view === 'diff' && <ReviewerDiff onBack={()=>setView('workspace')}/>}
      {view === 'docreview' && <ReviewerDocReview onBack={()=>setView('workspace')}/>}
      {view === 'audit' && <ReviewerAudit onBack={()=>setView('workspace')}/>}
      {view === 'analytics' && <ReviewerAnalytics/>}

      {modal === 'info' && <RequestInfoModal onClose={()=>setModal(null)}/>}
      {modal === 'approve' && <ApproveModal onClose={()=>setModal(null)} onDone={()=>{ setModal(null); setView('queue'); }}/>}
      {modal === 'escalate' && <EscalateModal onClose={()=>setModal(null)}/>}
    </div>
  );
};

// ─────────── Admin shell router ───────────
const AdminApp = () => {
  const [view, setView] = useState(() => localStorage.getItem('govease_ad') || 'dashboard');
  useEffect(() => { localStorage.setItem('govease_ad', view); }, [view]);
  return (
    <div className="app-frame">
      <AdminSidebar view={view} setView={setView}/>
      {view === 'dashboard' && <AdminDashboard nav={setView}/>}
      {view === 'monitoring' && <AdminMonitoring/>}
      {view === 'cases' && <AdminCases/>}
      {view === 'users' && <AdminUsers/>}
      {view === 'retention' && <AdminRetention/>}
      {view === 'consent' && <AdminConsent/>}
      {view === 'templates' && <AdminTemplates/>}
      {view === 'audit' && <AdminAudit/>}
      {view === 'ai' && <AdminAI/>}
      {view === 'security' && <AdminSecurity/>}
    </div>
  );
};

// ─────────── Root ───────────
const App = () => {
  const [tweaks, setTweaksState] = useTweakState();
  const [persona, setPersona] = useState(() => localStorage.getItem('govease_persona') || 'applicant');
  const [homeNonce, setHomeNonce] = useState(0);
  const [tweaksOpen, setTweaksOpen] = useState(false);
  const [editMode, setEditMode] = useState(false);

  useEffect(() => { localStorage.setItem('govease_persona', persona); }, [persona]);

  // Tweaks host integration
  useEffect(() => {
    const handler = (e) => {
      if (!e.data || typeof e.data !== 'object') return;
      if (e.data.type === '__activate_edit_mode') setEditMode(true);
      if (e.data.type === '__deactivate_edit_mode') setEditMode(false);
    };
    window.addEventListener('message', handler);
    try { window.parent.postMessage({type: '__edit_mode_available'}, '*'); } catch {}
    return () => window.removeEventListener('message', handler);
  }, []);

  const setTweaks = (patch) => setTweaksState(patch);
  const goHome = () => {
    setPersona('applicant');
    setHomeNonce(n => n + 1);
  };

  return (
    <AppCtx.Provider value={{ tweaks, setTweaks, persona, setPersona }}>
      <div className="app-root" data-density={tweaks.density}>
        <TopBar persona={persona} setPersona={setPersona} onHome={goHome}/>
        {persona === 'applicant' && <ApplicantApp homeNonce={homeNonce}/>}
        {persona === 'reviewer' && <ReviewerApp/>}
        {persona === 'admin' && <AdminApp/>}

        {editMode && (
          <>
            <div className="tweaks-scrim" onClick={()=>setTweaksOpen(false)}/>
            <TweaksPanel onClose={()=>setEditMode(false)}/>
          </>
        )}
      </div>
    </AppCtx.Provider>
  );
};

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