// primitives.jsx — small UI atoms shared across screens

// Theme tokens — read CSS vars from the FitKit phone wrapper
const tokens = (dark) => dark ? {
  bg:'#0E1110', card:'#191D1B', card2:'#22272A', line:'rgba(255,255,255,0.08)',
  ink:'#F4F7F4', ink2:'rgba(244,247,244,0.62)', ink3:'rgba(244,247,244,0.38)',
  brand:'#C9F76F', brandInk:'#0E1110', warn:'#FFB36B', danger:'#FF8273', good:'#9BE36B',
  chip:'rgba(255,255,255,0.06)',
} : {
  bg:'#F4F4EE', card:'#FFFFFF', card2:'#F0EFE7', line:'rgba(20,22,18,0.08)',
  ink:'#14180F', ink2:'rgba(20,24,15,0.6)', ink3:'rgba(20,24,15,0.36)',
  brand:'#C9F76F', brandInk:'#0E1110', warn:'#FF8A33', danger:'#E1573B', good:'#41A55E',
  chip:'rgba(20,22,18,0.05)',
};

// ── Avatar — initials with colored seed
function Avatar({ name='?', tone='#9BE36B', size=36, ring=false, dark=false }) {
  const initials = name.split(' ').map(s=>s[0]).slice(0,2).join('').toUpperCase();
  return (
    <div style={{
      width:size, height:size, borderRadius:size/2,
      background:tone, color:'#0E1110',
      display:'flex', alignItems:'center', justifyContent:'center',
      fontWeight:700, fontSize:size*0.36, fontFamily:'"Plus Jakarta Sans", system-ui',
      boxShadow: ring ? `0 0 0 2px ${dark?'#0E1110':'#fff'}, 0 0 0 4px ${tone}` : 'none',
      flexShrink:0,
    }}>{initials}</div>
  );
}

// ── Pill / Chip
function Pill({ children, tone, dark, kind='default', style={} }) {
  const T = tokens(dark);
  const map = {
    default: { bg: T.chip, fg: T.ink },
    brand:   { bg: T.brand, fg: T.brandInk },
    good:    { bg: dark?'rgba(155,227,107,.16)':'#E5F5D5', fg: dark?'#9BE36B':'#2E7C3D' },
    warn:    { bg: dark?'rgba(255,179,107,.18)':'#FFE8D2', fg: dark?'#FFB36B':'#9C4A0E' },
    danger:  { bg: dark?'rgba(255,130,115,.18)':'#FCE2DC', fg: dark?'#FF8273':'#9A2D17' },
    ghost:   { bg: 'transparent', fg: T.ink2 },
  };
  const c = map[kind];
  return <span style={{
    display:'inline-flex', alignItems:'center', gap:5, height:22, padding:'0 9px',
    borderRadius:99, fontSize:11, fontWeight:600, letterSpacing:0.1,
    background:tone||c.bg, color:c.fg, ...style,
  }}>{children}</span>;
}

