"""Default apps — Standard-Anwendung pro Kategorie wählen (user-level)."""
from __future__ import annotations

import gi

gi.require_version("Gtk", "4.0")
gi.require_version("Adw", "1")
from gi.repository import Adw, Gdk, Gtk  # noqa: E402

from taninux.core import defaultapps


def _icon(name: str, fallback: str) -> str:
    theme = Gtk.IconTheme.get_for_display(Gdk.Display.get_default())
    return name if (name and theme and theme.has_icon(name)) else fallback


def build() -> Gtk.Widget:
    page = Adw.PreferencesPage()
    group = Adw.PreferencesGroup(title="Default applications")
    page.add(group)

    for label, mime, fallback in defaultapps.CATEGORIES:
        current, apps = defaultapps.apps_for(mime)
        row = Adw.ComboRow(title=label)
        row.add_prefix(Gtk.Image.new_from_icon_name(fallback))

        if not apps:
            row.set_subtitle("No app installed")
            row.set_sensitive(False)
            group.add(row)
            continue

        names = [a.name for a in apps]
        row.set_model(Gtk.StringList.new(names))
        if current:
            sel = next((i for i, a in enumerate(apps) if a.id == current.id), 0)
            row.set_selected(sel)

        def on_sel(r, _p, apps=apps, mime=mime) -> None:
            i = r.get_selected()
            if 0 <= i < len(apps):
                defaultapps.set_default(apps[i].id, mime)

        row.connect("notify::selected", on_sel)
        group.add(row)

    return page
