// Wander — App router & shell

const SCREENS = {
  ONBOARDING:'onboarding', LOCATION:'location', MAP:'map', BROWSE:'browse', SAVED:'saved',
  PROFILE:'profile', DETAIL:'detail', PLAYER:'player', PAYWALL:'paywall',
  COMPLETION:'completion', SEARCH:'search', OFFLINE:'offline',
  // Auth & creator
  AUTH:'auth', CREATOR:'creator', TOUR_EDITOR:'tour_editor',
};

const TWEAKS_DEFAULTS = /*EDITMODE-BEGIN*/{ "density":"comfortable", "brand":"#FFC93C" }/*EDITMODE-END*/;

function App() {
  const [screen, setScreen]       = React.useState(SCREENS.ONBOARDING);
  const [tourId, setTourId]       = React.useState('merlion-marina');
  const [tours, setTours]         = React.useState(window.WANDER_DATA.TOURS);
  const [tweaks, setTweak]        = window.useTweaks ? window.useTweaks(TWEAKS_DEFAULTS) : [TWEAKS_DEFAULTS, ()=>{}];
  const dense = tweaks.density === 'compact';

  // ── Auth state (persisted in localStorage) ─────────────────────────────────
  const [authUser, setAuthUser] = React.useState(() => {
    try { return JSON.parse(localStorage.getItem('wander_user')); } catch { return null; }
  });
  const [authToken, setAuthToken] = React.useState(
    () => localStorage.getItem('wander_token') || null
  );
  const [authMode, setAuthMode]   = React.useState('login');
  const [editingTour, setEditingTour] = React.useState(null);
  const [resetToken, setResetToken]   = React.useState(null);

  // ── Boot ───────────────────────────────────────────────────────────────────
  React.useEffect(() => {
    // Load tours from API
    window.loadTours().then(data => {
      window.WANDER_DATA.TOURS = data;
      setTours(data);
    });

    // Handle ?reset_token= in URL
    const params = new URLSearchParams(window.location.search);
    const rt = params.get('reset_token');
    if (rt) {
      setResetToken(rt);
      window.history.replaceState({}, '', '/');
      setAuthMode('reset');
      setScreen(SCREENS.AUTH);
    }
  }, []);

  // Apply brand colour tweak
  React.useEffect(() => {
    document.documentElement.style.setProperty('--w-yellow', tweaks.brand);
  }, [tweaks.brand]);

  // ── Auth handlers ──────────────────────────────────────────────────────────
  const handleLogin = (user, token) => {
    setAuthUser(user);
    setAuthToken(token);
    setScreen(SCREENS.CREATOR);
  };

  const handleLogout = () => {
    localStorage.removeItem('wander_token');
    localStorage.removeItem('wander_user');
    setAuthUser(null);
    setAuthToken(null);
    setScreen(SCREENS.PROFILE);
  };

  // ── Tab navigation ─────────────────────────────────────────────────────────
  const goTab = t => {
    if (t==='map')     setScreen(SCREENS.MAP);
    if (t==='browse')  setScreen(SCREENS.BROWSE);
    if (t==='saved')   setScreen(SCREENS.SAVED);
    if (t==='profile') setScreen(SCREENS.PROFILE);
  };

  // ── Screen router ──────────────────────────────────────────────────────────
  let body;
  switch (screen) {
    case SCREENS.ONBOARDING:
      body = <Onboarding onDone={()=>setScreen(SCREENS.LOCATION)} dense={dense}/>;
      break;
    case SCREENS.LOCATION:
      body = <LocationScreen
        onDone={()=>setScreen(SCREENS.MAP)}
        onSkip={()=>setScreen(SCREENS.MAP)}
        brand={tweaks.brand}
      />;
      break;
    case SCREENS.MAP:
      body = <MapScreen onOpenTour={id=>{setTourId(id);setScreen(SCREENS.DETAIL);}} onTab={goTab} dense={dense} brand={tweaks.brand}/>;
      break;
    case SCREENS.BROWSE:
      body = <BrowseScreen onOpenTour={id=>{setTourId(id);setScreen(SCREENS.DETAIL);}} onTab={goTab} onSearch={()=>setScreen(SCREENS.SEARCH)} dense={dense}/>;
      break;
    case SCREENS.SAVED:
      body = <SavedScreen onTab={goTab} onOpenTour={id=>{setTourId(id);setScreen(SCREENS.DETAIL);}} onOpenOffline={()=>setScreen(SCREENS.OFFLINE)} dense={dense}/>;
      break;
    case SCREENS.PROFILE:
      body = <ProfileScreen
        onTab={goTab} dense={dense}
        authUser={authUser} authToken={authToken}
        onGoAuth={mode=>{ setAuthMode(mode||'login'); setScreen(SCREENS.AUTH); }}
        onGoCreator={()=>setScreen(SCREENS.CREATOR)}
        onLogout={handleLogout}
      />;
      break;
    case SCREENS.AUTH:
      body = <AuthScreen
        onLogin={handleLogin}
        onBack={()=>setScreen(SCREENS.PROFILE)}
        initialMode={authMode}
        resetToken={resetToken}
      />;
      break;
    case SCREENS.CREATOR:
      body = <CreatorDashboardScreen
        authUser={authUser} authToken={authToken}
        onBack={()=>setScreen(SCREENS.PROFILE)}
        onCreateTour={()=>{ setEditingTour(null); setScreen(SCREENS.TOUR_EDITOR); }}
        onEditTour={t=>{ setEditingTour(t); setScreen(SCREENS.TOUR_EDITOR); }}
      />;
      break;
    case SCREENS.TOUR_EDITOR:
      body = <TourEditorScreen
        authToken={authToken}
        existingTour={editingTour}
        onBack={()=>setScreen(SCREENS.CREATOR)}
      />;
      break;
    case SCREENS.SEARCH:
      body = <SearchScreen onClose={()=>setScreen(SCREENS.BROWSE)} onOpenTour={id=>{setTourId(id);setScreen(SCREENS.DETAIL);}}/>;
      break;
    case SCREENS.DETAIL:
      body = <DetailScreen tourId={tourId} onBack={()=>setScreen(SCREENS.MAP)} onStart={()=>setScreen(SCREENS.PLAYER)} onPaywall={()=>setScreen(SCREENS.PAYWALL)} dense={dense}/>;
      break;
    case SCREENS.PLAYER:
      body = <PlayerScreen tourId={tourId} onBack={()=>setScreen(SCREENS.DETAIL)} onComplete={()=>setScreen(SCREENS.COMPLETION)} dense={dense}/>;
      break;
    case SCREENS.PAYWALL:
      body = <PaywallScreen tourId={tourId} onClose={()=>setScreen(SCREENS.DETAIL)} onSuccess={()=>setScreen(SCREENS.PLAYER)}/>;
      break;
    case SCREENS.COMPLETION:
      body = <CompletionScreen tourId={tourId} onDone={()=>setScreen(SCREENS.MAP)}/>;
      break;
    case SCREENS.OFFLINE:
      body = <OfflineScreen onClose={()=>setScreen(SCREENS.SAVED)}/>;
      break;
    default: body = null;
  }

  const labels = {
    [SCREENS.ONBOARDING]:'01 Onboarding', [SCREENS.LOCATION]:'01b Location', [SCREENS.MAP]:'02 Map', [SCREENS.BROWSE]:'03 Browse',
    [SCREENS.SAVED]:'04 Saved', [SCREENS.PROFILE]:'05 Profile', [SCREENS.SEARCH]:'06 Search',
    [SCREENS.DETAIL]:'07 Tour Detail', [SCREENS.PLAYER]:'08 Tour Player', [SCREENS.PAYWALL]:'09 Paywall',
    [SCREENS.COMPLETION]:'10 Completion', [SCREENS.OFFLINE]:'11 Offline',
    [SCREENS.AUTH]:'12 Auth', [SCREENS.CREATOR]:'13 Creator', [SCREENS.TOUR_EDITOR]:'14 Tour Editor',
  };

  return (
    <div style={{ minHeight:'100vh', display:'flex', alignItems:'center', justifyContent:'center', padding:'32px 16px', background:'radial-gradient(circle at 30% 20%,#FFF4D2,#FAF6EC 60%)' }}>
      <div data-screen-label={labels[screen]} style={{ position:'relative' }}>
        <IOSDevice width={402} height={874}>{body}</IOSDevice>
        <ScreenJumper current={screen} onJump={setScreen} authUser={authUser}/>
      </div>

      {window.TweaksPanel && (
        <window.TweaksPanel title="Tweaks">
          <window.TweakSection title="Display"/>
          <window.TweakRadio label="Card density" value={tweaks.density} onChange={v=>setTweak('density',v)} options={[{value:'comfortable',label:'Comfortable'},{value:'compact',label:'Compact'}]}/>
          <window.TweakSection title="Brand colour"/>
          <window.TweakColor label="Primary" value={tweaks.brand} onChange={v=>setTweak('brand',v)}/>
          <div style={{ display:'flex', gap:6, marginTop:8 }}>
            {['#FFC93C','#FF6B5A','#2DD4A7','#9B7EDC','#4FB7E8','#E89B6C'].map(c => (
              <button key={c} onClick={()=>setTweak('brand',c)} style={{ width:28, height:28, borderRadius:14, border:tweaks.brand===c?'2px solid #1A1812':'2px solid transparent', background:c, cursor:'pointer' }}/>
            ))}
          </div>
          <window.TweakSection title="Jump to screen"/>
          <window.TweakSelect label="Screen" value={screen} onChange={v=>setScreen(v)} options={Object.entries(labels).map(([k,v])=>({value:k,label:v}))}/>
        </window.TweaksPanel>
      )}
    </div>
  );
}

