/* Shared UI primitives — themed by the current direction */

const Card = ({ children, style, hover, ...rest }) => {
  const t = useTheme();
  const isBloom = t.name === 'BLOOM';
  return (
    <div style={{
      background: t.surface,
      border: isBloom ? `1.5px solid ${t.border}` : `1px solid ${t.border}`,
      borderRadius: t.radiusLg,
      boxShadow: isBloom ? '4px 4px 0 0 #14131A' : '0 1px 0 rgba(255,255,255,0.04) inset',
      ...style,
    }} {...rest}>{children}</div>
  );
};

const Pill = ({ children, color, soft, style }) => {
  const t = useTheme();
  const isBloom = t.name === 'BLOOM';
  return (
    <span style={{
      display: 'inline-flex',
      alignItems: 'center',
      gap: 6,
      padding: '4px 10px',
      borderRadius: t.radiusPill,
      background: soft || t.surfaceAlt,
      color: color || t.text,
      fontSize: 12,
      fontWeight: 600,
      fontFamily: t.fontBody,
      letterSpacing: '-0.01em',
      border: isBloom ? `1.5px solid ${t.border}` : '1px solid rgba(255,255,255,0.06)',
      whiteSpace: 'nowrap',
      ...style,
    }}>{children}</span>
  );
};

const Btn = ({ children, variant = 'primary', size = 'md', icon, style, ...rest }) => {
  const t = useTheme();
  const isBloom = t.name === 'BLOOM';
  const sizes = {
    sm: { padding: '6px 10px', fontSize: 12, gap: 6 },
    md: { padding: '9px 14px', fontSize: 13, gap: 8 },
    lg: { padding: '12px 18px', fontSize: 14, gap: 10 },
  }[size];
  const variants = {
    primary: {
      background: t.primary,
      color: isBloom ? '#FFFBF4' : '#fff',
      border: isBloom ? `1.5px solid ${t.border}` : '1px solid rgba(255,255,255,0.1)',
      boxShadow: isBloom ? '3px 3px 0 0 #14131A' : '0 4px 16px -4px rgba(91,141,239,0.45)',
    },
    secondary: {
      background: isBloom ? t.surface : t.surfaceAlt,
      color: t.text,
      border: isBloom ? `1.5px solid ${t.border}` : `1px solid ${t.border}`,
      boxShadow: isBloom ? '3px 3px 0 0 #14131A' : 'none',
    },
    ghost: { background: 'transparent', color: t.text, border: '1px solid transparent' },
    green: {
      background: t.green, color: isBloom ? '#0a2a1f' : '#fff',
      border: isBloom ? `1.5px solid ${t.border}` : '1px solid rgba(255,255,255,0.1)',
      boxShadow: isBloom ? '3px 3px 0 0 #14131A' : '0 4px 16px -4px rgba(16,185,129,0.45)',
    },
  }[variant];
  return (
    <button style={{
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      borderRadius: t.radiusMd, fontWeight: 600, fontFamily: t.fontBody,
      letterSpacing: '-0.01em', cursor: 'pointer', transition: 'transform 0.1s, filter 0.1s',
      ...sizes, ...variants, ...style,
    }}
    onMouseDown={(e) => e.currentTarget.style.transform = isBloom ? 'translate(2px, 2px)' : 'scale(0.98)'}
    onMouseUp={(e) => e.currentTarget.style.transform = ''}
    onMouseLeave={(e) => e.currentTarget.style.transform = ''}
    {...rest}>
      {icon}{children}
    </button>
  );
};

const Avatar = ({ name, color, size = 36, ai }) => {
  const t = useTheme();
  const isBloom = t.name === 'BLOOM';
  return (
    <div style={{
      width: size, height: size, borderRadius: isBloom ? size * 0.35 : '50%',
      background: color || t.primary, color: '#fff',
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      fontWeight: 700, fontSize: size * 0.4,
      border: isBloom ? `1.5px solid ${t.border}` : 'none',
      fontFamily: t.fontDisplay,
      position: 'relative', flexShrink: 0,
    }}>
      {name}
      {ai && (
        <span style={{
          position: 'absolute', bottom: -2, right: -2, width: size * 0.4, height: size * 0.4,
          borderRadius: '50%', background: t.green, border: `2px solid ${t.surface}`,
          display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: size * 0.22,
        }}>
          <Icons.Sparkles size={size * 0.24} stroke={isBloom ? '#0a2a1f' : '#fff'} />
        </span>
      )}
    </div>
  );
};