// ── Inline icons (stroke style, 20px)
function Icon({ name, size=20, color='currentColor', stroke=1.7 }) {
  const sw = stroke; const s = size;
  const props = { width:s, height:s, viewBox:'0 0 24 24', fill:'none',
    stroke:color, strokeWidth:sw, strokeLinecap:'round', strokeLinejoin:'round' };
  switch(name){
    case 'home': return <svg {...props}><path d="M3 11.5 12 4l9 7.5"/><path d="M5 10v10h14V10"/></svg>;
    case 'dumbbell': return <svg {...props}><path d="M2 12h2M20 12h2M6 8v8M18 8v8M6 12h12"/><path d="M9 6v12M15 6v12"/></svg>;
    case 'fork': return <svg {...props}><path d="M5 3v7a3 3 0 0 0 6 0V3M8 10v11"/><path d="M17 3c-1.5 1.5-2 3-2 5s.5 2.5 2 3v10"/></svg>;
    case 'chat': return <svg {...props}><path d="M4 5h16v11H8l-4 4z"/></svg>;
    case 'cal': return <svg {...props}><rect x="3" y="5" width="18" height="16" rx="2"/><path d="M3 10h18M8 3v4M16 3v4"/></svg>;
    case 'plus': return <svg {...props}><path d="M12 5v14M5 12h14"/></svg>;
    case 'check': return <svg {...props}><path d="M4 12.5 9 17l11-11"/></svg>;
    case 'flame': return <svg {...props}><path d="M12 22c4 0 7-3 7-7 0-3-2-5-3-7-1 2-2 3-4 3 0-3 1-5 3-8-5 1-9 5-9 11 0 5 3 8 6 8z"/></svg>;
    case 'cam': return <svg {...props}><rect x="3" y="6" width="18" height="14" rx="2"/><circle cx="12" cy="13" r="4"/><path d="M8 6l2-2h4l2 2"/></svg>;
    case 'mic': return <svg {...props}><rect x="9" y="3" width="6" height="12" rx="3"/><path d="M5 11a7 7 0 0 0 14 0M12 18v3"/></svg>;
    case 'send': return <svg {...props}><path d="M3 11l18-7-7 18-3-8z"/></svg>;
    case 'bell': return <svg {...props}><path d="M6 8a6 6 0 1 1 12 0c0 5 2 7 2 7H4s2-2 2-7zM10 20a2 2 0 0 0 4 0"/></svg>;
    case 'play': return <svg {...props} fill={color} stroke="none"><path d="M7 4l13 8-13 8z"/></svg>;
    case 'arrow': return <svg {...props}><path d="M5 12h14M13 6l6 6-6 6"/></svg>;
    case 'back': return <svg {...props}><path d="M19 12H5M11 6l-6 6 6 6"/></svg>;
    case 'more': return <svg {...props}><circle cx="5" cy="12" r="1.4" fill={color}/><circle cx="12" cy="12" r="1.4" fill={color}/><circle cx="19" cy="12" r="1.4" fill={color}/></svg>;
    case 'filter': return <svg {...props}><path d="M4 6h16M7 12h10M10 18h4"/></svg>;
    case 'search': return <svg {...props}><circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/></svg>;
    case 'trend-up': return <svg {...props}><path d="M3 17l6-6 4 4 8-8M15 7h6v6"/></svg>;
    case 'trend-dn': return <svg {...props}><path d="M3 7l6 6 4-4 8 8M15 17h6v-6"/></svg>;
    case 'star': return <svg {...props}><path d="M12 3l2.7 5.7 6.3.6-4.7 4.4 1.3 6.3L12 16.9l-5.6 3.1 1.3-6.3L3 9.3l6.3-.6z"/></svg>;
    case 'lock': return <svg {...props}><rect x="5" y="11" width="14" height="9" rx="2"/><path d="M8 11V8a4 4 0 0 1 8 0v3"/></svg>;
    case 'target': return <svg {...props}><circle cx="12" cy="12" r="9"/><circle cx="12" cy="12" r="5"/><circle cx="12" cy="12" r="1.6" fill={color} stroke="none"/></svg>;
    case 'x': return <svg {...props}><path d="M6 6l12 12M18 6 6 18"/></svg>;
    case 'wave': return <svg {...props}><path d="M3 12c2 0 2-3 4-3s2 6 4 6 2-6 4-6 2 3 4 3"/></svg>;
    case 'spark': return <svg {...props}><path d="M12 3l1.7 4.6L18 9.3l-4.3 1.7L12 15l-1.7-4L6 9.3l4.3-1.7zM18 15l.8 2.2L21 18l-2.2.8L18 21l-.8-2.2L15 18l2.2-.8z"/></svg>;
    case 'gauge': return <svg {...props}><path d="M4 18a8 8 0 1 1 16 0"/><path d="m12 12 4-3"/></svg>;
    case 'water': return <svg {...props}><path d="M12 3s6 7 6 12a6 6 0 0 1-12 0c0-5 6-12 6-12z"/></svg>;
    case 'moon': return <svg {...props}><path d="M20 14a8 8 0 1 1-9-10 6 6 0 0 0 9 10z"/></svg>;
    default: return null;
  }
}

// ── Sparkline (used a lot)
function Sparkline({ data, w=120, h=36, color='#41A55E', fill='rgba(65,165,94,0.14)', dot=true }) {
  const min = Math.min(...data), max = Math.max(...data);
  const range = max-min || 1;
  const stepX = w/(data.length-1);
  const pts = data.map((v,i)=>[i*stepX, h - ((v-min)/range)*(h-6) - 3]);
  const path = pts.map((p,i)=>`${i?'L':'M'}${p[0].toFixed(1)},${p[1].toFixed(1)}`).join(' ');
  const area = `${path} L${w},${h} L0,${h} Z`;
  const last = pts[pts.length-1];
  return (
    <svg width={w} height={h} style={{ overflow:'visible' }}>
      <path d={area} fill={fill}/>
      <path d={path} stroke={color} strokeWidth="1.8" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
      {dot && <circle cx={last[0]} cy={last[1]} r="3" fill={color} stroke="#fff" strokeWidth="1.5"/>}
    </svg>
  );
}