function ScreenJumper({ current, onJump, authUser }) {
  const items = [
    {id:'onboarding',label:'Intro'},{id:'location',label:'Location'},{id:'map',label:'Map'},{id:'browse',label:'Browse'},
    {id:'search',label:'Search'},{id:'detail',label:'Detail'},{id:'paywall',label:'Paywall'},
    {id:'player',label:'Player'},{id:'completion',label:'Done'},{id:'saved',label:'Saved'},
    {id:'offline',label:'Offline'},{id:'profile',label:'You'},
    {id:'auth',label:'Auth'},{id:'creator',label:'Creator'},{id:'tour_editor',label:'Tour Editor'},
  ];
  return (
    <div style={{ position:'absolute', top:'50%', left:'calc(100% + 24px)', transform:'translateY(-50%)', display:'flex', flexDirection:'column', gap:4, background:'#fff', borderRadius:20, padding:8, boxShadow:'0 8px 24px rgba(0,0,0,0.08)', maxHeight:640, overflowY:'auto' }}>
      <div style={{ fontSize:9, color:'#8A8474', fontWeight:700, letterSpacing:0.5, textTransform:'uppercase', padding:'6px 10px 4px' }}>Screens</div>
      {items.map(s => (
        <button key={s.id} onClick={()=>onJump(s.id)} style={{ padding:'8px 12px', borderRadius:12, border:'none', cursor:'pointer', background:current===s.id?'#1A1812':'transparent', color:current===s.id?'#FFC93C':'#1A1812', fontWeight:600, fontSize:12, fontFamily:'inherit', textAlign:'left', minWidth:90 }}>
          {s.label}
        </button>
      ))}
      {authUser && (
        <div style={{ padding:'6px 10px 2px', fontSize:9, color:'#2DD4A7', fontWeight:700, letterSpacing:0.5, textTransform:'uppercase', borderTop:'1px solid #f0ece0', marginTop:4 }}>
          ✓ {authUser.name}
        </div>
      )}
    </div>
  );
}

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