// Shell components: status bar, tab bar, sheet, card primitives.

const SCREEN_W = 412, SCREEN_H = 892;

function StatusBar({ dark }) {
  const t = T(dark);
  return (
    <div style={{
      height: 44, padding: '0 26px', display: 'flex',
      justifyContent: 'space-between', alignItems: 'center',
      fontFamily: TOK.fontText, fontSize: 15, fontWeight: 700, color: t.ink,
    }}>
      <div>9:41</div>
      <div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
        <svg width="17" height="11" viewBox="0 0 17 11" fill={t.ink}>
          <rect x="0" y="7" width="3" height="4" rx="0.5"/>
          <rect x="4.5" y="5" width="3" height="6" rx="0.5"/>
          <rect x="9" y="2.5" width="3" height="8.5" rx="0.5"/>
          <rect x="13.5" y="0" width="3" height="11" rx="0.5"/>
        </svg>
        <svg width="25" height="12" viewBox="0 0 25 12">
          <rect x="0.5" y="0.5" width="21" height="11" rx="2.5" fill="none" stroke={t.ink} strokeOpacity="0.4"/>
          <rect x="2" y="2" width="18" height="8" rx="1.5" fill={t.ink}/>
          <path d="M23 4v4c.6-.3 1-1 1-2s-.4-1.7-1-2z" fill={t.ink} fillOpacity="0.5"/>
        </svg>
      </div>
    </div>
  );
}

function TabBar({ active, onChange, dark }) {
  const t = T(dark);
  const tabs = [
    { id: 'home', icon: ICONS.home },
    { id: 'analytics', icon: ICONS.chart },
    { id: 'add', icon: ICONS.plus },
    { id: 'goal', icon: ICONS.target },
    { id: 'me', icon: ICONS.user },
  ];
  return (
    <div style={{
      position: 'absolute', left: 14, right: 14, bottom: 18,
      height: 64, borderRadius: 32,
      background: dark ? 'rgba(30,28,23,0.92)' : 'rgba(255,255,255,0.92)',
      backdropFilter: 'blur(20px)',
      WebkitBackdropFilter: 'blur(20px)',
      border: `1px solid ${t.line}`,
      boxShadow: dark ? '0 12px 40px rgba(0,0,0,0.5)' : '0 12px 32px rgba(30,20,5,0.10)',
      display: 'flex', alignItems: 'center', zIndex: 10,
    }}>
      {tabs.map(tab => {
        const isAdd = tab.id === 'add';
        const isActive = tab.id === active;
        if (isAdd) return (
          <div key={tab.id} style={{ flex: 1, display: 'flex', justifyContent: 'center' }}>
            <button onClick={() => onChange('add')} style={{
              width: 50, height: 50, borderRadius: 25, border: 'none', cursor: 'pointer',
              background: t.accent, color: t.accentInk,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              boxShadow: `0 8px 20px ${t.accent}55`,
              transition: 'transform .15s',
            }} onMouseDown={e => e.currentTarget.style.transform = 'scale(0.94)'}
               onMouseUp={e => e.currentTarget.style.transform = ''}
               onMouseLeave={e => e.currentTarget.style.transform = ''}>
              <Icon d={tab.icon} size={22} stroke={t.accentInk} sw={2.4} />
            </button>
          </div>
        );
        return (
          <button key={tab.id} onClick={() => onChange(tab.id)} style={{
            flex: 1, border: 'none', cursor: 'pointer', background: 'transparent',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            height: '100%', padding: 0,
          }}>
            <div style={{
              width: 40, height: 40, borderRadius: 14,
              background: isActive ? t.accentSoft : 'transparent',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              transition: 'background .2s',
            }}>
              <Icon d={tab.icon} size={22} stroke={isActive ? t.accent : t.muted} sw={1.9} />
            </div>
          </button>
        );
      })}
    </div>
  );
}

function HomeIndicator({ dark }) {
  return (
    <div style={{
      position: 'absolute', bottom: 0, left: 0, right: 0, height: 34,
      display: 'flex', justifyContent: 'center', alignItems: 'flex-end', paddingBottom: 8,
      pointerEvents: 'none', zIndex: 20,
    }}>
      <div style={{
        width: 138, height: 5, borderRadius: 100,
        background: dark ? 'rgba(255,241,234,0.7)' : 'rgba(26,24,20,0.3)',
      }} />
    </div>
  );
}