const ScoreRing = ({ value, size = 44, label, color }) => {
  const t = useTheme();
  const isBloom = t.name === 'BLOOM';
  const r = (size - 6) / 2;
  const c = 2 * Math.PI * r;
  const safeValue = Number(value) || 0;
  const offset = c - (safeValue / 100) * c;
  const ringColor = color || (safeValue > 75 ? t.green : safeValue > 50 ? t.orange : t.red);
  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={isBloom ? 'rgba(20,19,26,0.1)' : 'rgba(255,255,255,0.08)'} strokeWidth="3"/>
        <circle cx={size/2} cy={size/2} r={r} fill="none" stroke={ringColor}
          strokeWidth="3" strokeDasharray={c} strokeDashoffset={offset} strokeLinecap="round"/>
      </svg>
      <div style={{
        position: 'absolute', inset: 0, display: 'flex', alignItems: 'center',
        justifyContent: 'center', fontFamily: t.fontMono, fontSize: size * 0.32,
        fontWeight: 700, color: t.text, letterSpacing: '-0.02em',
      }}>{value}</div>
    </div>
  );
};

const Sparkline = ({ values, color, height = 32, width = 80, fill }) => {
  const t = useTheme();
  if (!values || values.length === 0) return null;
  const max = Math.max(...values);
  const min = Math.min(...values);
  const range = max - min || 1;
  const points = values.map((v, i) => {
    const x = (i / (values.length - 1)) * width;
    const y = height - ((v - min) / range) * height;
    return `${x},${y}`;
  }).join(' ');
  const areaPoints = `0,${height} ${points} ${width},${height}`;
  return (
    <svg width={width} height={height} style={{ overflow: 'visible' }}>
      {fill && <polygon points={areaPoints} fill={color} opacity={0.15} />}
      <polyline points={points} fill="none" stroke={color || t.primary} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  );
};

const SectionTitle = ({ children, sub, action }) => {
  const t = useTheme();
  return (
    <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginBottom: 16, gap: 16 }}>
      <div>
        <h2 style={{ margin: 0, fontFamily: t.fontDisplay, fontSize: 22, fontWeight: 700, letterSpacing: '-0.02em', color: t.text }}>{children}</h2>
        {sub && <div style={{ marginTop: 4, fontSize: 13, color: t.textMuted }}>{sub}</div>}
      </div>
      {action}
    </div>
  );
};

const Tab = ({ active, children, onClick, count, color }) => {
  const t = useTheme();
  const isBloom = t.name === 'BLOOM';
  return (
    <button onClick={onClick} style={{
      padding: '8px 14px', borderRadius: t.radiusMd,
      background: active ? (isBloom ? t.text : t.surfaceAlt) : 'transparent',
      color: active ? (isBloom ? t.surface : t.text) : t.textMuted,
      border: isBloom ? `1.5px solid ${active ? t.border : 'transparent'}` : '1px solid transparent',
      fontFamily: t.fontBody, fontSize: 13, fontWeight: 600,
      display: 'inline-flex', alignItems: 'center', gap: 8, letterSpacing: '-0.01em',
    }}>
      {children}
      {count != null && (
        <span style={{
          padding: '1px 7px', borderRadius: 99, fontSize: 11, fontWeight: 700,
          background: color || (active ? (isBloom ? t.surface : t.primarySoft) : 'rgba(255,255,255,0.06)'),
          color: color ? '#fff' : (active ? (isBloom ? t.text : t.primary) : t.textMuted),
        }}>{count}</span>
      )}
    </button>
  );
};

const Status = ({ ok, label, dot, color }) => {
  const t = useTheme();
  return (
    <div style={{ display: 'inline-flex', alignItems: 'center', gap: 7, fontSize: 12, color: t.textMuted, fontFamily: t.fontMono }}>
      <span style={{
        width: 7, height: 7, borderRadius: '50%',
        background: color || (ok ? t.green : t.red),
        boxShadow: `0 0 0 3px ${color ? color + '22' : (ok ? t.greenSoft : 'rgba(248,113,113,0.18)')}`,
        animation: ok ? 'pulse 2s ease-in-out infinite' : 'none',
      }} />
      <span>{label}</span>
      <style>{`@keyframes pulse { 0%,100% { opacity: 1 } 50% { opacity: 0.5 } }`}</style>
    </div>
  );
};

const ToastContext = React.createContext();

const ToastProvider = ({ children }) => {
  const [toasts, setToasts] = React.useState([]);
  
  const showToast = React.useCallback((message, type = 'info') => {
    const id = Date.now() + Math.random();
    setToasts(prev => [...prev, { id, message, type }]);
    setTimeout(() => {
      setToasts(prev => prev.filter(t => t.id !== id));
    }, 4000);
  }, []);

  return (
    <ToastContext.Provider value={{ showToast }}>
      {children}
      <div style={{
        position: 'fixed', bottom: 20, right: 20, zIndex: 99999,
        display: 'flex', flexDirection: 'column', gap: 10,
        pointerEvents: 'none'
      }}>
        {toasts.map(t => (
          <div key={t.id} style={{
            background: '#14131A', color: '#fff', padding: '12px 18px',
            borderRadius: 10, fontSize: 13.5, fontWeight: 600,
            border: '1.5px solid rgba(255,255,255,0.1)',
            boxShadow: '4px 4px 0 0 rgba(0,0,0,0.8)',
            display: 'flex', alignItems: 'center', gap: 10,
            animation: 'slideIn 0.3s cubic-bezier(0.16, 1, 0.3, 1)'
          }}>
            <Icons.Check size={16} stroke="#5B8DEF" />
            {t.message}
          </div>
        ))}
      </div>
      <style>{`
        @keyframes slideIn {
          from { transform: translateX(100%); opacity: 0; }
          to { transform: translateX(0); opacity: 1; }
        }
      `}</style>
    </ToastContext.Provider>
  );
};

