// VYB LIFE — UI Primitives

const C = {
  bg: 'var(--c-bg)',
  bgDeep: 'var(--c-bgDeep)',
  card: 'var(--c-card)',
  cardEl: 'var(--c-cardEl)',
  border: 'var(--c-border)',
  borderMid: 'var(--c-borderMid)',
  borderStrong: 'var(--c-borderStrong)',
  sand: 'var(--c-sand)',
  sandLight: 'var(--c-sandLight)',
  sandFaint: 'var(--c-sandFaint)',
  sandGlow: 'var(--c-sandGlow)',
  sage: 'var(--c-sage)',
  sageLight: 'var(--c-sageLight)',
  sageFaint: 'var(--c-sageFaint)',
  clay: 'var(--c-clay)',
  clayFaint: 'var(--c-clayFaint)',
  textPrimary: 'var(--c-textPrimary)',
  textSecondary: 'var(--c-textSecondary)',
  textMuted: 'var(--c-textMuted)',
  textFaint: 'var(--c-textFaint)',
};

// ─── Icon ──────────────────────────────────────────────────────
const Icon = ({ name, size=16, color='currentColor', sw=1.5 }) => {
  const ref = React.useRef(null);
  React.useEffect(() => {
    if (!window.lucide || !ref.current) return;
    ref.current.innerHTML = '';
    const i = document.createElement('i');
    i.setAttribute('data-lucide', name);
    ref.current.appendChild(i);
    try { window.lucide.createIcons({ attrs: { 'stroke-width': String(sw), stroke: color, width: String(size), height: String(size), fill: 'none' }, nodes: [i] }); } catch(e) {}
    const svg = ref.current.querySelector('svg');
    if (svg) { svg.setAttribute('width', size); svg.setAttribute('height', size); svg.style.display = 'block'; }
  }, [name, size, color]);
  return <span ref={ref} style={{display:'inline-flex',alignItems:'center',flexShrink:0}} />;
};

// ─── Ring ──────────────────────────────────────────────────────
const Ring = ({ pct=0, size=64, stroke=4, color=C.sand, bg='rgba(250,250,248,0.07)', children }) => {
  const r = (size - stroke) / 2;
  const circ = 2 * Math.PI * r;
  return (
    <div style={{position:'relative',width:size,height:size,flexShrink:0}}>
      <svg width={size} height={size} style={{transform:'rotate(-90deg)'}}>
        <circle cx={size/2} cy={size/2} r={r} fill="none" stroke={bg} strokeWidth={stroke}/>
        <circle cx={size/2} cy={size/2} r={r} fill="none" stroke={color} strokeWidth={stroke}
          strokeDasharray={circ} strokeDashoffset={circ*(1-pct/100)} strokeLinecap="round"
          style={{transition:'stroke-dashoffset 0.6s cubic-bezier(0.16,1,0.3,1)'}}/>
      </svg>
      <div style={{position:'absolute',inset:0,display:'flex',alignItems:'center',justifyContent:'center'}}>
        {children}
      </div>
    </div>
  );
};

// ─── Card ──────────────────────────────────────────────────────
const Card = ({ children, style={}, onClick, hoverable, className }) => {
  const [h, setH] = React.useState(false);
  return (
    <div onClick={onClick} className={`vyb-card${className ? ' ' + className : ''}`}
      onMouseEnter={()=>hoverable&&setH(true)} onMouseLeave={()=>hoverable&&setH(false)}
      style={{background:C.card,border:`1px solid ${h?C.borderMid:C.border}`,borderRadius:16,padding:24,
        cursor:onClick?'pointer':'default',transition:'border-color 0.2s',...style}}>
      {children}
    </div>
  );
};

// ─── Label ─────────────────────────────────────────────────────
const Label = ({ children, color=C.textFaint, mb=12 }) => (
  <div style={{fontSize:10,fontWeight:700,letterSpacing:'0.2em',textTransform:'uppercase',color,marginBottom:mb}}>{children}</div>
);