function PageHeader({ title, subtitle, dark, leading, trailing, large }) {
  const t = T(dark);
  return (
    <div style={{ padding: '8px 20px 16px' }}>
      <div style={{ display: 'flex', alignItems: 'center', minHeight: 32, marginBottom: large ? 8 : 4 }}>
        {leading || <div style={{ width: 36 }} />}
        <div style={{ flex: 1 }} />
        {trailing}
      </div>
      {subtitle && (
        <div style={{ fontSize: 13, color: t.muted, fontWeight: 600, marginBottom: 4 }}>{subtitle}</div>
      )}
      <div style={{
        fontFamily: TOK.fontDisplay, fontSize: large ? 32 : 28, fontWeight: 700,
        letterSpacing: -0.6, color: t.ink, lineHeight: 1.1,
      }}>{title}</div>
    </div>
  );
}

function Card({ children, dark, pad = 18, radius, style = {}, onClick, flat }) {
  const t = T(dark);
  return (
    <div onClick={onClick} style={{
      background: t.surface,
      borderRadius: radius ?? TOK.r.lg,
      padding: pad,
      boxShadow: flat || dark ? 'none' : '0 1px 2px rgba(40,30,15,0.04), 0 6px 24px rgba(40,30,15,0.05)',
      border: dark ? `1px solid ${t.line}` : 'none',
      cursor: onClick ? 'pointer' : undefined,
      ...style,
    }}>{children}</div>
  );
}

function IconCircle({ icon, color, size = 40, bg, fg, dark }) {
  const t = T(dark);
  const _bg = bg ?? (color ? color + '22' : t.surfaceAlt);
  const _fg = fg ?? color ?? t.ink;
  return (
    <div style={{
      width: size, height: size, borderRadius: size * 0.32,
      background: _bg, color: _fg,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      flexShrink: 0,
    }}>
      <Icon d={ICONS[icon] || icon} size={Math.round(size * 0.5)} stroke={_fg} sw={1.9} />
    </div>
  );
}

function Sheet({ open, onClose, dark, children, title, height }) {
  const t = T(dark);
  if (!open) return null;
  return (
    <div onClick={onClose} style={{
      position: 'absolute', inset: 0, zIndex: 100,
      background: 'rgba(0,0,0,0.4)', backdropFilter: 'blur(4px)',
      display: 'flex', alignItems: 'flex-end',
      animation: 'fadeIn .2s ease',
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        background: t.bg, width: '100%',
        borderRadius: '28px 28px 0 0', padding: '14px 20px 30px',
        maxHeight: height || '90%', overflowY: 'auto',
        animation: 'slideUp .25s ease',
      }}>
        <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 6 }}>
          <div style={{ width: 36, height: 5, borderRadius: 3, background: t.lineStrong }} />
        </div>
        {title && (
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '8px 0 12px' }}>
            <div style={{ fontSize: 18, fontWeight: 700, color: t.ink }}>{title}</div>
            <button onClick={onClose} style={{ border: 'none', background: 'transparent', cursor: 'pointer', padding: 4 }}>
              <Icon d={ICONS.x} size={20} stroke={t.muted} />
            </button>
          </div>
        )}
        {children}
      </div>
    </div>
  );
}

// CSS keyframes (inject once)
if (typeof document !== 'undefined' && !document.getElementById('money-anim')) {
  const s = document.createElement('style');
  s.id = 'money-anim';
  s.textContent = `
    @keyframes fadeIn { from{opacity:0} to{opacity:1} }
    @keyframes slideUp { from{transform:translateY(40px); opacity:0} to{transform:translateY(0); opacity:1} }
    @keyframes screenIn { from{opacity:0; transform:translateY(8px)} to{opacity:1; transform:translateY(0)} }
    @keyframes tabFade { from{opacity:0.7} to{opacity:1} }
    @keyframes pulse { 0%{transform:scale(1); opacity:.5} 50%{transform:scale(1.15); opacity:.2} 100%{transform:scale(1); opacity:.5} }
  `;
  document.head.appendChild(s);
}

// Screen container with consistent padding & subtle entrance
function Screen({ dark, children, scroll = true, padTop = 0, padBottom = 100 }) {
  const t = T(dark);
  return (
    <div key={Math.random()} style={{
      position: 'absolute', inset: 0, top: 44, paddingBottom: padBottom, paddingTop: padTop,
      overflowY: scroll ? 'auto' : 'hidden',
      animation: 'screenIn .22s ease',
    }}>{children}</div>
  );
}

