/**
 * admin-store.js
 * Global admin settings store for DSS configuration
 * Manages hostname, port, local/remote setup type
 */

export class AdminStore {
  constructor() {
    this.state = {
      hostname: localStorage.getItem('admin_hostname') || 'localhost',
      port: parseInt(localStorage.getItem('admin_port')) || 6006,
      isRemote: localStorage.getItem('admin_isRemote') === 'true' || false,
      dssSetupType: localStorage.getItem('admin_setupType') || 'local'
    };
    this.listeners = new Set();
  }

  getState() {
    return { ...this.state };
  }

  setState(newState) {
    const oldState = this.state;
    this.state = { ...this.state, ...newState };

    // Persist to localStorage
    localStorage.setItem('admin_hostname', this.state.hostname);
    localStorage.setItem('admin_port', this.state.port.toString());
    localStorage.setItem('admin_isRemote', this.state.isRemote.toString());
    localStorage.setItem('admin_setupType', this.state.dssSetupType);

    // Notify listeners
    this.notifyListeners();
    return this.state;
  }

  /**
   * Update hostname
   * @param {string} hostname - Hostname or IP address
   */
  setHostname(hostname) {
    return this.setState({ hostname });
  }

  /**
   * Update port
   * @param {number} port - Port number
   */
  setPort(port) {
    return this.setState({ port: parseInt(port) });
  }

  /**
   * Toggle between local and remote DSS setup
   * @param {boolean} isRemote - True for remote, false for local
   */
  setRemote(isRemote) {
    const dssSetupType = isRemote ? 'remote' : 'local';
    return this.setState({ isRemote, dssSetupType });
  }

  /**
   * Get full URL for Storybook based on current settings
   * @param {string} skin - Selected skin/theme
   * @returns {string} Full Storybook URL
   */
  getStorybookUrl(skin = 'default') {
    const protocol = this.state.isRemote ? 'https' : 'http';
    return `${protocol}://${this.state.hostname}:${this.state.port}/storybook/?skin=${skin}`;
  }

  /**
   * Subscribe to state changes
   * @param {Function} callback - Called when state changes
   * @returns {Function} Unsubscribe function
   */
  subscribe(callback) {
    this.listeners.add(callback);
    return () => this.listeners.delete(callback);
  }

  notifyListeners() {
    this.listeners.forEach(listener => listener(this.state));
  }

  /**
   * Reset to defaults
   */
  reset() {
    localStorage.removeItem('admin_hostname');
    localStorage.removeItem('admin_port');
    localStorage.removeItem('admin_isRemote');
    localStorage.removeItem('admin_setupType');

    this.state = {
      hostname: 'localhost',
      port: 6006,
      isRemote: false,
      dssSetupType: 'local'
    };
    this.notifyListeners();
  }
}

// Singleton instance
let adminStoreInstance = null;

export function useAdminStore() {
  if (!adminStoreInstance) {
    adminStoreInstance = new AdminStore();
  }
  return adminStoreInstance;
}
