
// RMTCTRL — Main App with router, phone frame, navigation

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "dashboardState": "pre-flight",
  "startScreen": "splash"
}/*EDITMODE-END*/;

function App() {
  const [tweaks] = React.useState(TWEAK_DEFAULTS);
  const [screen, setScreen] = React.useState(tweaks.startScreen);
  const [onboardStep, setOnboardStep] = React.useState(1);
  const [activeTab, setActiveTab] = React.useState('home');
  const [dashState, setDashState] = React.useState(tweaks.dashboardState);

  const navigate = (to) => {
    setScreen(to);
    if (['home', 'trips', 'workspaces', 'vault'].includes(to)) setActiveTab(to);
  };

  const showTabBar = ['home','trips','workspaces','vault','expenses','profile'].includes(screen);

  const renderScreen = () => {
    switch (screen) {
      case 'splash':       return <SplashScreen onDone={() => setScreen('onboard-1')} />;
      case 'onboard-1':   return <OnboardingAuth onNext={() => setScreen('onboard-2')} />;
      case 'onboard-2':   return <OnboardingPrefs onNext={() => setScreen('onboard-3')} />;
      case 'onboard-3':   return <OnboardingHomeBase onNext={() => { setScreen('home'); setActiveTab('home'); }} />;
      case 'home':        return <Dashboard state={dashState} onNavigate={navigate} />;
      case 'trips':       return <TripsList onNavigate={navigate} />;
      case 'trip-detail': return <TripDetail onBack={() => navigate('trips')} onNavigate={navigate} />;
      case 'add-segment': return <AddSegment onBack={() => navigate('trip-detail')} />;
      case 'workspaces':  return <WorkspaceMap onNavigate={navigate} />;
      case 'workspace-detail': return <WorkspaceDetail onBack={() => navigate('workspaces')} onNavigate={navigate} />;
      case 'add-workspace':    return <AddWorkspace onBack={() => navigate('workspaces')} />;
      case 'vault':       return <VaultScreen onNavigate={navigate} />;
      case 'doc-detail':  return <DocDetail onBack={() => navigate('vault')} />;
      case 'country':     return <CountryProfile onBack={() => navigate('home')} onNavigate={navigate} />;
      case 'calendar':    return <CalendarScreen onNavigate={navigate} />;
      case 'expenses':    return <ExpensesScreen onNavigate={navigate} />;
      case 'currency':    return <CurrencyConverter onBack={() => navigate('expenses')} />;
      case 'submit-review': return <SubmitReview onBack={() => navigate('workspace-detail')} />;
      case 'profile':     return <ProfileScreen />;
      default:            return <Dashboard state={dashState} onNavigate={navigate} />;
    }
  };

  return (
    <div style={{
      width: '100%', height: '100%', display: 'flex', flexDirection: 'column',
      background: TOKENS.color.bg, color: TOKENS.color.textPrimary, position: 'relative', overflow: 'hidden',
    }}>
      {/* Safe area top */}
      <div style={{ height: 50, flexShrink: 0, background: TOKENS.color.bg, display: 'flex', alignItems: 'flex-end', justifyContent: 'center', paddingBottom: 8, position: 'relative', zIndex: 20 }}>
        {/* Status bar */}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', width: '100%', padding: '0 24px' }}>
          <span style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 13, fontWeight: 600, color: TOKENS.color.textPrimary }}>9:41</span>
          <div style={{ width: 126, height: 34, background: TOKENS.color.bg, borderRadius: 999, border: '1px solid #1F1F26', position: 'absolute', left: '50%', transform: 'translateX(-50%)', top: 10 }} />
          <div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
            <svg width="16" height="12" viewBox="0 0 16 12" fill="none">
              <rect x="0" y="4" width="3" height="8" rx="1" fill="#F5F5F7"/>
              <rect x="4.5" y="2.5" width="3" height="9.5" rx="1" fill="#F5F5F7"/>
              <rect x="9" y="1" width="3" height="11" rx="1" fill="#F5F5F7"/>
              <rect x="13.5" y="0" width="2.5" height="12" rx="1" fill="#F5F5F7"/>
            </svg>
            <svg width="16" height="12" viewBox="0 0 24 24" fill="#F5F5F7"><path d="M1.41 8.59A13.5 13.5 0 0 1 12 4c3.87 0 7.35 1.62 9.83 4.22L23 7.05A15.5 15.5 0 0 0 12 2C8.36 2 4.97 3.38 2.42 5.74L1.41 8.59z"/><path d="M5.55 12.73A8 8 0 0 1 12 10c2.53 0 4.8 1.18 6.29 3.02L19.71 12A10 10 0 0 0 12 8a10 10 0 0 0-7.42 3.29l.97 1.44z"/><circle cx="12" cy="18" r="3"/></svg>
            <div style={{ display: 'flex', alignItems: 'center', gap: 2 }}>
              <div style={{ width: 24, height: 12, borderRadius: 3, border: '1.5px solid #F5F5F7', padding: 2, display: 'flex', gap: 1 }}>
                <div style={{ flex: 0.9, background: TOKENS.color.accent, borderRadius: 1 }} />
              </div>
              <div style={{ width: 2, height: 6, background: TOKENS.color.textPrimary, borderRadius: 1 }} />
            </div>
          </div>
        </div>
      </div>

      {/* Screen content */}
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden', position: 'relative' }}>
        {renderScreen()}
      </div>

      {/* Bottom Tab Bar */}
      {showTabBar && (
        <div style={{ flexShrink: 0, position: 'relative' }}>
          <BottomTabBar active={activeTab} onNavigate={(tab) => { setActiveTab(tab); setScreen(tab); }} />
          {/* Quick nav for non-tab screens */}
          {!['home','trips','workspaces','vault'].includes(screen) && ['expenses','profile','calendar'].includes(screen) === false && (
            <div style={{ display: 'none' }} />
          )}
        </div>
      )}

      {/* Nav overflow buttons when on sub-screen */}
      {screen === 'home' && (
        <div style={{ position: 'absolute', top: 52, right: 0, zIndex: 0 }} />
      )}
    </div>
  );
}

