import React from 'react';
import { useShadeContext } from '../ShadeProvider.js';

/**
 * Common widget shell — provides consistent border, padding, header.
 * All widgets render inside one of these for visual consistency.
 */
export interface WidgetShellProps {
  title: string;
  icon?: React.ReactNode;
  status?: React.ReactNode;
  children: React.ReactNode;
  className?: string;
}

export function WidgetShell({ title, icon, status, children, className }: WidgetShellProps): React.ReactElement {
  const { theme } = useShadeContext();
  return (
    <div
      className={`shade-widget ${className ?? ''}`}
      style={{
        background: theme.bgElevated,
        border: `1px solid ${theme.border}`,
        borderRadius: theme.radius,
        padding: 16,
        fontFamily: theme.font,
        color: theme.text,
        boxShadow: theme.shadow,
      }}
    >
      <div
        style={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          marginBottom: 12,
          gap: 8,
        }}
      >
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, minWidth: 0 }}>
          {icon}
          <span
            style={{
              fontSize: 11,
              fontWeight: 600,
              letterSpacing: '0.06em',
              textTransform: 'uppercase',
              color: theme.accent,
              whiteSpace: 'nowrap',
              overflow: 'hidden',
              textOverflow: 'ellipsis',
            }}
          >
            {title}
          </span>
        </div>
        {status}
      </div>
      {children}
    </div>
  );
}

export function formatRelative(ts: number | null): string {
  if (!ts) return 'never';
  const diff = Date.now() - ts;
  if (diff < 1000) return 'just now';
  if (diff < 60_000) return `${Math.floor(diff / 1000)}s ago`;
  if (diff < 3600_000) return `${Math.floor(diff / 60_000)}m ago`;
  if (diff < 86400_000) return `${Math.floor(diff / 3600_000)}h ago`;
  return `${Math.floor(diff / 86400_000)}d ago`;
}

export function StatusDot({ color }: { color: string }): React.ReactElement {
  return (
    <span
      style={{
        display: 'inline-block',
        width: 8,
        height: 8,
        borderRadius: '50%',
        background: color,
      }}
    />
  );
}

export function ConnectionStatus({ connected }: { connected: boolean }): React.ReactElement {
  const { theme } = useShadeContext();
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 11, color: theme.textMuted }}>
      <StatusDot color={connected ? theme.success : theme.danger} />
      {connected ? 'live' : 'offline'}
    </div>
  );
}
