// Otto — Prototype shell: tab nav, screen routing, transitions, tweaks

const SCREENS = {
  onboarding: { title: 'Onboarding', component: 'ScreenOnboarding' },
  home: { title: 'Home', component: 'ScreenHome' },
  signals: { title: 'Live Signals', component: 'ScreenSignals' },
  risk: { title: 'Risks', component: 'ScreenRisk' },
  preventive: { title: 'Preventive Care', component: 'ScreenPreventive' },
  book: { title: 'Book Tests', component: 'ScreenBook' },
  lab: { title: 'Lab Results', component: 'ScreenLab' },
  coach: { title: 'Otto Coach', component: 'ScreenCoach' },
  checkin: { title: 'Daily Check-in', component: 'ScreenCheckin' },
  profile: { title: 'Profile', component: 'ScreenProfile' },
};

// Bottom tab navigator (only 5 main; others are pushed)
const TABS = [
  { id: 'home', label: 'Today', icon: 'home' },
  { id: 'signals', label: 'Signals', icon: 'pulse' },
  { id: 'coach', label: 'Otto', icon: 'logo' },
  { id: 'preventive', label: 'Care', icon: 'cross' },
  { id: 'profile', label: 'You', icon: 'person' },
];

function TabIcon({ name, active }) {
  const c = active ? OttoTokens.ink : OttoTokens.inkSubtle;
  const s = 26;
  if (name === 'home') return (
    <svg width={s} height={s} viewBox="0 0 24 24" fill="none">
      <path d="M3 11l9-7 9 7v9a1 1 0 01-1 1h-5v-7h-6v7H4a1 1 0 01-1-1v-9z" stroke={c} strokeWidth="1.8" strokeLinejoin="round"/>
    </svg>
  );
  if (name === 'pulse') return (
    <svg width={s} height={s} viewBox="0 0 24 24" fill="none">
      <path d="M3 12h4l2-6 4 12 2-6h6" stroke={c} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  );
  if (name === 'logo') return <OttoMark size={28} color={c}/>;
  if (name === 'cross') return (
    <svg width={s} height={s} viewBox="0 0 24 24" fill="none">
      <rect x="9.5" y="3" width="5" height="18" rx="1.2" stroke={c} strokeWidth="1.8"/>
      <rect x="3" y="9.5" width="18" height="5" rx="1.2" stroke={c} strokeWidth="1.8"/>
    </svg>
  );
  if (name === 'person') return (
    <svg width={s} height={s} viewBox="0 0 24 24" fill="none">
      <circle cx="12" cy="8" r="4" stroke={c} strokeWidth="1.8"/>
      <path d="M4 21c0-4.4 3.6-8 8-8s8 3.6 8 8" stroke={c} strokeWidth="1.8" strokeLinecap="round"/>
    </svg>
  );
  return null;
}

function TabBar({ current, onChange, dark }) {
  return (
    <div style={{
      position: 'absolute', bottom: 0, left: 0, right: 0,
      paddingTop: 6, paddingBottom: 24,
      background: dark ? 'rgba(28,26,23,0.85)' : 'rgba(244,240,232,0.85)',
      backdropFilter: 'blur(20px) saturate(180%)',
      WebkitBackdropFilter: 'blur(20px) saturate(180%)',
      borderTop: `0.5px solid ${OttoTokens.hairline}`,
      display: 'flex', justifyContent: 'space-around',
      zIndex: 30,
    }}>
      {TABS.map(t => {
        const active = t.id === current ||
          (t.id === 'preventive' && (current === 'book' || current === 'lab' || current === 'risk')) ||
          (t.id === 'home' && current === 'checkin');
        return (
          <button key={t.id} onClick={() => onChange(t.id)} style={{
            flex: 1, padding: '8px 4px', minHeight: 56,
            background: 'transparent', border: 'none', cursor: 'pointer',
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
          }}>
            <TabIcon name={t.icon} active={active}/>
            <span style={{
              fontFamily: OttoTokens.sans, fontSize: 11, fontWeight: 600,
              color: active ? OttoTokens.ink : OttoTokens.inkSubtle,
              letterSpacing: -0.1,
            }}>{t.label}</span>
          </button>
        );
      })}
    </div>
  );
}