// ── Screen selector overlay (dev navigation) ──────────────────────────────────
function DevNav({ onSelect }) {
  const screens = [
    { label: 'Splash', id: 'splash' },
    { label: 'Auth', id: 'onboard-1' },
    { label: 'Work Prefs', id: 'onboard-2' },
    { label: 'Home Base', id: 'onboard-3' },
    { label: '◆ Dashboard (pre-flight)', id: 'home', extra: 'pre-flight' },
    { label: '◆ Dashboard (mid-trip)', id: 'home', extra: 'mid-trip' },
    { label: '◆ Dashboard (no-trip)', id: 'home', extra: 'no-trip' },
    { label: 'Trips List', id: 'trips' },
    { label: 'Trip Detail', id: 'trip-detail' },
    { label: 'Add Segment', id: 'add-segment' },
    { label: 'Workspace Map', id: 'workspaces' },
    { label: 'Workspace Detail', id: 'workspace-detail' },
    { label: 'Add Workspace', id: 'add-workspace' },
    { label: 'Vault', id: 'vault' },
    { label: 'Doc Detail', id: 'doc-detail' },
    { label: 'Country Profile', id: 'country' },
    { label: 'Calendar', id: 'calendar' },
    { label: 'Expenses', id: 'expenses' },
    { label: 'Currency Converter', id: 'currency' },
    { label: 'Submit Review', id: 'submit-review' },
    { label: 'Profile / Settings', id: 'profile' },
  ];
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 0, overflowY: 'auto', flex: 1 }}>
      {screens.map((s, i) => (
        <button key={i} onClick={() => onSelect(s.id, s.extra)} style={{
          height: 40, background: 'none', border: 'none', borderBottom: '1px solid #26262E',
          cursor: 'pointer', textAlign: 'left', padding: '0 16px',
          fontFamily: "'Inter',sans-serif", fontSize: 13, color: TOKENS.color.textPrimary,
          display: 'flex', alignItems: 'center', gap: 8,
          transition: `background ${TOKENS.anim.fast}`,
        }}>
          <span style={{ width: 20, fontFamily: "'JetBrains Mono',monospace", fontSize: 10, color: TOKENS.color.textTertiary }}>{String(i+1).padStart(2,'0')}</span>
          {s.label}
        </button>
      ))}
    </div>
  );
}

