// crm-main.jsx — Main entry. Loaded LAST by the cache-busting
// loader in CRM.html so every component is defined before App() runs.
const { useState, useEffect, useRef, useCallback } = React;

class ErrorBoundary extends React.Component {
  constructor(props) { super(props); this.state = { error: null }; }
  static getDerivedStateFromError(e) { return { error: e }; }
  render() {
    if (this.state.error) {
      return (
        <div style={{padding:40,textAlign:'center',color:'#BC141E'}}>
          <div style={{fontSize:24,marginBottom:12}}>⚠️</div>
          <div style={{fontWeight:700,marginBottom:8}}>Something went wrong loading this view.</div>
          <div style={{fontSize:13,color:'#5A6478',marginBottom:16}}>{String(this.state.error)}</div>
          <button onClick={() => this.setState({error:null})}
            style={{padding:'8px 20px',background:'#162534',color:'white',border:'none',borderRadius:6,cursor:'pointer',fontFamily:'inherit',fontWeight:600}}>
            Try Again
          </button>
        </div>
      );
    }
    return this.props.children;
  }
}

function App() {
  const [user, setUser] = useState(null);
  const [checking, setChecking] = useState(true);
  const [view, setView] = useState('dashboard');
  const [adminTab, setAdminTab] = useState('users');
  const [toasts, setToasts] = useState([]);
  const [sidebarOpen,    setSidebarOpen]    = useState(false);
  const [quickAdd,       setQuickAdd]       = useState(null);
  const [showMyEmail,    setShowMyEmail]    = useState(false);

  const handleQuickAdd = (type) => {
    const viewMap = { lead:'leads', account:'accounts', sale:'accounts', ticket:'tickets' };
    setView(viewMap[type] || 'dashboard');
    setQuickAdd({ type, key: Date.now() });
  };

  // Deep-links: jump to Accounts/Leads with a specific record's detail
  // open (dashboard widgets + global search use these).
  const [openAccountId, setOpenAccountId] = useState(null);
  const openAccount = (id) => { setOpenAccountId(id); setView('accounts'); };
  const [openLeadId, setOpenLeadId] = useState(null);
  const openLead = (id) => { setOpenLeadId(id); setView('leads'); };

  useEffect(() => {
    fetch('/api/auth/me', { credentials: 'include' })
      .then(r => r.ok ? r.json() : null)
      .then(async u => {
        if (u) {
          await Promise.all([
            CRM.UsersAPI.fetch().catch(() => {}),
            CRM.DropdownsAPI.load().catch(() => {}),
          ]);
          setUser(u);
          setView(u.role === 'tech' ? 'tickets' : 'dashboard');
        }
        setChecking(false);
      })
      .catch(() => setChecking(false));
  }, []);

  const showToast = useCallback((msg, type) => {
    const id = Date.now();
    setToasts(t => [...t, { id, msg, type: type || 'default' }]);
    setTimeout(() => setToasts(t => t.filter(x => x.id !== id)), 3000);
  }, []);

  const login = async (u) => {
    await Promise.all([
      CRM.UsersAPI.fetch().catch(() => {}),
      CRM.DropdownsAPI.load().catch(() => {}),
    ]);
    setUser(u);
    setView(u.role === 'tech' ? 'tickets' : 'dashboard');
  };

  const logout = async () => {
    await fetch('/api/auth/logout', { method: 'POST', credentials: 'include' });
    setUser(null);
  };

  if (checking) return (
    <div style={{display:'flex',alignItems:'center',justifyContent:'center',height:'100vh',background:'var(--folio-brand-900,#0A131E)',flexDirection:'column',gap:18}}>
      <span style={{color:'#fff',fontFamily:"'Inter',sans-serif",fontWeight:600,fontSize:22,letterSpacing:'-0.02em',display:'inline-flex',alignItems:'baseline',gap:6}}>
        <svg width="22" height="22" viewBox="0 0 24 24" fill="none" aria-hidden="true">
          <path d="M5 4 H17 A2 2 0 0 1 19 6 V20 L13 16 L7 20 V6 A2 2 0 0 1 9 4 Z" fill="currentColor" opacity="0.18" />
          <path d="M5 4 H17 A2 2 0 0 1 19 6 V20 L13 16 L7 20 V6 A2 2 0 0 1 9 4 Z" stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round" />
        </svg>
        Folio<small style={{fontWeight:400,fontSize:'0.62em',opacity:0.62,textTransform:'lowercase'}}>CRM</small>
      </span>
      <div style={{color:'rgba(255,255,255,0.5)',fontSize:12,fontFamily:'Inter,sans-serif',letterSpacing:'0.05em',textTransform:'uppercase'}}>Loading</div>
    </div>
  );

  if (!user) return <LoginScreen onLogin={login} />;

  const closeSidebar = () => setSidebarOpen(false);

  return (
    <div className="shell">
      <div className={`mob-backdrop${sidebarOpen ? ' open' : ''}`} onClick={closeSidebar} />
      <Sidebar view={view} setView={setView} adminTab={adminTab} setAdminTab={setAdminTab} user={user} onLogout={logout} isOpen={sidebarOpen} onClose={closeSidebar} onMyEmail={() => setShowMyEmail(true)} />
      <div className="main">
        <Topbar view={view} adminTab={adminTab} user={user} onMenuClick={() => setSidebarOpen(o => !o)} onQuickAdd={handleQuickAdd}
          onOpenAccount={openAccount} onOpenLead={openLead} />
        <div className="content">
          <ErrorBoundary key={view + adminTab}>
            {view === 'dashboard'        && (user.isAdmin || user.role !== 'tech') && <Dashboard user={user} setView={setView} showToast={showToast} onOpenAccount={openAccount} onOpenLead={openLead} />}
            {view === 'pipeline'         && (user.isAdmin || user.role !== 'tech') && <Pipeline  user={user} showToast={showToast} />}
            {view === 'leads'            && (user.isAdmin || user.role !== 'tech') && <Leads     user={user} showToast={showToast} quickAdd={quickAdd?.type==='lead' ? quickAdd : null} openLeadId={openLeadId} onOpenedLead={() => setOpenLeadId(null)} />}
            {view === 'accounts'         && (user.isAdmin || user.role !== 'tech') && <Accounts  user={user} showToast={showToast} quickAdd={quickAdd?.type==='account'||quickAdd?.type==='sale' ? quickAdd : null} openAccountId={openAccountId} onOpenedAccount={() => setOpenAccountId(null)} />}
            {view === 'tickets'          && <Tickets user={user} showToast={showToast} quickAdd={quickAdd?.type==='ticket' ? quickAdd : null} />}
            {view === 'helpcenter'       && <HelpCenterView user={user} showToast={showToast} />}
            {view === 'reports'          && (user.isAdmin || user.role !== 'tech') && <Reports user={user} showToast={showToast} />}
            {view === 'admin'            && user.isAdmin && <AdminView user={user} showToast={showToast} tab={adminTab} />}
            {view === 'dataio'           && <DataIO user={user} showToast={showToast} />}
            {view === 'sales'            && (user.isAdmin || user.role !== 'tech') && <SalesView user={user} showToast={showToast} setView={setView} />}
            {view === 'aod'              && user.isAdmin && CRM.connectors?.aod !== false && <AodView user={user} showToast={showToast} />}
            {view === 'library'          && (user.isAdmin || user.role !== 'tech') && <LibraryView user={user} showToast={showToast} />}
          </ErrorBoundary>
        </div>
        <AppFooter />
      </div>
      <BottomNav view={view} setView={setView} user={user} onMore={() => setSidebarOpen(true)} />
      {typeof FloatingChat === 'function' && <FloatingChat user={user} />}
      {showMyEmail && <MyEmailSettingsModal user={user} onClose={() => setShowMyEmail(false)} showToast={showToast} />}
      <div className="toast-wrap">
        {toasts.map(t => <div key={t.id} className={`toast ${t.type}`}>{t.msg}</div>)}
      </div>
    </div>
  );
}

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