// Reusable UI primitives — bottom tab bar, floating preview chrome, sheets, etc.

function Card({ children, style = {}, t }) {
  return (
    <div style={{
      background: t.surface, borderRadius: 18, padding: 16,
      boxShadow: '0 1px 3px rgba(0,0,0,0.04)',
      ...style,
    }}>{children}</div>
  );
}

function PillToggle({ options, value, onChange, t }) {
  return (
    <div style={{
      display: 'grid', gridTemplateColumns: `repeat(${options.length}, 1fr)`,
      gap: 8, padding: 0,
    }}>
      {options.map(opt => {
        const active = value === opt;
        return (
          <button key={opt} onClick={() => onChange(opt)} style={{
            border: 'none', cursor: 'pointer',
            padding: '14px 0', borderRadius: 999,
            background: active ? t.primary : t.surface3,
            color: active ? t.onPrimary : t.text,
            fontSize: 15, fontWeight: 600,
            fontFamily: 'inherit',
            transition: 'all .2s',
          }}>{opt}</button>
        );
      })}
    </div>
  );
}

// Floating top chrome — back / Coach Switcher / theme / Client App Preview
function PreviewChrome({ dark, setDark, onCoachSwitch, coach }) {
  const bg = dark ? 'rgba(40,40,44,0.85)' : 'rgba(255,255,255,0.85)';
  const text = dark ? '#fff' : '#111';
  const muted = dark ? 'rgba(255,255,255,0.6)' : 'rgba(0,0,0,0.55)';
  const pill = (children, onClick, style = {}) => (
    <button onClick={onClick} style={{
      height: 30, padding: '0 11px', border: 'none',
      borderRadius: 999, background: bg,
      backdropFilter: 'blur(20px) saturate(180%)',
      WebkitBackdropFilter: 'blur(20px) saturate(180%)',
      boxShadow: '0 1px 3px rgba(0,0,0,0.08), 0 4px 16px rgba(0,0,0,0.06)',
      display: 'inline-flex', alignItems: 'center', gap: 6,
      color: text, fontSize: 12, fontWeight: 600, cursor: 'pointer',
      fontFamily: 'inherit',
      ...style,
    }}>{children}</button>
  );
  return (
    <div style={{
      position: 'absolute', top: 56, left: 0, right: 0, zIndex: 40,
      display: 'flex', justifyContent: 'space-between', alignItems: 'center',
      padding: '0 10px', pointerEvents: 'none',
    }}>
      <div style={{ display: 'flex', gap: 6, pointerEvents: 'auto' }}>
        {pill(
          dark
            ? <Icon.Sun size={14} color={text}/>
            : <Icon.Moon size={14} color={text}/>,
          () => setDark(!dark),
          { padding: '0 9px' }
        )}
      </div>
    </div>
  );
}

// Bottom tab bar
function TabBar({ active, setActive, t }) {
  const tabs = [
    { id: 'home',      label: 'Home',      Icon: Icon.Home },
    { id: 'workouts',  label: 'Workouts',  Icon: Icon.Workouts },
    { id: 'nutrition', label: 'Nutrition', Icon: Icon.Nutrition },
    { id: 'chat',      label: 'Chat',      Icon: Icon.Chat },
    { id: 'profile',   label: 'Profile',   Icon: Icon.Profile },
  ];
  return (
    <div style={{
      position: 'absolute', bottom: 0, left: 0, right: 0, zIndex: 30,
      background: t.surface,
      borderTop: `1px solid ${t.border}`,
      paddingBottom: 24, paddingTop: 8,
      display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)',
    }}>
      {tabs.map(tab => {
        const isActive = active === tab.id;
        return (
          <button key={tab.id} onClick={() => setActive(tab.id)} style={{
            background: 'none', border: 'none', cursor: 'pointer',
            display: 'flex', flexDirection: 'column', alignItems: 'center',
            gap: 4, padding: '6px 0', fontFamily: 'inherit',
          }}>
            {isActive ? (
              <div style={{
                width: 38, height: 38, borderRadius: 999,
                background: t.primary,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}>
                <tab.Icon size={20} color={t.onPrimary}/>
              </div>
            ) : (
              <div style={{ height: 38, display: 'flex', alignItems: 'center' }}>
                <tab.Icon size={22} color={t.textMuted}/>
              </div>
            )}
            <div style={{
              fontSize: 11, fontWeight: 500,
              color: isActive ? t.text : t.textMuted,
            }}>{tab.label}</div>
          </button>
        );
      })}
    </div>
  );
}