// Phone container that handles screen transitions
function Phone({ width = 390, height = 844, initial = 'onboarding', showTabBar = true, framed = true }) {
  const [current, setCurrent] = React.useState(initial);
  const [history, setHistory] = React.useState([initial]);
  const [direction, setDirection] = React.useState('forward');
  const [transitionKey, setTransitionKey] = React.useState(0);

  const go = React.useCallback((id) => {
    setDirection('forward');
    setHistory(h => [...h, id]);
    setCurrent(id);
    setTransitionKey(k => k + 1);
  }, []);

  const goBack = React.useCallback(() => {
    if (history.length > 1) {
      setDirection('back');
      const newHist = history.slice(0, -1);
      setHistory(newHist);
      setCurrent(newHist[newHist.length - 1]);
      setTransitionKey(k => k + 1);
    }
  }, [history]);

  const Comp = window[SCREENS[current].component];
  const isOnboarding = current === 'onboarding';
  const isCheckin = current === 'checkin';
  const isCoach = current === 'coach';

  const screenContent = (
    <div style={{ position: 'relative', width: '100%', height: '100%', overflow: 'hidden', background: OttoTokens.bg }}>
      {/* Status bar overlay */}
      {!isOnboarding && (
        <div style={{
          position: 'absolute', top: 0, left: 0, right: 0, zIndex: 40,
          padding: '14px 28px 0',
          display: 'flex', justifyContent: 'space-between',
          fontFamily: OttoTokens.sans, fontSize: 15, fontWeight: 600, color: OttoTokens.ink,
        }}>
          <span>9:41</span>
          <span style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
            <svg width="17" height="11" viewBox="0 0 17 11"><path d="M1 8h2v3H1V8zm4-2h2v5H5V6zm4-2h2v7H9V4zm4-2h2v9h-2V2z" fill={OttoTokens.ink}/></svg>
            <svg width="22" height="11" viewBox="0 0 22 11" fill="none">
              <rect x="0.5" y="0.5" width="18" height="10" rx="2.5" stroke={OttoTokens.ink} strokeOpacity="0.4"/>
              <rect x="2" y="2" width="15" height="7" rx="1" fill={OttoTokens.ink}/>
              <rect x="20" y="3.5" width="1.5" height="4" rx="0.5" fill={OttoTokens.ink} opacity="0.4"/>
            </svg>
          </span>
        </div>
      )}

      {/* Back chevron for pushed screens */}
      {!isOnboarding && current !== 'home' && history.length > 1 && (
        <button onClick={goBack} style={{
          position: 'absolute', top: 50, left: 16, zIndex: 50,
          width: 40, height: 40, borderRadius: '50%',
          background: 'rgba(255,255,255,0.7)',
          backdropFilter: 'blur(12px)',
          WebkitBackdropFilter: 'blur(12px)',
          border: 'none', cursor: 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          boxShadow: '0 1px 4px rgba(28,26,23,0.06)',
        }}>
          <svg width="10" height="16" viewBox="0 0 10 16" fill="none">
            <path d="M8 2L2 8l6 6" stroke={OttoTokens.ink} strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </button>
      )}

      <div key={transitionKey} style={{
        height: '100%',
        animation: direction === 'forward'
          ? 'ottoSlideIn 360ms cubic-bezier(.2,.8,.2,1)'
          : 'ottoSlideBack 320ms cubic-bezier(.2,.8,.2,1)',
      }}>
        <Comp go={go} goBack={goBack}/>
      </div>

      {showTabBar && !isOnboarding && !isCheckin && (
        <TabBar current={current} onChange={(id) => { setDirection('forward'); setHistory([id]); setCurrent(id); setTransitionKey(k => k + 1); }} dark={false}/>
      )}

      {/* Home indicator */}
      {!isOnboarding && (
        <div style={{
          position: 'absolute', bottom: 8, left: '50%', transform: 'translateX(-50%)',
          width: 134, height: 5, borderRadius: 3, background: OttoTokens.ink,
          opacity: 0.85, zIndex: 50, pointerEvents: 'none',
        }}/>
      )}
    </div>
  );

  if (!framed) {
    return <div style={{ width, height, position: 'relative', borderRadius: 44, overflow: 'hidden' }}>{screenContent}</div>;
  }

  // iPhone bezel
  return (
    <div style={{
      width: width + 16, height: height + 16,
      borderRadius: 56, padding: 8,
      background: 'linear-gradient(135deg, #2a2926 0%, #14130f 100%)',
      boxShadow: '0 30px 60px -20px rgba(28,26,23,0.35), 0 0 0 1px rgba(0,0,0,0.4)',
      position: 'relative',
    }}>
      <div style={{
        width, height, borderRadius: 48, overflow: 'hidden',
        background: OttoTokens.bg, position: 'relative',
      }}>
        {/* Dynamic island */}
        <div style={{
          position: 'absolute', top: 11, left: '50%', transform: 'translateX(-50%)',
          width: 124, height: 36, borderRadius: 22, background: '#000', zIndex: 100,
        }}/>
        {screenContent}
      </div>
    </div>
  );
}

Object.assign(window, { Phone, SCREENS, TABS });
