import { Injectable, signal } from '@angular/core';
import {
  AppearanceId,
  IconStyleId,
  THEME_PROPOSALS,
  ThemeProposal,
} from '../theme/appearance.config';

const STORAGE_KEY = 'dailymeals.appearance';

@Injectable({ providedIn: 'root' })
export class AppearanceService {
  readonly proposal = signal<ThemeProposal>(this.load());

  readonly iconStyle = signal<IconStyleId>(this.proposal().iconStyle);

  init(): void {
    this.apply(this.proposal());
  }

  setProposal(id: AppearanceId): void {
    const next = THEME_PROPOSALS.find((p) => p.id === id) ?? THEME_PROPOSALS[0];
    this.proposal.set(next);
    this.iconStyle.set(next.iconStyle);
    localStorage.setItem(STORAGE_KEY, id);
    this.apply(next);
  }

  proposals(): ThemeProposal[] {
    return THEME_PROPOSALS;
  }

  strokeWidth(): string {
    return this.iconStyle() === 'bold' ? '2.5' : '2';
  }

  useEmojiIcons(): boolean {
    return this.iconStyle() === 'emoji';
  }

  private load(): ThemeProposal {
    const stored = localStorage.getItem(STORAGE_KEY) as AppearanceId | null;
    const found = THEME_PROPOSALS.find((p) => p.id === stored);
    const proposal = found ?? THEME_PROPOSALS[0];
    this.apply(proposal);
    return proposal;
  }

  private apply(proposal: ThemeProposal): void {
    const root = document.documentElement;
    root.dataset['colorTheme'] = proposal.colorTheme;
    root.dataset['iconStyle'] = proposal.iconStyle;
  }
}
