/* SkinJourney UI Kit — app shell, phone frame, router */
const Ca = window.SJ.c, Ra = window.SJ.r, FONTa = window.SJ.font;

/* ---- iPhone 15 Pro frame (390×844) --------------------------------------- */
function PhoneFrame({ children, dark }) {
  return (
    <div style={{ width:390, height:844, position:'relative', background: dark?Ca.darkBg:Ca.bg,
      borderRadius:54, boxShadow:'0 30px 80px rgba(14,27,22,.28), 0 0 0 12px #1a1c1b, 0 0 0 13px #2c2c2e',
      overflow:'hidden', fontFamily:FONTa, direction:'rtl' }}>
      {/* Dynamic Island */}
      <div style={{ position:'absolute', top:11, left:'50%', transform:'translateX(-50%)', width:120, height:34,
        background:'#000', borderRadius:20, zIndex:100 }}/>
      {/* status bar */}
      <div style={{ position:'absolute', top:0, left:0, right:0, height:54, display:'flex',
        flexDirection:'row-reverse', alignItems:'center', justifyContent:'space-between',
        padding:'0 30px', zIndex:99, color: dark?'#fff':Ca.textPrimary, pointerEvents:'none' }}>
        <span style={{ fontSize:15, fontWeight:700, marginTop:6 }}>9:41</span>
        <div style={{ display:'flex', gap:6, alignItems:'center', marginTop:6 }}>
          <Icon name="cellular" size={16} color={dark?'#fff':Ca.textPrimary}/>
          <Icon name="wifi" size={16} color={dark?'#fff':Ca.textPrimary}/>
          <Icon name="battery-full" size={18} color={dark?'#fff':Ca.textPrimary}/>
        </div>
      </div>
      {children}
    </div>
  );
}

const ONBOARDING = ['splash','welcome','howitworks','personalize'];

function useFitScale(designH) {
  const [scale,setScale]=useState(1);
  useEffect(()=>{
    const fit=()=>{ const s=Math.min(1,(window.innerHeight-32)/designH); setScale(s); };
    fit(); window.addEventListener('resize',fit); return ()=>window.removeEventListener('resize',fit);
  },[designH]);
  return scale;
}

// ---- embed deep-linking: ?screen=home&chrome=0 ---------------------------
const EMBED = (()=>{
  const p = new URLSearchParams(location.search);
  const chrome = p.get('chrome') !== '0';
  const s = p.get('screen') || 'splash';
  const onb = ONBOARDING.includes(s);
  return {
    chrome,
    screen: onb ? s : 'home',
    tab: s==='timeline' ? 'timeline' : s==='compare' ? 'compare' : s==='settings' ? 'settings' : 'home',
    camera: s==='camera',
    summary: s==='summary',
  };
})();

