import { parseShineRootSegment } from './services/shine-routes.js';

const ROOT_PAGES = ['messages-list', 'channels-list', 'network-view', 'notifications-view', 'profile-view'];

export const PRE_AUTH_PAGES = [
  'start-view',
  'entry-settings-view',
  'register-view',
  'registration-payment-view',
  'registration-draft-keys-view',
  'registration-keys-view',
  'topup-view',
  'devnet-topup-view',
  'login-view',
  'login-camera-view',
  'login-other-device-view',
  'login-password-view',
  'key-storage-view',
];

export function getRoute() {
  const currentPath = String(window.location.pathname || '').trim();
  const raw = currentPath
    .replace(/^\/+/, '')
    .replace(/^index\.html$/i, '')
    .replace(/^index\.html\//i, '')
    .replace(/\/+$/, '');
  if (!raw) return { pageId: '', params: {} };

  const segments = raw.split('/').filter(Boolean);
  const pageId = segments[0] || '';
  const dynamicId = segments[1] || '';

  const decodePart = (value) => {
    try {
      return decodeURIComponent(value || '');
    } catch {
      return value || '';
    }
  };

  const shineLogin = parseShineRootSegment(pageId);
  if (shineLogin) {
    const section = decodePart(segments[1] || '').toLowerCase();
    if (!section) {
      return { pageId: 'user', params: { login: shineLogin, fromPage: 'messages-list', section: 'profile' } };
    }
    if (section === 'links') {
      return { pageId: 'network-view', params: { mode: 'keep-history', login: shineLogin } };
    }
    if (section === 'channels') {
      const sub = decodePart(segments[2] || '').toLowerCase();
      if (sub === 'owned') {
        return {
          pageId: 'channels-list',
          params: { mode: 'my', login: shineLogin, scope: 'owned' },
        };
      }
      if (sub === 'following') {
        return {
          pageId: 'channels-list',
          params: { mode: 'feed', login: shineLogin, scope: 'following' },
        };
      }
      return {
        pageId: 'channels-list',
        params: { mode: 'feed', login: shineLogin, scope: 'all' },
      };
    }
    if (section === 'msg') {
      return {
        pageId: 'channel-thread-view',
        params: {
          messageBlockchainName: decodePart(segments[2]),
          messageBlockNumber: segments[3] || '',
          messageBlockHash: '',
          channelOwnerBlockchainName: '',
          channelRootBlockNumber: '',
          channelRootBlockHash: '',
        },
      };
    }
    if (section === 'channel') {
      const ownerBlockchainName = decodePart(segments[2] || '');
      const channelName = decodePart(segments[3] || '');
      const messageBlockNumber = segments[4] || '';
      if (ownerBlockchainName && channelName && messageBlockNumber) {
        return {
          pageId: 'channel-thread-view',
          params: {
            ownerBlockchainName,
            channelName,
            messageBlockNumber,
            messageBlockHash: '',
            messageBlockchainName: '',
            channelOwnerBlockchainName: ownerBlockchainName,
            channelRootBlockNumber: '',
            channelRootBlockHash: '',
          },
        };
      }
      return {
        pageId: 'channel-view',
        params: { ownerBlockchainName, channelName, channelId: '' },
      };
    }
  }

  if (pageId === 'chat-view') {
    return { pageId, params: { chatId: dynamicId ? decodeURIComponent(dynamicId) : '' } };
  }

  if (pageId === 'channel-view') {
    if (segments.length >= 4) {
      return {
        pageId,
        params: {
          ownerBlockchainName: decodePart(segments[1]),
          channelRootBlockNumber: segments[2] || '',
          channelRootBlockHash: segments[3] || '',
          channelId: '',
        },
      };
    }
    return { pageId, params: { channelId: dynamicId || '' } };
  }

  if (pageId === 'channel-thread-view') {
    return {
      pageId,
      params: {
        messageBlockchainName: decodePart(segments[1]),
        messageBlockNumber: segments[2] || '',
        messageBlockHash: '',
        channelOwnerBlockchainName: decodePart(segments[3]),
        channelRootBlockNumber: segments[4] || '',
        channelRootBlockHash: segments[5] || '',
      },
    };
  }

  if (pageId === 'device-session-view') {
    return { pageId, params: { sessionId: dynamicId ? decodeURIComponent(dynamicId) : '' } };
  }

  if (pageId === 'network-view') {
    return { pageId, params: { mode: segments[1] ? decodePart(segments[1]) : '' } };
  }

  if (pageId === 'channels-list') {
    return { pageId, params: { mode: segments[1] ? decodePart(segments[1]) : '' } };
  }

  return { pageId, params: {} };
}

export function navigate(path) {
  const cleanPath = String(path || '').replace(/^\/+/, '');
  const nextPath = cleanPath ? `/${cleanPath}` : '/';
  if (window.location.pathname !== nextPath) {
    window.history.pushState({}, '', nextPath);
  }
  window.dispatchEvent(new PopStateEvent('popstate'));
}

export function navigateBack() {
  if (window.history.length <= 1) return;
  window.history.back();
}

export function resolveToolbarActive(pageId) {
  if (ROOT_PAGES.includes(pageId)) return pageId;
  if (
    pageId === 'profile-edit-view' ||
    pageId === 'wallet-view' ||
    pageId === 'settings-view' ||
    pageId === 'developer-settings-view' ||
    pageId === 'server-settings-view' ||
    pageId === 'tools-settings-view' ||
    pageId === 'device-view' ||
    pageId === 'connect-device-view' ||
    pageId === 'device-pairing-view' ||
    pageId === 'device-qr-view' ||
    pageId === 'device-camera-view' ||
    pageId === 'show-keys-view' ||
    pageId === 'device-session-view' ||
    pageId === 'language-view' ||
    pageId === 'app-log-view' ||
    pageId === 'pwa-diagnostics-view' ||
    pageId === 'solana-users-init-view'
  ) return 'profile-view';
  if (pageId === 'chat-view' || pageId === 'contact-search-view') return 'messages-list';
  if (pageId === 'channel-view' || pageId === 'channel-thread-view' || pageId === 'add-channel-view' || pageId === 'add-personal-public-chat-view') return 'channels-list';
  if (pageId === 'user') return 'messages-list';
  return 'profile-view';
}
