import 'dart:convert';
import 'package:http/http.dart' as http;

/// Service for fetching background portraits from the Unsplash API.
class UnsplashService {
  static const String _clientId = 'BkgEMpfG_ReNpVwJcbgNx30IZXhoFoWwKgwbrPU0hq4';
  static const String _baseUrl = 'https://api.unsplash.com';

  static final UnsplashService instance = UnsplashService._();
  UnsplashService._();

  /// Fetches a list of highly compressed landscape URLs based on the given keyword.
  Future<List<String>> fetchLandscapeBackgrounds(String keyword) async {
    // Trim keyword and default to 'mosque' if empty
    final query = keyword.trim().isEmpty ? 'mosque' : keyword.trim();
    
    // Specifically requesting 'regular' size to fit 1080p elegantly while minimizing RAM overhead.
    final url = Uri.parse('$_baseUrl/search/photos?query=$query&orientation=landscape&per_page=20');

    try {
      final response = await http.get(
        url,
        headers: {
          'Authorization': 'Client-ID $_clientId',
          'Accept-Version': 'v1',
        },
      );

      if (response.statusCode == 200) {
        final data = json.decode(response.body);
        final results = data['results'] as List<dynamic>? ?? [];
        
        final urls = <String>[];
        for (final item in results) {
          final urlsMap = item['urls'] as Map<String, dynamic>?;
          if (urlsMap != null && urlsMap.containsKey('regular')) {
            urls.add(urlsMap['regular'].toString());
          }
        }
        return urls;
      }
    } catch (e) {
      // Offline or error — fail silently.
    }
    
    return [];
  }
}
