/**
 * Client-safe product constants — no Node.js imports.
 *
 * Use this in 'use client' components. For server-side code that needs
 * loadProductIdentity(), import from product-config.ts instead.
 *
 * The product list is CONFIGURABLE so this dashboard works for any deployment
 * (a third-party / freelance / self-hosted operator), not just the built-in set.
 * Set `NEXT_PUBLIC_PRODUCTS` to a JSON array of `{ id, name, icon? }` to override
 * the default list; an empty/invalid value falls back to the built-in default.
 */

export const PRODUCT_ID = process.env.NEXT_PUBLIC_PRODUCT_ID || process.env.PRODUCT_ID || 'lysnrai';
export const DISPLAY_NAME = process.env.NEXT_PUBLIC_DISPLAY_NAME || 'LysnrAI';

/** A selectable product/project the dashboard can be scoped to. */
export interface Product {
  id: string;
  name: string;
  icon?: string;
}

/** Built-in default product set (the original ByteLyst ecosystem). */
export const DEFAULT_PRODUCTS: readonly Product[] = [
  { id: 'lysnrai', name: 'LysnrAI', icon: 'Mic' },
  { id: 'chronomind', name: 'ChronoMind', icon: 'Clock' },
  { id: 'nomgap', name: 'NomGap', icon: 'Apple' },
  { id: 'mindlyst', name: 'MindLyst', icon: 'Brain' },
];

/**
 * Parse the `NEXT_PUBLIC_PRODUCTS` override into a validated product list. PURE +
 * defensive: any malformed entry (missing id/name, non-array, bad JSON) falls
 * back to `fallback`, so a bad env value can never blank out the switcher.
 */
export function parseProductsEnv(
  raw: string | undefined,
  fallback: readonly Product[] = DEFAULT_PRODUCTS
): readonly Product[] {
  if (!raw || raw.trim() === '') return fallback;
  try {
    const parsed: unknown = JSON.parse(raw);
    if (!Array.isArray(parsed)) return fallback;
    const products: Product[] = [];
    for (const entry of parsed) {
      if (!entry || typeof entry !== 'object') continue;
      const { id, name, icon } = entry as Record<string, unknown>;
      if (typeof id !== 'string' || id.trim() === '') continue;
      products.push({
        id,
        name: typeof name === 'string' && name.trim() !== '' ? name : id,
        ...(typeof icon === 'string' ? { icon } : {}),
      });
    }
    return products.length > 0 ? products : fallback;
  } catch {
    return fallback;
  }
}

/** Configured product set — `NEXT_PUBLIC_PRODUCTS` override, else the default. */
export const KNOWN_PRODUCTS: readonly Product[] = parseProductsEnv(
  process.env.NEXT_PUBLIC_PRODUCTS
);
