/* SkinJourney UI Kit — shared components. Exports to window for cross-file use. */
const { useState, useRef, useEffect, useCallback } = React;
const C = window.SJ.c, GRAD = window.SJ.grad, ELEV = window.SJ.elev, R = window.SJ.r, FONT = window.SJ.font;

/* ---- Icon (Ionicons web component) ---------------------------------------- */
function Icon({ name, size = 24, color = 'currentColor', style }) {
  return <ion-icon name={name} style={{ fontSize: size, color, ...style }}></ion-icon>;
}

/* ---- Brand leaf ----------------------------------------------------------- */
function Leaf({ size = 40, fill = C.primary, vein = C.sage300 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 48 48" style={{ display:'block' }}>
      <path d="M10 38 C10 22 22 10 38 10 C38 26 26 38 10 38 Z" fill={fill}/>
      <path d="M14 34 C20 24 26 18 34 14" stroke={vein} strokeWidth="2.4" strokeLinecap="round" fill="none"/>
    </svg>
  );
}

/* ---- press-scale spring --------------------------------------------------- */
function usePress(scale = 0.96) {
  const [p, setP] = useState(false);
  const bind = {
    onPointerDown: () => setP(true),
    onPointerUp: () => setP(false),
    onPointerLeave: () => setP(false),
  };
  const transform = `scale(${p ? scale : 1})`;
  return { bind, transform, pressed: p };
}

/* ---- Button --------------------------------------------------------------- */
function Btn({ label, icon, onClick, variant = 'primary', disabled, full = true, style }) {
  const { bind, transform } = usePress();
  const base = {
    display:'flex', alignItems:'center', justifyContent:'center', gap:8,
    border:'none', borderRadius:R.pill, padding:'15px 28px', fontFamily:FONT,
    fontSize:16, fontWeight:700, cursor:'pointer', width: full ? '100%' : 'auto',
    transition:'transform .12s cubic-bezier(.4,0,.2,1), box-shadow .12s, background .15s',
    transform, opacity: disabled ? 0.4 : 1, boxSizing:'border-box', ...style,
  };
  const variants = {
    primary: { background:C.primary, color:'#fff', boxShadow: ELEV.sage },
    secondary: { background:'transparent', color:C.primary, border:`1.5px solid ${C.primary}` },
    text: { background:'transparent', color:C.primary, boxShadow:'none', padding:'10px 12px' },
    danger: { background:'transparent', color:C.error, border:`1.5px solid ${C.error}` },
    dark: { background:'rgba(255,255,255,.14)', color:'#fff' },
  };
  return (
    <button {...bind} onClick={disabled ? undefined : onClick} style={{ ...base, ...variants[variant] }}>
      {icon && <Icon name={icon} size={19} />}{label}
    </button>
  );
}

/* ---- Card ----------------------------------------------------------------- */
function Card({ children, tone = 'default', style, elev = 2, onClick }) {
  const bg = tone === 'high' ? C.sage100 : tone === 'sunken' ? C.surfaceSunken : C.surfaceElevated;
  return (
    <div onClick={onClick} style={{
      background:bg, borderRadius:R.xl, padding:18,
      border:`1px solid ${tone==='high'?C.sage200:C.borderSubtle}`,
      boxShadow: ELEV[elev] || ELEV[2], ...style }}>{children}</div>
  );
}

/* ---- Chip ----------------------------------------------------------------- */
function Chip({ label, selected, accent, onClick }) {
  const { bind, transform } = usePress(0.94);
  const sel = selected
    ? (accent ? { background:C.accent, borderColor:C.accent, color:'#fff' }
               : { background:C.sage300, borderColor:C.sage300, color:C.sage800 })
    : { background:C.surfaceElevated, borderColor:C.borderDefault, color:C.textSecondary };
  return (
    <button {...bind} onClick={onClick} style={{
      padding:'9px 18px', borderRadius:R.pill, fontSize:14, fontWeight:600, fontFamily:FONT,
      borderWidth:1, borderStyle:'solid', cursor:'pointer', transform,
      transition:'transform .12s, background .15s, border-color .15s', ...sel }}>{label}</button>
  );
}