function App() {
  const scale=useFitScale(EMBED.chrome ? 844+96 : 844);
  const [screen,setScreen]=useState(EMBED.screen);
  const [tab,setTab]=useState(EMBED.tab);
  const [camera,setCamera]=useState(EMBED.camera);
  const [summary,setSummary]=useState(EMBED.summary);
  const [photo,setPhoto]=useState(null);
  const [toast,setToast]=useState(null);

  useEffect(()=>{ // splash auto-advance (skipped when a screen is deep-linked)
    if(screen==='splash'){ const t=setTimeout(()=>setScreen('welcome'),1500); return ()=>clearTimeout(t); }
  },[screen]);

  useEffect(()=>{ if(!EMBED.chrome){
    document.body.style.background='transparent';
    document.body.style.padding='0';
    document.body.style.minHeight='0';
  }},[]);

  const go = s => setScreen(s);
  const inApp = !ONBOARDING.includes(screen);
  const showToast = msg => { setToast(msg); setTimeout(()=>setToast(null),2200); };

  // jump targets for the reviewer strip
  const JUMPS = [
    ['splash','Splash',()=>{setScreen('splash');}],
    ['welcome','Welcome',()=>go('welcome')],
    ['howitworks','How it works',()=>go('howitworks')],
    ['personalize','Personalize',()=>go('personalize')],
    ['home','Home',()=>{go('home');setTab('home');}],
    ['camera','Camera',()=>{go('home');setCamera(true);}],
    ['timeline','Timeline',()=>{go('home');setTab('timeline');}],
    ['compare','Compare',()=>{go('home');setTab('compare');}],
    ['summary','Summary',()=>{go('home');setTab('home');setSummary(true);}],
    ['settings','Settings',()=>{go('home');setTab('settings');}],
  ];
  const activeJump = camera?'camera' : summary?'summary' : inApp?tab : screen;

  const dark = camera || !!photo;

  return (
    <div style={{ transform:`scale(${scale})`, transformOrigin:'top center' }}>
    <div style={{ display:'flex', flexDirection:'column', alignItems:'center', gap:18 }}>
      {/* reviewer screen-picker */}
      {EMBED.chrome && <div style={{ display:'flex', flexWrap:'wrap', gap:6, justifyContent:'center', maxWidth:560 }}>
        {JUMPS.map(([k,label,fn])=>(
          <button key={k} onClick={fn} style={{ border:'none', cursor:'pointer', fontFamily:FONTa,
            fontSize:12, fontWeight:600, padding:'6px 13px', borderRadius:99,
            background: activeJump===k?Ca.primary:'#fff', color: activeJump===k?'#fff':Ca.textSecondary,
            boxShadow:'0 1px 3px rgba(14,27,22,.08)' }}>{label}</button>
        ))}
      </div>}

      <PhoneFrame dark={dark}>
        {/* base screen */}
        {screen==='splash' && <SplashScreen/>}
        {screen==='welcome' && <WelcomeScreen go={go}/>}
        {screen==='howitworks' && <HowItWorksScreen go={go}/>}
        {screen==='personalize' && <PersonalizeScreen go={go}/>}

        {inApp && (
          <React.Fragment>
            {tab==='home' && <HomeScreen openSummary={()=>setSummary(true)} capture={()=>setCamera(true)}/>}
            {tab==='timeline' && <TimelineScreen openPhoto={setPhoto}/>}
            {tab==='compare' && <ComparisonScreen/>}
            {tab==='settings' && <SettingsScreen exportPdf={()=>showToast('מייצרים דוח PDF…')}/>}
            <TabBar active={tab} onTab={setTab} onCapture={()=>setCamera(true)}/>
          </React.Fragment>
        )}

        {/* overlays */}
        {summary && <WeeklySummarySheet close={()=>setSummary(false)}/>}
        {photo && <PhotoViewer item={photo} close={()=>setPhoto(null)}/>}
        {camera && <CameraScreen close={()=>setCamera(false)}
          onShoot={()=>{ setCamera(false); setTab('timeline'); setScreen('home'); showToast('התמונה נשמרה ✓'); }}/>}

        {/* toast */}
        {toast && (
          <div style={{ position:'absolute', bottom:104, left:20, right:20, zIndex:60,
            display:'flex', flexDirection:'row-reverse', alignItems:'center', gap:10,
            background:Ca.sand900, color:'#fff', borderRadius:Ra.md, padding:'13px 16px',
            boxShadow:window.SJ.elev[3], animation:'sjFadeUp .3s ease' }}>
            <Icon name="checkmark-circle" size={20} color={Ca.sage300}/>
            <span style={{ fontSize:14, fontWeight:600 }}>{toast}</span>
          </div>
        )}
      </PhoneFrame>

      {EMBED.chrome && <div style={{ fontSize:12, color:Ca.textTertiary, fontFamily:FONTa }}>
        iPhone 15 Pro · 390×844 · RTL · עברית — לחצי על המסכים למעלה כדי לנווט
      </div>}
    </div>
    </div>
  );
}

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