// v-main.jsx — app state, session machine, routing, mount

function App() {
  const session = useSession();
  const [page, setPage] = React.useState('map');
  const [selected, setSelected] = React.useState(null);
  const [range, setRange] = React.useState('today');
  const [toast, setToast] = React.useState(null);
  const [builder, setBuilder] = React.useState({ open:false, estateId:null, item:null, template:null });
  const [campaignFocus, setCampaignFocus] = React.useState(null);
  const [mustard, setMustard] = React.useState(null); // label of the Mustard Seed area tapped
  const [paletteOpen, setPaletteOpen] = React.useState(false);
  const scrollRef = React.useRef(null);

  const role = session.sess ? session.sess.role : 'owner';

  const nav = (p) => { setPage(p); if (scrollRef.current) scrollRef.current.scrollTop = 0; };

  // ⌘K / Ctrl+K → command palette
  React.useEffect(()=>{
    const onKey = (e)=>{
      if ((e.metaKey || e.ctrlKey) && (e.key==='k' || e.key==='K')) { e.preventDefault(); setPaletteOpen(o=>!o); }
    };
    window.addEventListener('keydown', onKey);
    return ()=>window.removeEventListener('keydown', onKey);
  }, []);

  // Land each role on a page it can actually open
  React.useEffect(()=>{
    if (session.phase==='signedin' && !roleCanSee(role, page)) {
      setPage(role==='staff' ? 'orders' : 'overview');
    }
  }, [session.phase, role]);

  const app = {
    page, nav, selected, setSelected, range, setRange,
    toast: (m) => setToast(m),
    builder,
    openBuilder: (estateId, item=null, template=null) => setBuilder({ open:true, estateId, item, template }),
    closeBuilder: () => setBuilder(b => ({ ...b, open:false })),
    campaignFocus,
    openCampaign: (id) => { setCampaignFocus(id); nav('campaigns'); },
    clearCampaignFocus: () => setCampaignFocus(null),
    session, role,
    openPalette: () => setPaletteOpen(true),
    openMustard: (label) => setMustard(label || 'Back office'),
  };

  // ── Session phases ────────────────────────────────────────────────
  if (session.phase === 'restoring') {
    return <div style={{ position:'relative', height:'100%', width:'100%', background:'var(--dark-chocolate)' }}><SessionRestoring/></div>;
  }
  if (session.phase === 'signedout') {
    return (
      <div style={{ position:'relative', height:'100%', width:'100%', background:'var(--dark-chocolate)', overflow:'hidden' }}>
        <AuthScreen onSignIn={(r)=>{ session.signIn(r); setPage(r==='staff'?'orders':'map'); }}/>
      </div>
    );
  }

  const screens = {
    overview:  <OverviewScreen app={app}/>,
    menu:      <MenuScreen app={app}/>,
    orders:    <OrdersScreen app={app}/>,
    insights:  <InsightsScreen app={app}/>,
    campaigns: <CampaignsScreen app={app}/>,
    rewards:   <RewardsScreen app={app}/>,
    trail:     <TrailScreen app={app}/>,
    team:      <TeamScreen app={app}/>,
    ops:       <OpsScreen app={app}/>,
    settings:  <SettingsScreen app={app}/>,
  };

  const denied = !roleCanSee(role, page);
  const isMap = page === 'map' && !denied;

  // Floating nav geometry: 0.5rem from left edge, 1rem top/bottom.
  const NAV_W = 236, NAV_LEFT = 8, NAV_TOP = 16, CONTENT_OFFSET = NAV_LEFT + NAV_W + 16;

  return (
    <div style={{ position:'relative', height:'100%', width:'100%', background:'var(--dark-chocolate)', overflow:'hidden' }}>
      {/* Persistent live map — the background on every tab. Interactive only on Map Campaigns. */}
      <MapScreen app={app} navOffset={CONTENT_OFFSET} active={isMap}/>

      {/* On every other tab the page content floats above the (inert) map. */}
      {!isMap && (
        <div style={{ position:'absolute', inset:0, paddingLeft:CONTENT_OFFSET, display:'flex', flexDirection:'column', zIndex:30, pointerEvents:'none' }}>
          {/* Frosted veil — calms the map behind content so headers & loose text stay readable */}
          <div style={{ position:'absolute', top:0, bottom:0, left:CONTENT_OFFSET-14, right:0, background:'linear-gradient(180deg, rgba(245,239,231,0.66), rgba(245,239,231,0.58))', backdropFilter:'blur(26px) saturate(135%)', WebkitBackdropFilter:'blur(26px) saturate(135%)', borderLeft:'1px solid rgba(255,255,255,0.35)', pointerEvents:'none' }}></div>
          <div style={{ padding:'16px 16px 0', position:'relative', zIndex:5, pointerEvents:'auto' }}>
            <Topbar app={app} floating/>
          </div>
          <div ref={scrollRef} style={{ flex:1, minHeight:0, overflowY:'auto', overflowX:'hidden', padding:'18px 26px 40px', position:'relative', pointerEvents:'auto' }}>
            <div style={{ maxWidth:1320, margin:'0 auto' }}>
              {denied ? <RoleDenied page={page} session={session.sess}/> : screens[page]}
            </div>
          </div>
        </div>
      )}

      {/* Floating frosted-glass nav — above the map, below tab-pane content & modals */}
      <div style={{ position:'absolute', left:NAV_LEFT, top:NAV_TOP, bottom:NAV_TOP, width:NAV_W, zIndex:25 }}>
        <Sidebar app={app}/>
      </div>

      {builder.open && <CampaignBuilder app={app}/>}
      {paletteOpen && session.phase==='signedin' && <CommandPalette app={app} onClose={()=>setPaletteOpen(false)}/>}
      {mustard && <MustardSeedModal area={mustard} onClose={()=>setMustard(null)}/>}
      {session.phase==='expired' && (
        <SessionExpiredOverlay
          onSignBackIn={()=>{ session.restore(); setToast('Welcome back — session renewed'); }}
          onSignOut={()=>session.signOut()}/>
      )}
      <ToastHost toast={toast} onDone={()=>setToast(null)}/>
    </div>
  );
}

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