/* ---- Segmented (RTL) ------------------------------------------------------ */
function Segmented({ options, value, onChange, dark }) {
  return (
    <div style={{ display:'flex', background: dark?'rgba(255,255,255,.12)':C.surfaceSunken,
      borderRadius:R.pill, padding:4, direction:'rtl' }}>
      {options.map(o => {
        const on = o.value === value;
        return (
          <button key={o.value} onClick={() => onChange(o.value)} style={{
            flex:1, border:'none', background: on ? (dark?C.sage300:C.sage300) : 'transparent',
            color: on ? C.sage800 : (dark?'#fff':C.textSecondary),
            padding:'9px 0', borderRadius:R.pill, fontSize:14, fontWeight:600, fontFamily:FONT,
            cursor:'pointer', boxShadow: on ? ELEV[1] : 'none', transition:'all .18s' }}>{o.label}</button>
        );
      })}
    </div>
  );
}

/* ---- Input ---------------------------------------------------------------- */
function Input({ label, value, onChange, placeholder, type='text' }) {
  const [focus, setFocus] = useState(false);
  return (
    <div>
      {label && <div style={{ fontSize:13, fontWeight:600, color:C.textSecondary, marginBottom:6 }}>{label}</div>}
      <input value={value||''} onChange={e=>onChange&&onChange(e.target.value)} placeholder={placeholder}
        type={type} onFocus={()=>setFocus(true)} onBlur={()=>setFocus(false)}
        style={{ width:'100%', boxSizing:'border-box', background:C.surfaceElevated,
          border:`1.5px solid ${focus?C.borderFocus:C.borderDefault}`, borderRadius:R.md,
          padding:'13px 16px', fontSize:15, color:C.textPrimary, fontFamily:FONT, textAlign:'right',
          outline:'none', boxShadow: focus?'0 0 0 3px rgba(73,100,89,.12)':'none', transition:'all .2s' }}/>
    </div>
  );
}

/* ---- Toggle --------------------------------------------------------------- */
function Toggle({ on, onChange }) {
  return (
    <div onClick={()=>onChange&&onChange(!on)} style={{
      width:52, height:30, borderRadius:R.pill, position:'relative', cursor:'pointer',
      background: on ? C.sage300 : C.surfaceSunken, border: on?'none':`1px solid ${C.borderDefault}`,
      transition:'background .15s' }}>
      <div style={{ position:'absolute', top:3, right: on?3:'auto', left: on?'auto':25,
        width:24, height:24, borderRadius:'50%', background: on?C.primary:C.surfaceElevated,
        boxShadow:ELEV[1], transition:'all .15s' }}/>
    </div>
  );
}

/* ---- ProgressDots --------------------------------------------------------- */
function ProgressDots({ total, index }) {
  return (
    <div style={{ display:'flex', gap:8, direction:'rtl' }}>
      {Array.from({length:total}).map((_,i)=>(
        <div key={i} style={{ height:8, width: i===index?24:8, borderRadius:R.pill,
          background: i===index?C.primary:C.borderDefault, transition:'all .25s' }}/>
      ))}
    </div>
  );
}

/* ---- StreakRing ----------------------------------------------------------- */
function StreakRing({ value=3, total=4, size=150, label='שבועות רצופים', glow=true }) {
  const r = (size-26)/2, circ = 2*Math.PI*r;
  const pct = Math.min(value/total, 1);
  const [off, setOff] = useState(circ);
  useEffect(()=>{ const t=setTimeout(()=>setOff(circ*(1-pct)), 150); return ()=>clearTimeout(t); },[circ,pct]);
  return (
    <div style={{ position:'relative', width:size, height:size, display:'flex', alignItems:'center', justifyContent:'center' }}>
      {glow && <div style={{ position:'absolute', inset:-18, background:GRAD.streakGlow, borderRadius:'50%' }}/>}
      <svg width={size} height={size} style={{ position:'absolute', transform:'rotate(-90deg)' }}>
        <circle cx={size/2} cy={size/2} r={r} fill="none" stroke={C.sage100} strokeWidth="12"/>
        <circle cx={size/2} cy={size/2} r={r} fill="none" stroke={C.sage500} strokeWidth="12" strokeLinecap="round"
          strokeDasharray={circ} strokeDashoffset={off} style={{ transition:'stroke-dashoffset 1s cubic-bezier(.2,0,0,1)' }}/>
      </svg>
      <div style={{ position:'relative', textAlign:'center', zIndex:2 }}>
        <div style={{ fontSize:size*0.3, fontWeight:800, color:C.sage700, lineHeight:1, fontVariantNumeric:'tabular-nums' }}>{value}</div>
        <div style={{ fontSize:13, fontWeight:600, color:C.textSecondary, marginTop:2 }}>{label}</div>
      </div>
    </div>
  );
}

