import React from 'react';
import { formatBytes, formatRelative } from '../utils/format.js';
import { flagFor } from '../utils/country.js';

function StatusBadge({ status }) {
  const map = {
    running:   { dot: 'success', text: 'Работает',  cls: '' },
    applying:  { dot: 'warning pulse', text: 'Применяем…', cls: '' },
    error:     { dot: 'danger',  text: 'Ошибка',    cls: '' },
    stopped:   { dot: '',        text: 'Остановлен', cls: '' },
    no_config: { dot: '',        text: 'Не настроен', cls: '' },
  };
  const cfg = map[status] || map.stopped;
  return (
    <span className="flex">
      <span className={`dot ${cfg.dot}`} />
      <strong>{cfg.text}</strong>
    </span>
  );
}

export function Topbar({ state, status, activeServer, dirty, onRestart, onTryApply }) {
  const userInfo = state?.userInfo;
  const traffic = userInfo
    ? `${formatBytes((userInfo.upload || 0) + (userInfo.download || 0))}${userInfo.total ? ' / ' + formatBytes(userInfo.total) : ''}`
    : null;

  const isClient = state?.mode === 'client';

  return (
    <header className="topbar">
      <div className="topbar-brand">
        <span className="logo-dot" />
        {state?.mode === 'client' ? 'VPN Client' : 'VPN Gateway'}
      </div>

      <div className="topbar-status">
        <StatusBadge status={status} />
        {activeServer && (
          <div className="status-text">
            <strong>
              {flagFor(activeServer)} {activeServer.tag}
            </strong>
            <small>
              {activeServer.server}:{activeServer.server_port}
              {state?.appliedAt ? ` · применено ${formatRelative(state.appliedAt)}` : ''}
            </small>
          </div>
        )}
        {!activeServer && (
          <small className="muted">Сервер не выбран</small>
        )}
        {traffic && <span className="badge neutral">{traffic}</span>}
      </div>

      <div className="topbar-actions">
        {!isClient && dirty && (
          <span className="badge warning">● Несохранённые изменения</span>
        )}
        {!isClient && state?.previousTag && (
          <button className="btn btn-ghost sm" onClick={onTryApply} title="Откатить">
            ↶ Откат
          </button>
        )}
        <button
          className="btn btn-secondary sm"
          onClick={onRestart}
          disabled={!state?.configExists}
          title="Перезапустить sing-box"
        >
          ↻ Перезапуск
        </button>
      </div>
    </header>
  );
}
