/**
 * Namespaced localStorage helper for UI components.
 */
const safeStorageGet = (key) => {
  const normalized = String(key || '').trim();
  if (normalized === '') {
    return null;
  }
  try {
    return window.localStorage.getItem(normalized);
  } catch {
    return null;
  }
};

const safeStorageSet = (key, value) => {
  const normalized = String(key || '').trim();
  if (normalized === '') {
    return;
  }
  try {
    window.localStorage.setItem(normalized, value);
  } catch {
    // localStorage may be unavailable; fail safe.
  }
};

const safeStorageRemove = (key) => {
  const normalized = String(key || '').trim();
  if (normalized === '') {
    return;
  }
  try {
    window.localStorage.removeItem(normalized);
  } catch {
    // localStorage may be unavailable; fail safe.
  }
};

const normalizeToken = (value) => String(value ?? '')
  .trim()
  .toLowerCase()
  .replaceAll(/[^a-z0-9._-]+/g, '-')
  .replaceAll(/^-+|-+$/g, '');

export function createUiStorage(options = {}) {
  const namespace = normalizeToken(options.namespace || 'app-ui') || 'app-ui';
  const version = normalizeToken(options.version || 'v1') || 'v1';
  const scope = normalizeToken(options.scope || '') || 'global';
  const basePrefix = `${namespace}:${version}:${scope}`;

  const buildKey = (bucket, key) => {
    const normalizedBucket = normalizeToken(bucket || 'component') || 'component';
    const normalizedKey = normalizeToken(key || '');
    if (normalizedKey === '') {
      return '';
    }
    return `${basePrefix}:${normalizedBucket}:${normalizedKey}`;
  };

  return {
    buildKey,
    getItem: safeStorageGet,
    setItem: safeStorageSet,
    removeItem: safeStorageRemove,
  };
}
