import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

export type LayoutMode = 'split' | 'full';

export interface AppLayoutSettings {
  showBrief: boolean;
  layoutMode: LayoutMode;
  // whether the split-view hint has been dismissed by the user
  splitHintDismissed?: boolean;
  // brief panel customization
  briefBgColor?: string;
  briefText?: string;
  briefTextColor?: string;
  // sidebar overlay effect (none | smoke | dark | gradient | glass | white | opacity)
  sidebarOverlayEffect?: string;
  // opacity/strength for the overlay effect (0.0 - 1.0)
  sidebarOverlayOpacity?: number;
}

@Injectable({ providedIn: 'root' })
export class SettingsService {
  private readonly STORAGE_KEY = 'appLayoutSettings';

  private settingsSubject = new BehaviorSubject<AppLayoutSettings>(this.loadInitialSettings());

  private loadInitialSettings(): AppLayoutSettings {
    try {
      const raw = localStorage.getItem(this.STORAGE_KEY);
      if (raw) {
        const parsed = JSON.parse(raw) as Partial<AppLayoutSettings>;
        return {
          showBrief: parsed.showBrief ?? false,
          layoutMode: (parsed.layoutMode as LayoutMode) ?? 'full',
          splitHintDismissed: parsed.splitHintDismissed ?? false,
          briefBgColor: parsed.briefBgColor ?? '#CFE8FF',
          briefText: parsed.briefText ?? '',
          briefTextColor: parsed.briefTextColor ?? '#032b38',
          sidebarOverlayEffect: parsed.sidebarOverlayEffect ?? 'none',
          sidebarOverlayOpacity: parsed.sidebarOverlayOpacity ?? 0.5
        };
      }
    } catch (e) {
      // ignore parse errors and fall back to defaults
    }
    return { showBrief: false, layoutMode: 'full', splitHintDismissed: false, briefBgColor: '#CFE8FF', briefText: '', briefTextColor: '#032b38', sidebarOverlayEffect: 'none', sidebarOverlayOpacity: 0.5 };
  }

  readonly settings$ = this.settingsSubject.asObservable();

  updateSettings(patch: Partial<AppLayoutSettings>): void {
    const next = { ...this.settingsSubject.value, ...patch } as AppLayoutSettings;
    try {
      localStorage.setItem(this.STORAGE_KEY, JSON.stringify(next));
    } catch (e) {
      // ignore localStorage errors (e.g., private mode)
    }
    this.settingsSubject.next(next);
  }

  getSettings(): AppLayoutSettings {
    return { ...this.settingsSubject.value };
  }
}