// Floating Action Button — sticky to the bottom of the scroll area so it
// rides with the content (avoids overlapping cards mid-scroll).
function FAB({ onClick, t, menu }) {
  const [open, setOpen] = React.useState(false);
  return (
    <div style={{
      position: 'sticky', bottom: 90, zIndex: 25,
      display: 'flex', justifyContent: 'flex-end',
      padding: '0 20px',
      pointerEvents: 'none',
      marginTop: -54,
    }}>
      {open && menu && (
        <div style={{
          position: 'absolute', bottom: 66, right: 20,
          background: t.surface, borderRadius: 14, padding: 6,
          boxShadow: '0 12px 32px rgba(0,0,0,0.18)', border: `1px solid ${t.border}`,
          display: 'flex', flexDirection: 'column', minWidth: 160,
          pointerEvents: 'auto',
          animation: 'fadeIn .15s ease',
        }}>
          {menu.map((m, i) => (
            <button key={i} onClick={() => { setOpen(false); m.onClick(); }} style={{
              background: 'none', border: 'none', cursor: 'pointer',
              padding: '10px 12px', borderRadius: 10,
              display: 'flex', alignItems: 'center', gap: 10,
              fontFamily: 'inherit', textAlign: 'left',
              color: t.text, fontSize: 13, fontWeight: 600,
            }}>
              {m.icon}<span>{m.label}</span>
            </button>
          ))}
        </div>
      )}
      <button onClick={onClick || (() => setOpen(o => !o))} style={{
        width: 54, height: 54, borderRadius: 999,
        background: t.primary, border: 'none', cursor: 'pointer',
        boxShadow: '0 8px 24px rgba(0,0,0,0.18)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        pointerEvents: 'auto',
        transform: open ? 'rotate(45deg)' : 'none',
        transition: 'transform .2s',
      }}>
        <Icon.Plus size={24} color={t.onPrimary}/>
      </button>
    </div>
  );
}

// Header within content area: hamburger, avatar, greeting, action icons
function ContentHeader({ t, coach, greeting = true, leftStyle = 'menu', onMenu, onCommunity, onNotifications }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', padding: '110px 18px 16px' }}>
      {leftStyle === 'menu' && (
        <button onClick={onMenu} style={{
          background: 'none', border: 'none', padding: 0, marginRight: 12, cursor: 'pointer',
        }}><Icon.Menu color={t.text}/></button>
      )}
      {greeting && (
        <>
          <div style={{
            width: 44, height: 44, borderRadius: 999,
            background: `linear-gradient(135deg, ${t.primarySoft}, ${t.primary})`,
            marginRight: 12, flexShrink: 0,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            color: t.onPrimary, fontWeight: 700, fontSize: 16,
            overflow: 'hidden',
          }}>{coach.avatar_img
            ? <img src={coach.avatar_img} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover', borderRadius: 'inherit' }}/>
            : coach.coach.split(' ').map(n => n[0]).join('').slice(0, 2)}</div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 18, fontWeight: 700, color: t.text, lineHeight: 1.1 }}>
              Hola, {DEMO_CLIENT.split(' ')[0]} <span style={{ fontSize: 16 }}>🤍</span>
            </div>
            <div style={{ fontSize: 12, color: t.textMuted, marginTop: 2 }}>Today Sep 10</div>
          </div>
        </>
      )}
      {!greeting && <div style={{ flex: 1 }}/>}
      <div style={{ display: 'flex', gap: 8 }}>
        <button onClick={onCommunity} style={{
          position: 'relative', border: 'none', cursor: 'pointer',
          width: 36, height: 36, borderRadius: 999, background: t.primarySoft,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <Icon.Users size={17} color={t.primary}/>
          <div style={{
            position: 'absolute', top: -2, right: -2,
            background: t.primary, color: t.onPrimary,
            fontSize: 10, fontWeight: 700, borderRadius: 999,
            minWidth: 16, height: 16, padding: '0 4px',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            border: `2px solid ${t.surface}`,
          }}>3</div>
        </button>
        <button onClick={onNotifications} style={{
          width: 36, height: 36, borderRadius: 999, background: t.surface3, border: 'none',
          display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer',
          position: 'relative',
        }}>
          <Icon.Bell size={16} color={t.text}/>
          <div style={{
            position: 'absolute', top: 6, right: 8, width: 8, height: 8, borderRadius: 999,
            background: t.primary, border: `2px solid ${t.surface3}`,
          }}/>
        </button>
      </div>
    </div>
  );
}