// ── Root wrapper with phone frame ─────────────────────────────────────────────
function Root() {
  const [screen, setScreen] = React.useState(TWEAK_DEFAULTS.startScreen);
  const [dashState, setDashState] = React.useState(TWEAK_DEFAULTS.dashboardState);
  const [navOpen, setNavOpen] = React.useState(false);
  const [appKey, setAppKey] = React.useState(0);

  const handleSelect = (id, extra) => {
    setNavOpen(false);
    if (extra) setDashState(extra);
    // Force re-mount of App with new initial screen
    window.__initScreen = id;
    window.__initDashState = extra || dashState;
    setAppKey(k => k + 1);
  };

  return (
    <div style={{ minHeight: '100vh', background: '#080810', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '20px', fontFamily: "'Inter',sans-serif" }}>
      <div style={{ display: 'flex', gap: 24, alignItems: 'flex-start', flexWrap: 'wrap', justifyContent: 'center' }}>

        {/* Screen nav panel */}
        <div style={{ width: 220, background: TOKENS.color.bg, borderRadius: 16, border: '1px solid #26262E', overflow: 'hidden', display: 'flex', flexDirection: 'column', maxHeight: 780 }}>
          <div style={{ padding: '14px 16px', borderBottom: '1px solid #26262E', display: 'flex', alignItems: 'center', gap: 8 }}>
            <div style={{ width: 8, height: 8, borderRadius: '50%', background: TOKENS.color.accent, animation: 'pill-pulse 1.5s ease-in-out infinite' }} />
            <span style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 11, fontWeight: 600, color: TOKENS.color.accent, letterSpacing: '0.08em' }}>21 SCREENS</span>
          </div>
          <DevNav onSelect={handleSelect} />
        </div>

        {/* Phone frame */}
        <div style={{
          width: 393, height: 852, borderRadius: 54,
          background: TOKENS.color.bg,
          boxShadow: '0 0 0 10px #1A1A22, 0 0 0 12px #26262E, 0 40px 80px rgba(0,0,0,0.8)',
          overflow: 'hidden', position: 'relative', flexShrink: 0,
          display: 'flex', flexDirection: 'column',
        }}>
          <AppInstance key={appKey} initScreen={window.__initScreen || TWEAK_DEFAULTS.startScreen} initDashState={window.__initDashState || TWEAK_DEFAULTS.dashboardState} />
        </div>

        {/* Component library panel */}
        <div style={{ width: 260, display: 'flex', flexDirection: 'column', gap: 16, maxHeight: 852, overflowY: 'auto' }}>
          <ComponentLibraryPanel />
        </div>
      </div>
    </div>
  );
}