const useToast = () => React.useContext(ToastContext) || { showToast: () => alert("Toast not initialized") };

window.Card = Card;
// ── DIALOGS ────────────────────────────────────────────────────────────────
const DialogContext = React.createContext();

const DialogProvider = ({ children }) => {
  const t = useTheme();
  const isBloom = t.name === 'BLOOM';
  const [dialogs, setDialogs] = React.useState([]);

  const openDialog = React.useCallback((options) => {
    return new Promise((resolve) => {
      const id = Date.now() + Math.random();
      const close = (value) => {
        setDialogs(prev => prev.filter(d => d.id !== id));
        resolve(value);
      };
      setDialogs(prev => [...prev, { id, close, ...options }]);
    });
  }, []);

  const confirm = React.useCallback((message, options = {}) => openDialog({ type: 'confirm', message, ...options }), [openDialog]);
  const prompt = React.useCallback((message, defaultValue = '', options = {}) => openDialog({ type: 'prompt', message, defaultValue, ...options }), [openDialog]);
  const alert = React.useCallback((message, options = {}) => openDialog({ type: 'alert', message, ...options }), [openDialog]);

  return (
    <DialogContext.Provider value={{ confirm, prompt, alert }}>
      {children}
      {dialogs.length > 0 && (
        <div style={{
          position: 'fixed', inset: 0, zIndex: 100000,
          background: 'rgba(0, 0, 0, 0.6)', backdropFilter: 'blur(4px)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          animation: 'fadeIn 0.2s ease-out'
        }}>
          {dialogs.map(d => (
            <div key={d.id} style={{
              background: isBloom ? t.surface : t.surfaceAlt,
              border: isBloom ? `1.5px solid ${t.border}` : `1px solid ${t.border}`,
              borderRadius: t.radiusLg,
              padding: 24, width: '100%', maxWidth: 400,
              boxShadow: isBloom ? '6px 6px 0 0 #14131A' : '0 20px 40px -10px rgba(0,0,0,0.5)',
              display: 'flex', flexDirection: 'column', gap: 16,
              animation: 'scaleIn 0.2s cubic-bezier(0.16, 1, 0.3, 1)'
            }}>
              {d.title && <h3 style={{ margin: 0, fontSize: 18, fontFamily: t.fontDisplay, color: t.text }}>{d.title}</h3>}
              <div style={{ fontSize: 14, color: t.text, lineHeight: 1.5 }}>{d.message}</div>
              
              {d.type === 'prompt' && (
                <input 
                  autoFocus
                  type="text"
                  defaultValue={d.defaultValue}
                  onKeyDown={(e) => {
                    if (e.key === 'Enter') d.close(e.target.value);
                    if (e.key === 'Escape') d.close(null);
                  }}
                  onChange={(e) => { d._tempValue = e.target.value; }}
                  style={{
                    width: '100%', padding: '10px 14px',
                    background: isBloom ? t.bg : 'rgba(255,255,255,0.04)',
                    border: isBloom ? `1.5px solid ${t.border}` : `1px solid ${t.border}`,
                    borderRadius: t.radiusMd, color: t.text, fontSize: 14, outline: 'none',
                    fontFamily: t.fontBody
                  }}
                />
              )}

              <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end', marginTop: 8 }}>
                {d.type !== 'alert' && (
                  <Btn variant="ghost" onClick={() => d.close(null)}>{d.cancelText || 'Cancelar'}</Btn>
                )}
                <Btn variant="primary" onClick={() => {
                  if (d.type === 'prompt') d.close(d._tempValue !== undefined ? d._tempValue : d.defaultValue);
                  else d.close(true);
                }}>
                  {d.confirmText || 'OK'}
                </Btn>
              </div>
            </div>
          ))}
          <style>{`
            @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
            @keyframes scaleIn { from { transform: scale(0.95); opacity: 0; } to { transform: scale(1); opacity: 1; } }
          `}</style>
        </div>
      )}
    </DialogContext.Provider>
  );
};

const useDialog = () => React.useContext(DialogContext);

Object.assign(window, {
  Card, Pill, Btn, Avatar, ScoreRing, Sparkline, SectionTitle, Tab, Status,
  ToastProvider, useToast, DialogProvider, useDialog
});
