/* SkinJourney UI Kit — Camera (dark), Comparison (draggable), PhotoViewer */
const Cx = window.SJ.c, Rx = window.SJ.r, ELEVx = window.SJ.elev, FONTx = window.SJ.font;

/* ---- Camera Capture (low-light / dark) ------------------------------------ */
function CameraScreen({ close, onShoot }) {
  const [angle,setAngle]=useState('front');
  const [flash,setFlash]=useState(false);
  const [aligned,setAligned]=useState(false);
  useEffect(()=>{ const t=setTimeout(()=>setAligned(true), 900); return ()=>clearTimeout(t); },[]);
  const shoot = () => {
    setFlash(true);
    setTimeout(()=>{ setFlash(false); onShoot&&onShoot(); }, 480);
  };
  const ANGLES=[{value:'front',label:'חזית'},{value:'right',label:'צד ימין'},{value:'left',label:'צד שמאל'}];
  return (
    <div style={{ position:'absolute', inset:0, background:Cx.darkBg, overflow:'hidden', zIndex:48 }}>
      {/* top controls */}
      <div style={{ position:'absolute', top:54, left:16, right:16, display:'flex',
        flexDirection:'row-reverse', alignItems:'center', gap:10, zIndex:5 }}>
        <button onClick={close} style={{ width:44, height:44, borderRadius:'50%', border:'none',
          background:'rgba(255,255,255,.14)', color:'#fff', display:'flex', alignItems:'center', justifyContent:'center', cursor:'pointer' }}>
          <Icon name="close" size={22} color="#fff"/>
        </button>
        <div style={{ flex:1 }}><Segmented options={ANGLES} value={angle} onChange={setAngle} dark/></div>
      </div>

      {/* lighting indicator */}
      <div style={{ position:'absolute', top:118, left:0, right:0, display:'flex', justifyContent:'center', zIndex:5 }}>
        <div style={{ display:'flex', flexDirection:'row-reverse', alignItems:'center', gap:7,
          background:Cx.sage700, color:'#fff', padding:'8px 16px', borderRadius:Rx.pill, fontSize:14, fontWeight:600 }}>
          <Icon name="checkmark-circle" size={17} color={Cx.sage300}/> תאורה טובה
        </div>
      </div>

      {/* face guide + ghost overlay */}
      <div style={{ position:'absolute', inset:0, display:'flex', alignItems:'center', justifyContent:'center' }}>
        <div style={{ position:'relative', width:280, height:380 }}>
          {/* ghost of previous photo */}
          <PhotoPlaceholder tint={2} rounded="46% 46% 48% 48% / 60% 60% 40% 40%" showIcon={false}
            style={{ position:'absolute', inset:0, opacity:.22 }}/>
          {/* dashed outline */}
          <div style={{ position:'absolute', inset:0, border:`2px dashed ${aligned?Cx.sage300:'rgba(255,255,255,.4)'}`,
            borderRadius:'46% 46% 48% 48% / 60% 60% 40% 40%', transition:'border-color .4s' }}/>
          {/* simple face guide */}
          <svg viewBox="0 0 120 150" style={{ position:'absolute', inset:0, width:'100%', height:'100%', opacity:.5 }}>
            <path d="M42 58 Q50 50 60 56" stroke="#9aa39d" strokeWidth="3" fill="none" strokeLinecap="round"/>
            <path d="M62 58 Q72 50 80 58" stroke="#9aa39d" strokeWidth="3" fill="none" strokeLinecap="round"/>
            <path d="M61 64 L61 86 Q61 92 67 92" stroke="#9aa39d" strokeWidth="3" fill="none" strokeLinecap="round"/>
            <path d="M48 104 Q61 114 74 104" stroke="#9aa39d" strokeWidth="3" fill="none" strokeLinecap="round"/>
          </svg>
          {/* aligned pulse */}
          {aligned && (
            <div style={{ position:'absolute', top:-14, left:0, right:0, display:'flex', justifyContent:'center',
              animation:'sjPulse .5s cubic-bezier(.2,0,0,1)' }}>
              <div style={{ display:'flex', flexDirection:'row-reverse', alignItems:'center', gap:5,
                background:Cx.sage600, color:'#fff', padding:'5px 12px', borderRadius:Rx.pill, fontSize:13, fontWeight:700 }}>
                <Icon name="checkmark" size={14} color="#fff"/> מיושר
              </div>
            </div>
          )}
        </div>
      </div>

      {/* hint */}
      <div style={{ position:'absolute', bottom:150, left:0, right:0, textAlign:'center',
        fontSize:14, color:Cx.darkTextDim, padding:'0 40px' }}>
        יישרי את הפנים לפי התמונה הקודמת
      </div>

      {/* shutter */}
      <div style={{ position:'absolute', bottom:54, left:0, right:0, display:'flex', justifyContent:'center' }}>
        <Shutter onClick={shoot}/>
      </div>

      {flash && <div style={{ position:'absolute', inset:0, background:'rgba(255,255,255,.55)',
        animation:'sjFlash .48s ease', zIndex:30 }}/>}
    </div>
  );
}
function Shutter({ onClick }) {
  const { bind, transform } = usePress(0.92);
  return (
    <button {...bind} onClick={onClick} style={{ width:78, height:78, borderRadius:'50%',
      background:'transparent', border:`5px solid #fff`, display:'flex', alignItems:'center',
      justifyContent:'center', cursor:'pointer', transform, transition:'transform .12s' }}>
      <div style={{ width:58, height:58, borderRadius:'50%', background:Cx.sage300 }}/>
    </button>
  );
}

