'use client';

export interface ShareableState {
  text: string;
  font: string;
}

/**
 * Encode text and font to URL parameters
 */
export function encodeToUrl(text: string, font: string): string {
  const params = new URLSearchParams();

  if (text) {
    params.set('text', text);
  }

  if (font && font !== 'Standard') {
    params.set('font', font);
  }

  const queryString = params.toString();
  return queryString ? `?${queryString}` : '';
}

/**
 * Decode URL parameters to get text and font
 */
export function decodeFromUrl(): ShareableState | null {
  if (typeof window === 'undefined') return null;

  const params = new URLSearchParams(window.location.search);
  const text = params.get('text');
  const font = params.get('font');

  if (!text && !font) return null;

  return {
    text: text || '',
    font: font || 'Standard',
  };
}

/**
 * Update the URL without reloading the page
 */
export function updateUrl(text: string, font: string): void {
  if (typeof window === 'undefined') return;

  const url = encodeToUrl(text, font);
  const newUrl = url ? `${window.location.pathname}${url}` : window.location.pathname;

  window.history.replaceState({}, '', newUrl);
}

/**
 * Get shareable URL
 */
export function getShareableUrl(text: string, font: string): string {
  if (typeof window === 'undefined') return '';

  const query = encodeToUrl(text, font);
  return `${window.location.origin}${window.location.pathname}${query}`;
}