// Coach switcher sheet
function CoachSheet({ open, onClose, coach, setCoach, presets, t }) {
  if (!open) return null;
  return (
    <div onClick={onClose} style={{
      position: 'absolute', inset: 0, zIndex: 100,
      background: 'rgba(0,0,0,0.45)',
      display: 'flex', alignItems: 'flex-end',
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        background: t.surface, width: '100%', borderRadius: '24px 24px 0 0',
        padding: '12px 18px 32px',
        animation: 'slideUp .25s ease',
      }}>
        <div style={{
          width: 36, height: 4, background: t.textDim, borderRadius: 2,
          margin: '4px auto 14px',
        }}/>
        <div style={{ fontSize: 18, fontWeight: 700, color: t.text, marginBottom: 4 }}>
          Switch coach brand
        </div>
        <div style={{ fontSize: 13, color: t.textMuted, marginBottom: 16 }}>
          Preview the white-label across different coach brand kits.
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {presets.map(p => {
            const active = coach.id === p.id;
            return (
              <button key={p.id} onClick={() => { setCoach(p); onClose(); }} style={{
                display: 'flex', alignItems: 'center', gap: 12,
                padding: 12, borderRadius: 14,
                border: `1.5px solid ${active ? p.primary : t.border}`,
                background: active ? t.primarySoft : t.surface2,
                cursor: 'pointer', textAlign: 'left',
                fontFamily: 'inherit',
              }}>
                <div style={{
                  width: 40, height: 40, borderRadius: 10,
                  background: p.primary, color: '#fff',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontWeight: 800, fontSize: 14, letterSpacing: -0.5,
                  fontFamily: p.font,
                }}>{p.name[0]}</div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 15, fontWeight: 700, color: t.text }}>{p.name}</div>
                  <div style={{ fontSize: 12, color: t.textMuted }}>{p.handle} · {p.coach}</div>
                </div>
                <div style={{
                  display: 'flex', gap: 4,
                }}>
                  <div style={{ width: 18, height: 18, borderRadius: 4, background: p.primary }}/>
                  <div style={{ width: 18, height: 18, borderRadius: 4, background: p.secondary }}/>
                </div>
              </button>
            );
          })}
        </div>
      </div>
    </div>
  );
}

// Map food/recipe keywords → real Unsplash image URLs (fixed, curated)
// Demo client shown in this preview (Coach Jaz's audience is Latina women)
const DEMO_CLIENT = 'Camila Rivas';
window.DEMO_CLIENT = DEMO_CLIENT;

