// Nav stack — lets any tab push detail screens on top of it.
// Rendered above the tab content but BELOW the tab bar (so the tab bar stays visible).
// A pushed screen can push more screens, and each one has its own back arrow.

const NavContext = React.createContext(null);
function useNav() { return React.useContext(NavContext); }

function NavProvider({ children }) {
  // stack: [{ key, render }]
  const [stack, setStack] = React.useState([]);
  const push = (render) => setStack(s => [...s, { key: Date.now() + Math.random(), render }]);
  const pop  = () => setStack(s => s.slice(0, -1));
  const reset = () => setStack([]);
  return (
    <NavContext.Provider value={{ stack, push, pop, reset }}>
      {children}
    </NavContext.Provider>
  );
}

// Renders any currently-pushed pages, slide-in-from-right, full-screen inside the phone.
function NavStack({ t, coach, dark }) {
  const nav = useNav();
  return (
    <>
      {nav.stack.map((page, i) => (
        <div key={page.key} style={{
          position: 'absolute', inset: 0,
          background: t.bg, zIndex: 50 + i,
          animation: 'slideInRight .28s cubic-bezier(.3, .7, .3, 1)',
          overflowY: 'auto', overflowX: 'hidden',
        }} className="screen-scroll">
          {page.render({ t, coach, dark, nav })}
          <div style={{ height: 90 }}/>
        </div>
      ))}
    </>
  );
}

// Header for pushed screens: back arrow + title + optional right action
function NavHeader({ title, right, t, transparent = false, onBack }) {
  const nav = useNav();
  return (
    <div style={{
      position: transparent ? 'absolute' : 'relative',
      top: 0, left: 0, right: 0, zIndex: 5,
      padding: '58px 18px 10px',
      display: 'flex', alignItems: 'center', gap: 8,
      background: transparent ? 'transparent' : t.bg,
    }}>
      <button onClick={() => onBack ? onBack() : nav.pop()} style={{
        background: transparent ? 'rgba(0,0,0,0.35)' : 'none', border: 'none',
        width: 36, height: 36, borderRadius: 999,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        cursor: 'pointer', flexShrink: 0,
      }}>
        <Icon.Back size={18} color={transparent ? '#fff' : t.text}/>
      </button>
      <div style={{
        flex: 1, fontSize: 17, fontWeight: 700,
        color: transparent ? '#fff' : t.text,
      }}>{title}</div>
      {right}
    </div>
  );
}

// Small pill button — used for "Coach Note" etc
function BrandPill({ children, onClick, t, icon, style = {} }) {
  return (
    <button onClick={onClick} style={{
      background: t.primary, color: t.onPrimary, border: 'none',
      padding: '8px 12px', borderRadius: 999,
      display: 'inline-flex', alignItems: 'center', gap: 6,
      fontSize: 12, fontWeight: 600, cursor: 'pointer',
      fontFamily: 'inherit',
      ...style,
    }}>
      {icon}
      {children}
    </button>
  );
}

Object.assign(window, { NavContext, NavProvider, NavStack, NavHeader, BrandPill, useNav });