// ─── Title ─────────────────────────────────────────────────────
const Title = ({ children, size=18, mb=20 }) => (
  <div style={{fontSize:size,fontWeight:800,fontStyle:'italic',color:C.textPrimary,letterSpacing:'-0.01em',textTransform:'uppercase',marginBottom:mb,lineHeight:1}}>
    {children}
  </div>
);

// ─── Button ────────────────────────────────────────────────────
const Button = ({ children, onClick, icon, variant='primary', size='md', style={} }) => {
  const [h, setH] = React.useState(false);
  const sizes = { sm:'6px 12px', md:'9px 16px', lg:'12px 20px' };
  const fontSizes = { sm:10, md:11, lg:12 };
  const variants = {
    primary: { bg:h?C.sandLight:C.sand, color:C.bg, border:'transparent' },
    ghost: { bg:h?'rgba(250,250,248,0.05)':'transparent', color:C.textSecondary, border:C.border },
    danger: { bg:h?'rgba(184,100,60,0.18)':'transparent', color:h?'#D0825A':C.textMuted, border:C.border },
  };
  const v = variants[variant];
  return (
    <button onClick={onClick} onMouseEnter={()=>setH(true)} onMouseLeave={()=>setH(false)}
      style={{padding:sizes[size],background:v.bg,color:v.color,border:`1px solid ${v.border}`,borderRadius:8,
        fontSize:fontSizes[size],fontWeight:600,letterSpacing:'0.12em',textTransform:'uppercase',
        fontFamily:'Montserrat,sans-serif',cursor:'pointer',display:'inline-flex',alignItems:'center',gap:6,transition:'all 0.2s',...style}}>
      {icon && <Icon name={icon} size={fontSizes[size]+2} color={v.color} sw={2}/>}
      {children}
    </button>
  );
};

// ─── IconButton ────────────────────────────────────────────────
// variant: 'default' (subtle ghost) | 'danger' (warm clay tint on hover)
const IconButton = ({ icon, onClick, color, size=14, title, variant='default', ariaLabel }) => {
  const [h, setH] = React.useState(false);
  const baseColor = color || (variant === 'danger' ? C.textMuted : C.textMuted);
  const hoverColor = variant === 'danger' ? '#D0825A' : C.textPrimary;
  const hoverBg = variant === 'danger' ? 'rgba(184,100,60,0.12)' : 'rgba(250,250,248,0.05)';
  return (
    <button title={title} aria-label={ariaLabel || title} onClick={onClick}
      onMouseEnter={()=>setH(true)} onMouseLeave={()=>setH(false)}
      className="vyb-card-action-btn"
      style={{width:30,height:30,borderRadius:8,background:h?hoverBg:'transparent',
        border:'none',cursor:'pointer',display:'inline-grid',placeItems:'center',
        opacity: h ? 1 : 0.72, transition:'all 0.18s ease-out', padding:0,
        WebkitTapHighlightColor:'transparent'}}>
      <Icon name={icon} size={size} color={h?hoverColor:baseColor} />
    </button>
  );
};

// ─── CardActions ───────────────────────────────────────────────
// Standard footer wrapper for card action icons. Groups them tight,
// anchors bottom-right, gives consistent breathing room.
const CardActions = ({ children, align='end', gap=6, mt='auto', pt=14, style={} }) => (
  <div className="vyb-card-actions" style={{
    display:'flex', alignItems:'center',
    justifyContent: align==='end'?'flex-end':align==='start'?'flex-start':'center',
    gap, marginTop: mt, paddingTop: pt, ...style,
  }}>{children}</div>
);

// ─── Input ─────────────────────────────────────────────────────
const Input = React.forwardRef(({ value, onChange, onKeyDown, placeholder, style={}, type='text', autoFocus }, ref) => (
  <input ref={ref} type={type} value={value} onChange={onChange} onKeyDown={onKeyDown} placeholder={placeholder} autoFocus={autoFocus}
    style={{width:'100%',background:'rgba(250,250,248,0.03)',border:`1px solid ${C.border}`,borderRadius:8,
      padding:'10px 14px',fontSize:12,color:C.textPrimary,outline:'none',fontFamily:'Montserrat,sans-serif',
      transition:'all 0.2s',...style}}
    onFocus={e=>{e.target.style.borderColor=C.sand;e.target.style.background='rgba(250,250,248,0.05)';}}
    onBlur={e=>{e.target.style.borderColor=C.border;e.target.style.background='rgba(250,250,248,0.03)';}}
  />
));