// Separate App instance so we can re-mount with different initial state
function AppInstance({ initScreen, initDashState }) {
  const [screen, setScreen] = React.useState(initScreen || 'splash');
  const [activeTab, setActiveTab] = React.useState('home');
  const [dashState, setDashState] = React.useState(initDashState || 'pre-flight');

  const navigate = (to, extra) => {
    setScreen(to);
    if (['home','trips','workspaces','vault'].includes(to)) setActiveTab(to);
    if (extra) setDashState(extra);
  };

  const showTabBar = ['home','trips','workspaces','vault','expenses','profile','calendar'].includes(screen);

  const renderScreen = () => {
    switch (screen) {
      case 'splash':          return <SplashScreen onDone={() => setScreen('onboard-1')} />;
      case 'onboard-1':       return <OnboardingAuth onNext={() => setScreen('onboard-2')} />;
      case 'onboard-2':       return <OnboardingPrefs onNext={() => setScreen('onboard-3')} />;
      case 'onboard-3':       return <OnboardingHomeBase onNext={() => { setScreen('home'); setActiveTab('home'); }} />;
      case 'home':            return <Dashboard state={dashState} onNavigate={navigate} />;
      case 'trips':           return <TripsList onNavigate={navigate} />;
      case 'trip-detail':     return <TripDetail onBack={() => navigate('trips')} onNavigate={navigate} />;
      case 'add-segment':     return <AddSegment onBack={() => navigate('trip-detail')} />;
      case 'workspaces':      return <WorkspaceMap onNavigate={navigate} />;
      case 'workspace-detail':return <WorkspaceDetail onBack={() => navigate('workspaces')} onNavigate={navigate} />;
      case 'add-workspace':   return <AddWorkspace onBack={() => navigate('workspaces')} />;
      case 'vault':           return <VaultScreen onNavigate={navigate} />;
      case 'doc-detail':      return <DocDetail onBack={() => navigate('vault')} />;
      case 'country':         return <CountryProfile onBack={() => navigate('home')} onNavigate={navigate} />;
      case 'calendar':        return <CalendarScreen onNavigate={navigate} />;
      case 'expenses':        return <ExpensesScreen onNavigate={navigate} />;
      case 'currency':        return <CurrencyConverter onBack={() => navigate('expenses')} />;
      case 'submit-review':   return <SubmitReview onBack={() => navigate('workspace-detail')} />;
      case 'profile':         return <ProfileScreen />;
      default:                return <Dashboard state={dashState} onNavigate={navigate} />;
    }
  };

  return (
    <div style={{ width: '100%', height: '100%', display: 'flex', flexDirection: 'column', background: TOKENS.color.bg, color: TOKENS.color.textPrimary, position: 'relative', overflow: 'hidden' }}>
      {/* Status bar */}
      <div style={{ height: 50, flexShrink: 0, background: TOKENS.color.bg, position: 'relative', zIndex: 20 }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '14px 28px 0' }}>
          <span style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 13, fontWeight: 600, color: TOKENS.color.textPrimary }}>9:41</span>
          <div style={{ width: 120, height: 30, background: TOKENS.color.bg, borderRadius: 999, border: '1px solid #1F1F26', position: 'absolute', left: '50%', transform: 'translateX(-50%)', top: 8 }} />
          <div style={{ display: 'flex', gap: 5, alignItems: 'center' }}>
            <WifiIcon size={14} color="#F5F5F7" />
            <div style={{ display: 'flex', alignItems: 'center', gap: 2 }}>
              <div style={{ width: 22, height: 11, borderRadius: 3, border: '1.5px solid #F5F5F7', padding: '1.5px', display: 'flex', gap: 1 }}>
                <div style={{ flex: 0.88, background: TOKENS.color.accent, borderRadius: 1 }} />
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Screen */}
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden', position: 'relative' }}>
        {renderScreen()}
      </div>

      {/* Bottom tab bar */}
      {showTabBar && (
        <div style={{ flexShrink: 0 }}>
          <BottomTabBar active={activeTab} onNavigate={(tab) => { setActiveTab(tab); setScreen(tab); }} />
        </div>
      )}
    </div>
  );
}