function Pill({ children, dark, active, color, onClick, style = {} }) {
  const t = T(dark);
  const a = color || t.accent;
  return (
    <button onClick={onClick} style={{
      padding: '7px 14px', borderRadius: 999,
      background: active ? a : t.surfaceAlt,
      color: active ? '#fff' : t.inkSoft,
      border: 'none', cursor: 'pointer',
      fontFamily: 'inherit', fontSize: 13, fontWeight: 600,
      transition: 'background .15s, color .15s',
      ...style,
    }}>{children}</button>
  );
}

function Segmented({ options, value, onChange, dark }) {
  const t = T(dark);
  return (
    <div style={{
      display: 'flex', background: t.surfaceAlt, padding: 4, borderRadius: 12,
    }}>
      {options.map(o => {
        const isOn = o.value === value;
        return (
          <button key={o.value} onClick={() => onChange(o.value)} style={{
            flex: 1, padding: '8px 0', borderRadius: 9, border: 'none', cursor: 'pointer',
            background: isOn ? t.surface : 'transparent', color: isOn ? t.ink : t.muted,
            fontFamily: 'inherit', fontSize: 13, fontWeight: 600,
            boxShadow: isOn ? '0 1px 2px rgba(0,0,0,0.08)' : 'none',
            transition: 'background .15s',
          }}>{o.label}</button>
        );
      })}
    </div>
  );
}

function Btn({ children, dark, primary, secondary, onClick, style = {}, full, icon }) {
  const t = T(dark);
  const base = {
    padding: '14px 18px', borderRadius: 16, border: 'none', cursor: 'pointer',
    fontFamily: 'inherit', fontSize: 15, fontWeight: 700,
    display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
    transition: 'transform .12s, opacity .15s',
    width: full ? '100%' : undefined,
    ...style,
  };
  const variants = {
    primary: { background: t.accent, color: t.accentInk, boxShadow: `0 8px 20px ${t.accent}40` },
    secondary: { background: t.surfaceAlt, color: t.ink },
  };
  const v = primary ? variants.primary : secondary ? variants.secondary : variants.primary;
  return (
    <button onClick={onClick} style={{ ...base, ...v }}
      onMouseDown={e => e.currentTarget.style.transform = 'scale(0.97)'}
      onMouseUp={e => e.currentTarget.style.transform = ''}
      onMouseLeave={e => e.currentTarget.style.transform = ''}
    >
      {icon && <Icon d={ICONS[icon] || icon} size={18} stroke="currentColor" sw={2} />}
      {children}
    </button>
  );
}

function ListRow({ icon, color, title, sub, value, valueSub, right, dark, last, onClick, valueColor }) {
  const t = T(dark);
  return (
    <div onClick={onClick} style={{
      padding: '13px 16px', display: 'flex', alignItems: 'center', gap: 12,
      borderBottom: last ? 'none' : `1px solid ${t.line}`,
      cursor: onClick ? 'pointer' : undefined,
    }}>
      {icon && <IconCircle icon={icon} color={color} size={38} dark={dark} />}
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 15, fontWeight: 600, color: t.ink, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{title}</div>
        {sub && <div style={{ fontSize: 12, color: t.muted, marginTop: 2, fontWeight: 500 }}>{sub}</div>}
      </div>
      {right || (value !== undefined && (
        <div style={{ textAlign: 'right', flexShrink: 0 }}>
          <div style={{ fontSize: 15, fontWeight: 700, color: valueColor || t.ink, fontVariantNumeric: 'tabular-nums' }}>{value}</div>
          {valueSub && <div style={{ fontSize: 11, color: t.muted, marginTop: 2 }}>{valueSub}</div>}
        </div>
      ))}
    </div>
  );
}

function SectionLabel({ children, dark, action, onAction }) {
  const t = T(dark);
  return (
    <div style={{ padding: '20px 24px 10px', display: 'flex', alignItems: 'baseline', justifyContent: 'space-between' }}>
      <div style={{ fontFamily: TOK.fontDisplay, fontSize: 18, fontWeight: 700, color: t.ink, letterSpacing: -0.3 }}>{children}</div>
      {action && <button onClick={onAction} style={{ background: 'transparent', border: 'none', cursor: 'pointer', color: t.accent, fontFamily: 'inherit', fontSize: 13, fontWeight: 700 }}>{action}</button>}
    </div>
  );
}

Object.assign(window, {
  SCREEN_W, SCREEN_H, StatusBar, TabBar, HomeIndicator, PageHeader, Card, IconCircle, Sheet,
  Screen, Pill, Segmented, Btn, ListRow, SectionLabel,
});