// ── Bar chart
function Bars({ data, w=140, h=46, color='#C9F76F', dark=false, max }) {
  const T = tokens(dark);
  const M = max || Math.max(...data);
  const bw = (w - (data.length-1)*4) / data.length;
  return (
    <svg width={w} height={h}>
      {data.map((v,i)=>{
        const bh = (v/M)*h;
        return <rect key={i} x={i*(bw+4)} y={h-bh} width={bw} height={bh} rx="2" fill={i===data.length-1?color:T.line}/>;
      })}
    </svg>
  );
}

// ── Ring (donut for progress %)
function Ring({ value=0.6, size=64, stroke=6, color='#41A55E', track='rgba(0,0,0,0.08)', label }) {
  const r = (size-stroke)/2; const c = 2*Math.PI*r;
  return (
    <div style={{ position:'relative', width:size, height:size, flexShrink:0 }}>
      <svg width={size} height={size}>
        <circle cx={size/2} cy={size/2} r={r} stroke={track} strokeWidth={stroke} fill="none"/>
        <circle cx={size/2} cy={size/2} r={r} stroke={color} strokeWidth={stroke} fill="none"
          strokeDasharray={c} strokeDashoffset={c*(1-value)} strokeLinecap="round"
          transform={`rotate(-90 ${size/2} ${size/2})`}/>
      </svg>
      {label!==undefined && (
        <div style={{ position:'absolute', inset:0, display:'flex', alignItems:'center', justifyContent:'center',
          fontWeight:700, fontSize:size*0.22, fontFamily:'"Plus Jakarta Sans", system-ui'}}>{label}</div>
      )}
    </div>
  );
}

// ── Image placeholder (food, workout cover) — striped + label
function Placeholder({ kind='meal', w='100%', h=140, dark=false, label, tone }) {
  const palettes = {
    meal:{a:'#F2D27D', b:'#E89A4F'},
    breakfast:{a:'#FFE3A8', b:'#FFB36B'},
    lunch:{a:'#D6E89C', b:'#9BC264'},
    snack:{a:'#FFC9C2', b:'#E1573B'},
    lower:{a:'#C9F76F', b:'#7BBE3C'},
    cardio:{a:'#9CD2FF', b:'#3F88C5'},
    upper:{a:'#FFB36B', b:'#E1573B'},
    progress:{a:'#D9D9D5', b:'#9C9C92'},
    body:{a:'#F4D8C7', b:'#C58A6B'},
    pills:{a:'#E8D9F4', b:'#9F7BC7'},
    gym:{a:'#9C9C92', b:'#444'},
    doc:{a:'#E8E5DA', b:'#9C9C92'},
  };
  const c = tone || palettes[kind] || palettes.meal;
  return (
    <div style={{
      width:w, height:h, borderRadius:14, overflow:'hidden',
      background:`linear-gradient(135deg, ${c.a}, ${c.b})`,
      position:'relative', display:'flex', alignItems:'flex-end', padding:10,
    }}>
      <svg width="100%" height="100%" style={{ position:'absolute', inset:0, opacity:0.18 }}>
        <defs>
          <pattern id={`p-${kind}`} width="14" height="14" patternUnits="userSpaceOnUse" patternTransform="rotate(35)">
            <line x1="0" y1="0" x2="0" y2="14" stroke="#fff" strokeWidth="6"/>
          </pattern>
        </defs>
        <rect width="100%" height="100%" fill={`url(#p-${kind})`}/>
      </svg>
      {label && (
        <span style={{
          position:'relative', zIndex:1, fontSize:10, fontFamily:'"JetBrains Mono", monospace',
          background:'rgba(14,17,16,0.7)', color:'#fff', padding:'4px 8px', borderRadius:6,
          letterSpacing:0.4, textTransform:'uppercase',
        }}>{label}</span>
      )}
    </div>
  );
}

