/* Phone shell — wraps a screen function with a tiny router + iOS-ish
   status bar + bottom nav. Each phone artboard is independent: clicking
   bottom tabs / buttons inside it navigates within that phone only.

   Routes:
     home, plan, picker, live, log, malfunction, reconcile, cascade,
     record, firearm, maintain, supply, caliber, addlot, protect,
     gear, guns, accessories, suppressors, modifications,
     addgun, addaccessory, addsuppressor
*/

function PhoneStatusBar() {
  return (
    <div className="ios-bar">
      <span>9:41</span>
      <div className="right">
        {/* signal */}
        <svg width="16" height="10" viewBox="0 0 16 10"><rect x="0" y="6" width="3" height="4" rx="0.5" fill="currentColor"/><rect x="4" y="4" width="3" height="6" rx="0.5" fill="currentColor"/><rect x="8" y="2" width="3" height="8" rx="0.5" fill="currentColor"/><rect x="12" y="0" width="3" height="10" rx="0.5" fill="currentColor"/></svg>
        {/* battery */}
        <svg width="22" height="10" viewBox="0 0 22 10"><rect x="0.5" y="0.5" width="19" height="9" rx="2" fill="none" stroke="currentColor" strokeOpacity="0.5"/><rect x="2" y="2" width="16" height="6" rx="1" fill="currentColor"/><rect x="20" y="3.5" width="1.5" height="3" rx="0.5" fill="currentColor" opacity="0.5"/></svg>
      </div>
    </div>
  );
}

function Phone({ initial='home', navStyle='tabs', screens, onGo, emptyMode=false }) {
  const [route, setRoute] = React.useState(initial);
  const [tourId, setTourId] = React.useState(null);
  const bodyRef = React.useRef(null);

  const go = (r) => {
    setRoute(r);
    onGo && onGo(r);
  };

  // Expose go() and __rhTour so global components (TopBar, TourButton) can
  // trigger navigation + tours without threading props through every screen.
  React.useEffect(() => {
    window.__rhGo = go;
    window.__rhTour = (id) => setTourId(id);
  }, []);

  // v4.6: scroll the screen-body to the top whenever the route changes.
  React.useEffect(() => {
    if (bodyRef.current) bodyRef.current.scrollTop = 0;
  }, [route]);
  React.useEffect(() => {
    window.__rhScrollTop = () => { if (bodyRef.current) bodyRef.current.scrollTop = 0; };
  }, []);

  // Auto-fire the overall tour on first ever load.
  // Uses localStorage so it survives page reloads — fires once, never again
  // unless the user replays from Settings.
  React.useEffect(() => {
    if (!localStorage.getItem('rh-tour-seen')) {
      localStorage.setItem('rh-tour-seen', '1');
      const t = setTimeout(() => setTourId('overall'), 700);
      return () => clearTimeout(t);
    }
  }, []);

  const Screen = screens[route] || (() => <div style={{padding:20, color:'var(--rh-bone-500)'}}>Screen not found: {route}</div>);

  // Map routes to bottom tab IDs
  const tabFor = {
    home:'home', plan:'home', picker:'home', live:'home', log:'home', malfunction:'home', reconcile:'home', cascade:'home', settings:'home',
    gear:'gear', guns:'gear', gundetail:'gear', editgun:'gear', accessories:'gear', suppressors:'gear', modifications:'gear',
    addgun:'gear', addaccessory:'gear', addsuppressor:'gear',
    supply:'supply', caliber:'supply', addlot:'supply',
    maintain:'maintain',
    protect:'record',
    record:'record', firearm:'record', suppressordetail:'record', goalslibrary:'record',
  };
  const activeTab = tabFor[route] || 'home';

  // In empty mode, Maintain is locked (Protect is no longer a tab; it's reached from Record).
  const locked = emptyMode ? { maintain: true } : {};

  const goTab = (id) => {
    if (locked[id]) {
      // Tapping a locked tab routes home (gate is shown there too).
      go('home');
      return;
    }
    if (id === 'home')     go('home');
    if (id === 'gear')     go('gear');
    if (id === 'supply')   go('supply');
    if (id === 'maintain') go('maintain');
    if (id === 'record')   go('record');
  };

  return (
    <div className="rh-phone">
      <PhoneStatusBar/>
      <div className="screen-body" ref={bodyRef}>
        <Screen go={go} route={route} emptyMode={emptyMode}/>
      </div>
      {navStyle === 'tabs' && (
        <BottomTabs active={activeTab} setActive={goTab} locked={locked}/>
      )}
      {navStyle === 'hub' && (
        <div style={{position:'absolute', left:0, right:0, bottom:0, height:64, background:'var(--rh-obsidian-900)', borderTop:'1px solid var(--rh-brass-tint-32)', display:'flex', alignItems:'center', justifyContent:'space-between', padding:'0 20px'}}>
          <button className="btn btn-ghost" onClick={()=>go('home')} style={{padding:'8px 0'}}>← Home</button>
          <span className="label-md" style={{color:'var(--rh-bone-500)'}}>Hub navigation</span>
          <button className="btn btn-ghost" onClick={()=>go('record')} style={{padding:'8px 0'}}>Record →</button>
        </div>
      )}

      {/* Tour overlay — renders within the phone bezel, blocks the screen
          beneath until dismissed. */}
      {tourId && window.TourOverlay && (
        <window.TourOverlay tourId={tourId} onClose={()=>setTourId(null)}/>
      )}
    </div>
  );
}

window.Phone = Phone;