/* ---- PhotoPlaceholder — respectful stand-in for a sensitive face photo ---- */
function PhotoPlaceholder({ tint=0, style, rounded=R.lg, showIcon=true, label }) {
  const tints = [
    'linear-gradient(160deg,#F4E3DA,#E9D2C6)',
    'linear-gradient(160deg,#F0E0D6,#E2CBC0)',
    'linear-gradient(160deg,#EDDCD3,#DDC6BA)',
    'linear-gradient(160deg,#F2E6DD,#E6D0C4)',
  ];
  return (
    <div style={{ background:tints[tint%tints.length], borderRadius:rounded, position:'relative',
      display:'flex', alignItems:'center', justifyContent:'center', overflow:'hidden', ...style }}>
      {showIcon && <Icon name="person" size={Math.min((style&&style.height)||40, 64)*0.55} color="rgba(134,80,70,.32)"/>}
      {label && <div style={{ position:'absolute', bottom:8, insetInlineStart:10, fontSize:11, fontWeight:700,
        color:'#fff', background:'rgba(22,29,31,.35)', padding:'3px 8px', borderRadius:R.sm }}>{label}</div>}
    </div>
  );
}

/* ---- TabBar --------------------------------------------------------------- */
function TabBar({ active, onTab, onCapture }) {
  const tabs = [
    { k:'home', icon:'home', label:'בית' },
    { k:'timeline', icon:'time-outline', label:'היסטוריה' },
    { k:'compare', icon:'git-compare-outline', label:'השוואה' },
    { k:'settings', icon:'settings-outline', label:'הגדרות' },
  ];
  return (
    <div style={{ position:'absolute', bottom:0, left:0, right:0, background:C.surfaceElevated,
      borderTop:`1px solid ${C.borderSubtle}`, boxShadow:'0 -4px 20px rgba(14,27,22,0.05)',
      display:'flex', alignItems:'flex-end', justifyContent:'space-around', direction:'rtl',
      padding:'10px 14px 30px', zIndex:20 }}>
      {tabs.slice(0,2).map(t=><Tab key={t.k} {...t} active={active===t.k} onClick={()=>onTab(t.k)}/>)}
      <div style={{ flex:'0 0 auto', display:'flex', justifyContent:'center' }}>
        <button onClick={onCapture} style={{ width:58, height:58, borderRadius:'50%', background:C.primary,
          color:'#fff', border:'none', display:'flex', alignItems:'center', justifyContent:'center',
          boxShadow:ELEV.sage, marginTop:-30, cursor:'pointer' }}>
          <Icon name="camera" size={26} color="#fff"/>
        </button>
      </div>
      {tabs.slice(2).map(t=><Tab key={t.k} {...t} active={active===t.k} onClick={()=>onTab(t.k)}/>)}
    </div>
  );
}
function Tab({ icon, label, active, onClick }) {
  return (
    <button onClick={onClick} style={{ flex:1, background:'none', border:'none', cursor:'pointer',
      display:'flex', flexDirection:'column', alignItems:'center', gap:4,
      color: active?C.primary:C.textTertiary, fontFamily:FONT, transition:'color .2s' }}>
      <Icon name={active && !icon.includes('outline') ? icon : icon} size={23} />
      <span style={{ fontSize:11, fontWeight:600 }}>{label}</span>
    </button>
  );
}

/* ---- AppHeader ------------------------------------------------------------ */
function AppHeader({ title, sub, right, left }) {
  return (
    <div style={{ display:'flex', flexDirection:'row-reverse', alignItems:'center',
      justifyContent:'space-between', padding:'8px 20px 4px' }}>
      <div style={{ flex:1 }}>
        {sub && <div style={{ fontSize:12, fontWeight:600, color:C.textTertiary, letterSpacing:.4 }}>{sub}</div>}
        <div style={{ fontSize:24, fontWeight:700, color:C.textPrimary, textAlign:'right' }}>{title}</div>
      </div>
      {right}
      {left}
    </div>
  );
}

Object.assign(window, { Icon, Leaf, usePress, Btn, Card, Chip, Segmented, Input, Toggle,
  ProgressDots, StreakRing, PhotoPlaceholder, TabBar, Tab, AppHeader });