// ─── Modal ─────────────────────────────────────────────────────
const Modal = ({ open, onClose, title, children, width=440 }) => {
  const [isMobile, setIsMobile] = React.useState(() => typeof window!=='undefined' && window.matchMedia('(max-width: 768px)').matches);
  React.useEffect(() => {
    if (!open) return;
    const mq = window.matchMedia('(max-width: 768px)');
    const onChange = () => setIsMobile(mq.matches);
    mq.addEventListener?.('change', onChange);
    const prevOverflow = document.body.style.overflow;
    const prevPaddingRight = document.body.style.paddingRight;
    document.body.style.overflow = 'hidden';
    return () => {
      mq.removeEventListener?.('change', onChange);
      document.body.style.overflow = prevOverflow;
      document.body.style.paddingRight = prevPaddingRight;
    };
  }, [open]);
  if (!open) return null;
  const overlay = (
    <div onClick={onClose} className="vyb-modal-shell"
      style={{position:'fixed',inset:0,background:'rgba(7,6,5,0.7)',backdropFilter:'blur(12px)',WebkitBackdropFilter:'blur(12px)',
        zIndex:1000,display:'flex',alignItems:'center',justifyContent:'center',
        padding: isMobile ? '12px 12px calc(12px + env(safe-area-inset-bottom))' : 20,
        animation:'fadeIn 0.2s ease-out'}}>
      <div onClick={e=>e.stopPropagation()} className="vyb-modal-inner"
        style={{
          width: isMobile ? '100%' : width,
          maxWidth: isMobile ? 'calc(100vw - 24px)' : '100%',
          maxHeight: isMobile ? 'calc(100dvh - 24px - env(safe-area-inset-bottom))' : 'calc(100vh - 40px)',
          background:C.card,border:`1px solid ${C.borderMid}`,borderRadius:16,
          boxShadow:'0 32px 80px rgba(0,0,0,0.6)',animation:'slideUp 0.25s cubic-bezier(0.16,1,0.3,1)',
          display:'flex',flexDirection:'column',overflow:'hidden'}}>
        {title && <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',
          padding: isMobile ? '14px 16px 10px' : '24px 28px 16px', flexShrink:0}}>
          <Title mb={0} size={isMobile?15:16}>{title}</Title>
          <IconButton icon="x" onClick={onClose} color={C.textMuted} />
        </div>}
        <div style={{flex:1,minHeight:0,overflowY:'auto',WebkitOverflowScrolling:'touch',
          padding: isMobile ? (title ? '0 16px 16px' : '16px') : (title ? '0 28px 28px' : 28)}}>
          {children}
        </div>
      </div>
    </div>
  );
  return (typeof document!=='undefined' && document.body)
    ? ReactDOM.createPortal(overlay, document.body)
    : overlay;
};

// ─── Empty ─────────────────────────────────────────────────────
const Empty = ({ icon='sparkles', title, sub, action }) => (
  <div style={{padding:'40px 20px',textAlign:'center'}}>
    <div style={{width:48,height:48,borderRadius:999,background:C.sandFaint,display:'flex',alignItems:'center',justifyContent:'center',margin:'0 auto 16px'}}>
      <Icon name={icon} size={20} color={C.sand} />
    </div>
    <div style={{fontSize:13,fontWeight:600,color:C.textPrimary,marginBottom:6}}>{title}</div>
    {sub && <div style={{fontSize:11,fontWeight:300,color:C.textMuted,lineHeight:1.6,maxWidth:260,margin:'0 auto 16px'}}>{sub}</div>}
    {action}
  </div>
);

Object.assign(window, { C, Icon, Ring, Card, Label, Title, Button, IconButton, CardActions, Input, Modal, Empty });
