function encodeRoutePart(value = '') {
  return encodeURIComponent(String(value || '').trim());
}

function decodeRoutePart(value = '') {
  try {
    return decodeURIComponent(String(value || ''));
  } catch {
    return String(value || '');
  }
}

export function normalizeLogin(value = '') {
  return String(value || '').trim().replace(/^@+/, '');
}

export function extractLoginFromBlockchainName(value = '') {
  const raw = String(value || '').trim();
  const match = raw.match(/^(.+)-\d+$/);
  if (!match) return normalizeLogin(raw);
  return normalizeLogin(String(match[1] || ''));
}

export function makeProfileRoute(login = '') {
  const clean = normalizeLogin(login);
  return clean ? `shine.${encodeRoutePart(clean)}` : 'profile-view';
}

export function makeProfileLinksRoute(login = '') {
  const clean = normalizeLogin(login);
  return clean ? `shine.${encodeRoutePart(clean)}/links` : 'network-view/keep-history';
}

export function makeProfileChannelsRoute(login = '', scope = 'all') {
  const clean = normalizeLogin(login);
  if (!clean) return 'channels-list/feed';
  const normalizedScope = String(scope || '').trim().toLowerCase();
  if (normalizedScope === 'owned') return `shine.${encodeRoutePart(clean)}/channels/owned`;
  if (normalizedScope === 'following') return `shine.${encodeRoutePart(clean)}/channels/following`;
  return `shine.${encodeRoutePart(clean)}/channels`;
}

export function makeShineChannelRoute({ ownerLogin = '', ownerBlockchainName = '', channelName = '', messageBlockNumber = '' }) {
  const cleanOwnerLogin = normalizeLogin(ownerLogin) || extractLoginFromBlockchainName(ownerBlockchainName);
  const ownerBch = String(ownerBlockchainName || '').trim();
  const chName = String(channelName || '').trim();
  const msgNo = String(messageBlockNumber || '').trim();
  if (!cleanOwnerLogin || !ownerBch || !chName) return '';
  if (msgNo) return `shine.${encodeRoutePart(cleanOwnerLogin)}/channel/${encodeRoutePart(ownerBch)}/${encodeRoutePart(chName)}/${encodeRoutePart(msgNo)}`;
  return `shine.${encodeRoutePart(cleanOwnerLogin)}/channel/${encodeRoutePart(ownerBch)}/${encodeRoutePart(chName)}`;
}

export function makeShineMessageRoute({ ownerLogin = '', messageBlockchainName = '', messageBlockNumber = '' }) {
  const cleanOwnerLogin = normalizeLogin(ownerLogin);
  const msgBch = String(messageBlockchainName || '').trim();
  const msgNo = String(messageBlockNumber || '').trim();
  if (!cleanOwnerLogin || !msgBch || !msgNo) return '';
  return `shine.${encodeRoutePart(cleanOwnerLogin)}/msg/${encodeRoutePart(msgBch)}/${encodeRoutePart(msgNo)}`;
}

export function parseShineRootSegment(segment = '') {
  const raw = String(segment || '').trim();
  if (!raw.toLowerCase().startsWith('shine.')) return '';
  return normalizeLogin(decodeRoutePart(raw.slice('shine.'.length)));
}
