using System.IO;
using System.Text;
using NexusShell.Models.Browser;

namespace NexusShell.Services;

public sealed class NexusBrowserService
{
    private readonly string _favoritesPath;
    private readonly List<BrowserFavorite> _favorites = [];

    public NexusBrowserService(NexusTabService tabService, NexusBrowserNavigationService navigationService)
    {
        TabService = tabService;
        NavigationService = navigationService;

        var folder = Path.Combine(
            Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
            "NinjaNexus",
            "browser");
        Directory.CreateDirectory(folder);
        _favoritesPath = Path.Combine(folder, "favorites.json");
        LoadFavorites();
    }

    public NexusTabService TabService { get; }
    public NexusBrowserNavigationService NavigationService { get; }

    public IReadOnlyList<BrowserFavorite> Favorites => _favorites;

    public IReadOnlyList<BrowserQuickLink> QuickLinks { get; } =
    [
        new("RenNinja", "https://renninja.dk"),
        new("NinjaKernen", "https://ninjakernen.info"),
        new("Staldara.dk", "https://staldara.dk"),
        new("Google", "https://www.google.com"),
        new("Microsoft 365", "https://www.microsoft365.com"),
        new("YouTube", "https://www.youtube.com"),
    ];

    public string GetHomePageHtml()
    {
        var links = new StringBuilder();
        foreach (var link in QuickLinks)
        {
            links.Append(
                $"""
                 <a class="quick-link" href="{link.Url}">
                   <span class="link-label">{System.Net.WebUtility.HtmlEncode(link.Label)}</span>
                 </a>
                 """);
        }

        return $$"""
            <!DOCTYPE html>
            <html lang="da">
            <head>
              <meta charset="utf-8"/>
              <meta name="viewport" content="width=device-width, initial-scale=1"/>
              <title>Nexus Browser</title>
              <style>
                * { box-sizing: border-box; margin: 0; padding: 0; }
                body {
                  min-height: 100vh;
                  font-family: "Segoe UI Variable Display", "Segoe UI", sans-serif;
                  color: #E8F0FF;
                  background: radial-gradient(circle at 20% 20%, #1a1040 0%, #020712 55%, #01040c 100%);
                  display: flex; align-items: center; justify-content: center;
                  padding: 48px 24px;
                }
                .panel {
                  width: min(920px, 100%);
                  border-radius: 28px;
                  padding: 48px 40px;
                  background: rgba(8, 20, 40, 0.72);
                  border: 1px solid rgba(0, 217, 255, 0.28);
                  box-shadow: 0 0 48px rgba(138, 79, 255, 0.18), 0 0 24px rgba(0, 217, 255, 0.12);
                }
                h1 {
                  font-size: 2.4rem; font-weight: 700; letter-spacing: -0.02em;
                  background: linear-gradient(120deg, #00D9FF, #8A4FFF);
                  -webkit-background-clip: text; -webkit-text-fill-color: transparent;
                  margin-bottom: 8px;
                }
                .subtitle { color: #8CA3C7; font-size: 1.05rem; margin-bottom: 36px; }
                .section-title {
                  font-size: 0.72rem; font-weight: 700; letter-spacing: 0.12em;
                  text-transform: uppercase; color: #8CA3C7; margin-bottom: 14px;
                }
                .quick-grid {
                  display: grid; grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
                  gap: 12px; margin-bottom: 36px;
                }
                .quick-link {
                  display: flex; align-items: center; justify-content: center;
                  min-height: 72px; padding: 14px 16px; border-radius: 18px;
                  text-decoration: none; color: #E8F0FF;
                  background: rgba(20, 8, 40, 0.55);
                  border: 1px solid rgba(255, 255, 255, 0.12);
                  transition: border-color 0.15s, box-shadow 0.15s, background 0.15s;
                }
                .quick-link:hover {
                  border-color: rgba(0, 217, 255, 0.55);
                  background: rgba(0, 217, 255, 0.12);
                  box-shadow: 0 0 18px rgba(0, 217, 255, 0.22);
                }
                .link-label { font-size: 0.95rem; font-weight: 600; text-align: center; }
                .recent-placeholder {
                  padding: 18px 20px; border-radius: 16px;
                  color: #6B84A8; font-size: 0.92rem;
                  background: rgba(255, 255, 255, 0.03);
                  border: 1px dashed rgba(255, 255, 255, 0.1);
                }
              </style>
            </head>
            <body>
              <div class="panel">
                <h1>Nexus Browser</h1>
                <p class="subtitle">Søg eller skriv adresse</p>
                <div class="section-title">Hurtige links</div>
                <div class="quick-grid">{{links}}</div>
                <div class="section-title">Seneste</div>
                <div class="recent-placeholder">Ingen seneste besøg endnu — historik gemmes automatisk.</div>
              </div>
            </body>
            </html>
            """;
    }

    public bool ToggleFavorite(string title, string url)
    {
        var existing = _favorites.FirstOrDefault(f =>
            string.Equals(f.Url, url, StringComparison.OrdinalIgnoreCase));

        if (existing is not null)
        {
            _favorites.Remove(existing);
            SaveFavorites();
            return false;
        }

        _favorites.Add(new BrowserFavorite
        {
            Title = string.IsNullOrWhiteSpace(title) ? url : title,
            Url = url,
            AddedAt = DateTimeOffset.UtcNow,
        });
        SaveFavorites();
        return true;
    }

    public bool IsFavorite(string url) =>
        _favorites.Any(f => string.Equals(f.Url, url, StringComparison.OrdinalIgnoreCase));

    private void LoadFavorites()
    {
        try
        {
            if (!File.Exists(_favoritesPath))
            {
                return;
            }

            var json = File.ReadAllText(_favoritesPath);
            var entries = System.Text.Json.JsonSerializer.Deserialize<List<BrowserFavorite>>(json);
            if (entries is not null)
            {
                _favorites.Clear();
                _favorites.AddRange(entries);
            }
        }
        catch
        {
            // POC: ignore corrupt favorites
        }
    }

    private void SaveFavorites()
    {
        try
        {
            var json = System.Text.Json.JsonSerializer.Serialize(_favorites, new System.Text.Json.JsonSerializerOptions
            {
                WriteIndented = true,
            });
            File.WriteAllText(_favoritesPath, json);
        }
        catch
        {
            // POC: ignore persist failures
        }
    }
}

public sealed record BrowserQuickLink(string Label, string Url);