// ── Component Library Panel ───────────────────────────────────────────────────
function ComponentLibraryPanel() {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
      {/* Status Pills */}
      <div style={{ background: TOKENS.color.bg, borderRadius: 16, border: '1px solid #26262E', padding: 16 }}>
        <div style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 10, fontWeight: 600, color: TOKENS.color.textTertiary, letterSpacing: '0.08em', marginBottom: 12 }}>STATUS PILLS · 9 STATES</div>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
          {['ON TIME','DELAYED 23M','BOARDING','GATE B12','LANDED','CANCELLED','WORK BLOCK','IN TRANSIT','ARRIVED'].map(s => (
            <StatusPill key={s} label={s} />
          ))}
        </div>
      </div>

      {/* Buttons */}
      <div style={{ background: TOKENS.color.bg, borderRadius: 16, border: '1px solid #26262E', padding: 16 }}>
        <div style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 10, fontWeight: 600, color: TOKENS.color.textTertiary, letterSpacing: '0.08em', marginBottom: 12 }}>BUTTONS</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          <Btn variant="primary" size="md" fullWidth>Primary green</Btn>
          <Btn variant="secondary" size="md" fullWidth>Secondary outlined</Btn>
          <Btn variant="ghost" size="md" fullWidth>Ghost text</Btn>
          <Btn variant="destructive" size="md" fullWidth>Destructive</Btn>
          <div style={{ display: 'flex', gap: 8 }}>
            <Btn variant="primary" size="sm">SM</Btn>
            <Btn variant="primary" size="md">MD</Btn>
            <Btn variant="primary" size="lg">LG</Btn>
          </div>
        </div>
      </div>

      {/* Filter chips */}
      <div style={{ background: TOKENS.color.bg, borderRadius: 16, border: '1px solid #26262E', padding: 16 }}>
        <div style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 10, fontWeight: 600, color: TOKENS.color.textTertiary, letterSpacing: '0.08em', marginBottom: 12 }}>FILTER CHIPS</div>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
          <FilterChip label="All" selected={true} />
          <FilterChip label="Quiet" selected={false} />
          <FilterChip label="Fast Wi-Fi" selected={false} />
          <FilterChip label="24/7" selected={true} />
        </div>
      </div>

      {/* Avatars */}
      <div style={{ background: TOKENS.color.bg, borderRadius: 16, border: '1px solid #26262E', padding: 16 }}>
        <div style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 10, fontWeight: 600, color: TOKENS.color.textTertiary, letterSpacing: '0.08em', marginBottom: 12 }}>AVATAR</div>
        <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
          <Avatar size={24} initials="A" color="#00FF94" />
          <Avatar size={32} initials="AL" color="#3B9EFF" />
          <Avatar size={40} initials="AL" color="#FFB800" />
          <Avatar size={56} initials="AL" color="#00FF94" />
        </div>
      </div>

      {/* Skeleton */}
      <div style={{ background: TOKENS.color.bg, borderRadius: 16, border: '1px solid #26262E', padding: 16 }}>
        <div style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 10, fontWeight: 600, color: TOKENS.color.textTertiary, letterSpacing: '0.08em', marginBottom: 12 }}>SKELETON</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          <Skeleton height={16} width="80%" />
          <Skeleton height={60} />
          <Skeleton height={12} width="50%" />
        </div>
      </div>

      {/* Toggle */}
      <div style={{ background: TOKENS.color.bg, borderRadius: 16, border: '1px solid #26262E', padding: 16 }}>
        <div style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 10, fontWeight: 600, color: TOKENS.color.textTertiary, letterSpacing: '0.08em', marginBottom: 12 }}>TOGGLE</div>
        <div style={{ display: 'flex', gap: 16, alignItems: 'center' }}>
          <Toggle on={true} onChange={() => {}} />
          <Toggle on={false} onChange={() => {}} />
        </div>
      </div>

      {/* Empty state */}
      <div style={{ background: TOKENS.color.bg, borderRadius: 16, border: '1px solid #26262E', overflow: 'hidden' }}>
        <div style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 10, fontWeight: 600, color: TOKENS.color.textTertiary, letterSpacing: '0.08em', padding: '16px 16px 0' }}>EMPTY STATE</div>
        <EmptyState icon={<GlobeIcon size={48} />} headline="No trips yet" sub='Tap + to add one' cta="New trip" />
      </div>
    </div>
  );
}

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