// ── Tab bar (bottom nav for app)
function TabBar({ active, onChange, dark, role='trainee' }) {
  const T = tokens(dark);
  const tabs = role === 'trainer'
    ? [
        {id:'home', label:'Home', icon:'home'},
        {id:'roster', label:'Roster', icon:'dumbbell'},
        {id:'meals', label:'Reviews', icon:'fork'},
        {id:'chat', label:'Chat', icon:'chat'},
        {id:'cal', label:'Calendar', icon:'cal'},
      ]
    : [
        {id:'home', label:'Today', icon:'home'},
        {id:'plan', label:'Plan', icon:'dumbbell'},
        {id:'meals', label:'Meals', icon:'fork'},
        {id:'chat', label:'Chat', icon:'chat'},
        {id:'me', label:'Me', icon:'target'},
      ];
  return (
    <div style={{
      position:'absolute', bottom:0, left:0, right:0, paddingBottom:30, zIndex:30,
      background: dark ? 'rgba(14,17,16,0.85)' : 'rgba(244,244,238,0.85)',
      backdropFilter:'blur(20px) saturate(180%)', WebkitBackdropFilter:'blur(20px) saturate(180%)',
      borderTop:`0.5px solid ${T.line}`,
    }}>
      <div style={{ display:'flex', padding:'8px 6px 0', justifyContent:'space-around' }}>
        {tabs.map(t=>{
          const on = active===t.id;
          return (
            <button key={t.id} onClick={()=>onChange(t.id)} style={{
              flex:1, padding:'6px 4px 4px', display:'flex', flexDirection:'column',
              alignItems:'center', gap:3, background:'transparent', border:0, cursor:'pointer',
              color: on ? T.ink : T.ink3,
            }}>
              <Icon name={t.icon} size={22} color={on ? T.ink : T.ink3} stroke={on?2.1:1.7}/>
              <span style={{ fontSize:10, fontWeight:on?700:500, letterSpacing:0.2 }}>{t.label}</span>
            </button>
          );
        })}
      </div>
    </div>
  );
}

// ── Status bar that matches our theme
function PhoneStatus({ dark, time='9:41' }) {
  const c = dark ? '#fff' : '#000';
  return (
    <div style={{
      display:'flex', justifyContent:'space-between', alignItems:'center',
      padding:'14px 28px 6px', height:44, position:'relative', zIndex:20,
      fontFamily:'-apple-system, "SF Pro", system-ui',
    }}>
      <span style={{ fontSize:16, fontWeight:600, color:c }}>{time}</span>
      <div style={{
        position:'absolute', left:'50%', top:11, transform:'translateX(-50%)',
        width:118, height:32, borderRadius:20, background:'#000',
      }}/>
      <div style={{ display:'flex', gap:6, alignItems:'center' }}>
        <svg width="18" height="11" viewBox="0 0 18 11"><rect x="0" y="6" width="3" height="4" rx=".5" fill={c}/><rect x="4.5" y="4" width="3" height="6" rx=".5" fill={c}/><rect x="9" y="2" width="3" height="8" rx=".5" fill={c}/><rect x="13.5" y="0" width="3" height="10" rx=".5" fill={c}/></svg>
        <svg width="25" height="12" viewBox="0 0 25 12"><rect x="0.5" y="0.5" width="21" height="11" rx="3" stroke={c} strokeOpacity=".4" fill="none"/><rect x="2" y="2" width="15" height="8" rx="1.5" fill={c}/><rect x="22.5" y="3.5" width="1.5" height="5" rx=".5" fill={c} opacity=".4"/></svg>
      </div>
    </div>
  );
}

// ── Phone shell (custom — we control the chrome so theming is consistent)
function PhoneShell({ children, dark=false, width=390, height=844, frame='ios' }) {
  const T = tokens(dark);
  if (frame === 'android') {
    const radius = 38;
    return (
      <div style={{
        width:width+16, height:height+16, borderRadius:radius+6, padding:8,
        background: dark ? '#1A1A1A' : '#2D2A28',
        boxShadow:'0 30px 80px rgba(0,0,0,0.28), 0 0 0 1px rgba(0,0,0,0.1)',
      }}>
        <div style={{
          width, height, borderRadius:radius, overflow:'hidden', background:T.bg,
          position:'relative',
        }}>
          {children}
          <div style={{
            position:'absolute', bottom:0, left:0, right:0, height:24,
            display:'flex', alignItems:'center', justifyContent:'center', zIndex:60, pointerEvents:'none'
          }}>
            <div style={{ width:120, height:4, borderRadius:2, background: dark?'rgba(255,255,255,.55)':'rgba(20,20,20,0.45)'}}/>
          </div>
        </div>
      </div>
    );
  }
  // iOS
  return (
    <div style={{
      width, height, borderRadius:48, overflow:'hidden', background:T.bg,
      position:'relative',
      boxShadow:'0 40px 80px rgba(0,0,0,0.18), 0 0 0 1px rgba(0,0,0,0.12)',
      fontFamily:'"Inter", -apple-system, system-ui, sans-serif',
    }}>
      {children}
      {/* home indicator */}
      <div style={{
        position:'absolute', bottom:8, left:0, right:0, zIndex:60,
        display:'flex', justifyContent:'center', pointerEvents:'none'
      }}>
        <div style={{ width:139, height:5, borderRadius:100,
          background: dark ? 'rgba(255,255,255,0.55)' : 'rgba(0,0,0,0.28)' }}/>
      </div>
    </div>
  );
}

Object.assign(window, {
  tokens, Avatar, Pill, Icon, Sparkline, Bars, Ring, Placeholder, TabBar, PhoneStatus, PhoneShell,
});