/* ---- Before / After Comparison (draggable divider) ------------------------ */
function ComparisonScreen() {
  const [pos,setPos]=useState(50);
  const ref = useRef(null);
  const dragging = useRef(false);
  useEffect(()=>{ // first-view hint nudge
    const t1=setTimeout(()=>setPos(62),500), t2=setTimeout(()=>setPos(50),900);
    return ()=>{clearTimeout(t1);clearTimeout(t2);};
  },[]);
  const move = (clientX) => {
    const el = ref.current; if(!el) return;
    const rect = el.getBoundingClientRect();
    let p = ((clientX-rect.left)/rect.width)*100;
    p = Math.max(2, Math.min(98, p));
    setPos(p);
  };
  const onDown = e => { dragging.current=true; move(e.clientX); };
  const onMove = e => { if(dragging.current) move(e.clientX); };
  const onUp = () => {
    dragging.current=false;
    setPos(p => p>85?98 : p<15?2 : p); // snap near endpoints
  };
  return (
    <div style={{ position:'absolute', inset:0, background:Cx.bg, overflowY:'auto', paddingBottom:110 }}
      onPointerMove={onMove} onPointerUp={onUp} onPointerLeave={onUp}>
      <div style={{ paddingTop:56 }}>
        <div style={{ display:'flex', flexDirection:'row-reverse', alignItems:'center',
          justifyContent:'space-between', padding:'8px 20px 4px' }}>
          <div style={{ display:'flex', flexDirection:'row-reverse', alignItems:'center', gap:10 }}>
            <div style={{ width:40, height:40, borderRadius:'50%', background:Cx.sage100,
              display:'flex', alignItems:'center', justifyContent:'center' }}><Icon name="person" size={20} color={Cx.sage600}/></div>
            <div style={{ fontSize:22, fontWeight:700, color:Cx.textPrimary }}>שלום, זוהר</div>
          </div>
          <span style={{ fontSize:20 }}>🔥</span>
        </div>

        {/* date selector */}
        <div style={{ display:'flex', flexDirection:'row-reverse', alignItems:'center', gap:8, padding:'12px 20px' }}>
          <DatePill icon="calendar-outline" label="היום"/>
          <Icon name="arrow-back" size={18} color={Cx.textTertiary}/>
          <DatePill icon="calendar-outline" label="12 נוב׳ 2023" filled/>
        </div>

        {/* compare */}
        <div style={{ padding:'4px 20px' }}>
          <div ref={ref} onPointerDown={onDown} style={{ position:'relative', width:'100%', height:380,
            borderRadius:Rx.xl, overflow:'hidden', boxShadow:ELEVx[2], userSelect:'none', touchAction:'none', cursor:'ew-resize' }}>
            <PhotoPlaceholder tint={0} rounded={0} showIcon={true} style={{ position:'absolute', inset:0 }}/>
            <div style={{ position:'absolute', inset:0, width:`${pos}%`, overflow:'hidden' }}>
              <PhotoPlaceholder tint={3} rounded={0} showIcon={true}
                style={{ position:'absolute', top:0, right:0, height:'100%', width:`${100/pos*100}%` }}/>
            </div>
            <Tag label="לפני" style={{ top:12, insetInlineStart:12 }}/>
            <Tag label="היום" style={{ top:12, insetInlineEnd:12 }}/>
            {/* divider */}
            <div style={{ position:'absolute', top:0, bottom:0, left:`${pos}%`, transform:'translateX(-50%)',
              width:3, background:'#fff', boxShadow:'0 0 8px rgba(0,0,0,.25)' }}>
              <div style={{ position:'absolute', top:'50%', left:'50%', transform:'translate(-50%,-50%)',
                width:44, height:44, borderRadius:'50%', background:'#fff', boxShadow:ELEVx[2],
                display:'flex', alignItems:'center', justifyContent:'center' }}>
                <Icon name="code-outline" size={20} color={Cx.sage700} style={{ transform:'rotate(90deg)' }}/>
              </div>
            </div>
          </div>
        </div>

        <div style={{ padding:'16px 20px 0' }}>
          <Card elev={1} style={{ display:'flex', flexDirection:'row-reverse', alignItems:'center', gap:12 }}>
            <div style={{ width:44, height:44, borderRadius:'50%', background:Cx.sage100,
              display:'flex', alignItems:'center', justifyContent:'center' }}><Icon name="trending-up-outline" size={22} color={Cx.sage700}/></div>
            <div style={{ flex:1, textAlign:'right' }}>
              <div style={{ fontSize:17, fontWeight:700, color:Cx.textPrimary }}>מגמה חיובית</div>
              <p style={{ fontSize:14, color:Cx.textSecondary, margin:'2px 0 0', lineHeight:1.5 }}>
                ב-6 שבועות של מעקב עקבי, עור הפנים נראה רגוע יותר.
              </p>
            </div>
          </Card>
        </div>

        <div style={{ padding:'16px 20px 0', display:'flex', flexDirection:'column', gap:10 }}>
          <Btn label="שתפי עם המטפל/ת" icon="share-outline"/>
          <Btn label="שמרי כתמונה" icon="download-outline" variant="secondary"/>
        </div>
      </div>
    </div>
  );
}
function DatePill({ icon, label, filled }) {
  return (
    <div style={{ flex:1, display:'flex', flexDirection:'row-reverse', alignItems:'center', justifyContent:'center', gap:8,
      background: filled?Cx.surfaceElevated:Cx.surfaceSunken, border:`1px solid ${Cx.borderSubtle}`,
      borderRadius:Rx.pill, padding:'11px 14px', fontSize:14, fontWeight:600, color:Cx.textPrimary }}>
      {label}<Icon name={icon} size={17} color={Cx.sage600}/>
    </div>
  );
}
function Tag({ label, style }) {
  return <div style={{ position:'absolute', background:'rgba(255,252,248,.9)', color:Cx.textPrimary,
    fontSize:12, fontWeight:700, padding:'4px 12px', borderRadius:Rx.pill, boxShadow:ELEVx[1], ...style }}>{label}</div>;
}