const FOOD_IMG = {
  oats:              'https://images.unsplash.com/photo-1517673132405-a56a62b18caf?w=600&q=70&auto=format&fit=crop',
  eggs:              'https://images.unsplash.com/photo-1525351484163-7529414344d8?w=600&q=70&auto=format&fit=crop',
  apple:             'https://images.unsplash.com/photo-1568702846914-96b305d2aaeb?w=600&q=70&auto=format&fit=crop',
  chicken:           'https://images.unsplash.com/photo-1604908176997-125f25cc6f3d?w=600&q=70&auto=format&fit=crop',
  'grilled chicken': 'https://images.unsplash.com/photo-1604908176997-125f25cc6f3d?w=600&q=70&auto=format&fit=crop',
  poke:              'https://images.unsplash.com/photo-1563379091339-03b21ab4a4f8?w=600&q=70&auto=format&fit=crop',
  'poke bowl':       'https://images.unsplash.com/photo-1563379091339-03b21ab4a4f8?w=600&q=70&auto=format&fit=crop',
  rice:              'https://images.unsplash.com/photo-1536304993881-ff6e9eefa2a6?w=600&q=70&auto=format&fit=crop',
  veggies:           'https://images.unsplash.com/photo-1540420773420-3366772f4999?w=600&q=70&auto=format&fit=crop',
  shake:             'https://images.unsplash.com/photo-1553530666-ba11a7da3888?w=600&q=70&auto=format&fit=crop',
  smoothie:          'https://images.unsplash.com/photo-1553530666-ba11a7da3888?w=600&q=70&auto=format&fit=crop',
  almonds:           'https://images.unsplash.com/photo-1508061253366-f7da158b6d46?w=600&q=70&auto=format&fit=crop',
  'avocado toast':   'https://images.unsplash.com/photo-1541519227354-08fa5d50c44d?w=600&q=70&auto=format&fit=crop',
  steak:             'https://images.unsplash.com/photo-1558030006-450675393462?w=600&q=70&auto=format&fit=crop',
  pancakes:          'https://images.unsplash.com/photo-1528207776546-365bb710ee93?w=600&q=70&auto=format&fit=crop',
  'meal plan hero':  'https://images.unsplash.com/photo-1490645935967-10de6ba17061?w=900&q=70&auto=format&fit=crop',
  'recipe hero':     'https://images.unsplash.com/photo-1546069901-ba9599a7e63c?w=900&q=70&auto=format&fit=crop',

  // ── Coach Jaz, Project Rebirth (Sep 16 2026 studio shoot) ──
  // Cool-lit frames sit under coral UI chips so the brand colour still reads;
  // warm frames are used only where nothing coral overlays them.
  'gym hero image':        'img/gym-hero.webp',
  'gym hero':              'img/gym-hero.webp',
  'session hero':          'img/session-hero.webp',
  'progress photo':        'img/progress-1.webp',
  'video preview':         'img/video-preview.webp',
  'exercise video / image':'img/ex-row.webp',
  'bench':                 'img/ex-press.webp',
  'bench press':           'img/ex-press.webp',
  'ohp':                   'img/ex-ohp.webp',
  'overhead press':        'img/ex-ohp.webp',
  'barbell press':         'img/ex-press.webp',
  'incline press':         'img/ex-press.webp',
  'lateral raises':        'img/ex-power.webp',
  'face pulls':            'img/ex-row.webp',
  'rowing':                'img/ex-row.webp',
  'squat rack':            'img/ex-lean.webp',
  'tricep':                'img/ex-power.webp',
};

// Image placeholder — if `label` matches a known food keyword OR a `src` is provided,
// renders a real image. Otherwise falls back to a striped placeholder.
function ImgPlaceholder({ label, height = 160, t, dark, accent, src }) {
  const resolved = src || (label && FOOD_IMG[String(label).toLowerCase()]);
  if (resolved) {
    return (
      <div style={{
        height, borderRadius: 14, position: 'relative', overflow: 'hidden',
        background: dark ? '#1a1a1c' : '#E8DFD2',
      }}>
        <img src={resolved} alt={label || ''} loading="lazy"
          style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }}/>
        {/* The unresolved branch below carries this scrim so its white overlay text
            stays legible. Real images need it just as much, and on Jaz's bright
            coral backdrop they need it more. */}
        <div style={{
          position: 'absolute', inset: 0, pointerEvents: 'none',
          background: 'linear-gradient(180deg, transparent 42%, rgba(0,0,0,0.52) 100%)',
        }}/>
      </div>
    );
  }
  return (
    <div style={{
      height, borderRadius: 14, position: 'relative', overflow: 'hidden',
      background: `repeating-linear-gradient(135deg, ${dark ? '#222' : '#E8DFD2'} 0 8px, ${dark ? '#1a1a1c' : '#DDD2C0'} 8px 16px)`,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
    }}>
      <div style={{
        position: 'absolute', inset: 0,
        background: `linear-gradient(180deg, transparent 40%, rgba(0,0,0,0.55) 100%)`,
      }}/>
      <div style={{
        fontFamily: 'ui-monospace, SFMono-Regular, monospace',
        fontSize: 11, color: dark ? 'rgba(255,255,255,0.7)' : 'rgba(0,0,0,0.55)',
        background: dark ? 'rgba(0,0,0,0.4)' : 'rgba(255,255,255,0.7)',
        padding: '4px 8px', borderRadius: 4, position: 'relative', zIndex: 1,
      }}>{label}</div>
    </div>
  );
}

Object.assign(window, { Card, PillToggle, PreviewChrome, TabBar, FAB, ContentHeader, CoachSheet, ImgPlaceholder });