/* ---- Photo Viewer (shared-element target) --------------------------------- */
function PhotoViewer({ item, close }) {
  return (
    <div style={{ position:'absolute', inset:0, zIndex:50, background:Cx.darkBg,
      display:'flex', flexDirection:'column', animation:'sjFade .3s ease' }}>
      <div style={{ display:'flex', flexDirection:'row-reverse', alignItems:'center',
        justifyContent:'space-between', padding:'56px 20px 12px' }}>
        <button onClick={close} style={{ width:44, height:44, borderRadius:'50%', border:'none',
          background:'rgba(255,255,255,.14)', color:'#fff', display:'flex', alignItems:'center', justifyContent:'center', cursor:'pointer' }}>
          <Icon name="close" size={22} color="#fff"/>
        </button>
        <div style={{ textAlign:'right' }}>
          <div style={{ fontSize:18, fontWeight:700, color:'#fff' }}>שבוע {item?.week||12}</div>
          <div style={{ fontSize:13, color:Cx.darkTextDim }}>{item?.label||'12 אוק׳'} · חזית</div>
        </div>
      </div>
      <div style={{ flex:1, display:'flex', alignItems:'center', justifyContent:'center', padding:20 }}>
        <PhotoPlaceholder tint={item?.tint||3} rounded={Rx.xl} showIcon
          style={{ width:'100%', height:480, boxShadow:ELEVx[4] }}/>
      </div>
    </div>
  );
}

Object.assign(window, { CameraScreen, ComparisonScreen, PhotoViewer });
