# Copyright 2026, Jiri Eischmann <jiri@eischmann.cz> and the meshy contributors
# SPDX-License-Identifier: GPL-3.0-or-later

"""Contacts list view - shown in the sidebar."""

import gi

gi.require_version("Gtk", "4.0")
gi.require_version("Adw", "1")
gi.require_version("Shumate", "1.0")
from gi.repository import Adw, Gio, GLib, GObject, Gtk, Shumate
from meshy.models import Contact, ContactType
from meshy.protocol import build_sync_next_message
from meshy.utils import clear_children, format_number, format_trip_time, ngettext
from meshy.views import (
    _add_hover_swap,
    show_contact_picker,
)

SORT_AZ = "az"
SORT_HEARD = "heard"
SORT_MESSAGES = "messages"


def contact_sort_key(c: Contact, sort_mode: str, favorites_first: bool):
    """Compute sort key for a contact. Usable independently of ContactsView."""
    fav = favorites_first
    if sort_mode == SORT_AZ:
        return (not c.is_favorite if fav else False, c.name.lower())
    elif sort_mode == SORT_MESSAGES:
        return (
            not c.is_favorite if fav else False,
            -(c.last_message_at.timestamp() if c.last_message_at else 0),
        )
    else:  # SORT_HEARD
        return (
            not c.is_favorite if fav else False,
            -(c.last_seen.timestamp() if c.last_seen else 0),
        )


@Gtk.Template(resource_path="/page/codeberg/sesivany/Meshy/ui/contacts-view.ui")
class ContactsView(Gtk.Box):
    __gtype_name__ = "MeshyContactsView"

    _search_bar = Gtk.Template.Child("search_bar")
    _search_entry = Gtk.Template.Child("search_entry")
    _list_box = Gtk.Template.Child("list_box")
    _status_label = Gtk.Template.Child("status_label")
    _add_btn = Gtk.Template.Child("add_btn")

    # Filter constants
    FILTER_ALL = "all"
    FILTER_FAVORITES = "favorites"
    FILTER_USERS = "users"
    FILTER_REPEATERS = "repeaters"
    FILTER_ROOMS = "rooms"
    FILTER_SENSORS = "sensors"

    # Sort constants
    SORT_AZ = "az"
    SORT_HEARD = "heard"
    SORT_MESSAGES = "messages"

    def __init__(self, window, **kwargs):
        super().__init__(**kwargs)
        self._window = window
        self._contact_rows: dict[str, Adw.ActionRow] = {}
        self._unread_keys: set[str] = set()
        self._unread_counts: dict[str, int] = {}
        self._unread_dots: dict[str, Gtk.Label] = {}
        self._current_filter = self.FILTER_ALL
        settings = Gio.Settings(schema_id="page.codeberg.sesivany.Meshy")
        saved_sort = settings.get_string("contact-sort")
        self._current_sort = (
            saved_sort
            if saved_sort in (self.SORT_AZ, self.SORT_HEARD, self.SORT_MESSAGES)
            else self.SORT_HEARD
        )
        self._favorites_first = settings.get_boolean("contact-favorites-first")
        self._login_dialog_open = False
        self._total_contacts = 0

        # Register actions
        action_group = Gio.SimpleActionGroup()
        filter_action = Gio.SimpleAction.new_stateful(
            "filter", GLib.VariantType.new("s"), GLib.Variant.new_string(self._current_filter)
        )
        filter_action.connect("activate", self._on_filter_changed)
        action_group.add_action(filter_action)
        sort_action = Gio.SimpleAction.new_stateful(
            "sort", GLib.VariantType.new("s"), GLib.Variant.new_string(self._current_sort)
        )
        sort_action.connect("activate", self._on_sort_changed)
        action_group.add_action(sort_action)
        fav_action = Gio.SimpleAction.new_stateful(
            "favorites-first", None, GLib.Variant.new_boolean(self._favorites_first)
        )
        fav_action.connect("change-state", self._on_favorites_first_toggled)
        action_group.add_action(fav_action)

        # Add contact menu (conditional QR item)
        add_menu = Gio.Menu()
        add_menu.append(_("Discover Contacts"), "contacts.discover")
        add_menu.append(_("Add Manually"), "contacts.add-manual")
        add_menu.append(_("Import from Clipboard"), "contacts.import-clipboard")
        import meshy as _meshy_pkg

        if _meshy_pkg.QR_SCANNER_ENABLED:
            add_menu.append(_("Scan QR Code"), "contacts.scan-qr")
        self._add_btn.set_menu_model(add_menu)

        add_action = Gio.SimpleAction.new("add-manual", None)
        add_action.connect("activate", self._on_add_manual)
        action_group.add_action(add_action)

        discover_action = Gio.SimpleAction.new("discover", None)
        discover_action.connect("activate", self._on_discover_contacts)
        action_group.add_action(discover_action)

        clipboard_action = Gio.SimpleAction.new("import-clipboard", None)
        clipboard_action.connect("activate", self._on_import_clipboard)
        action_group.add_action(clipboard_action)

        if _meshy_pkg.QR_SCANNER_ENABLED:
            qr_action = Gio.SimpleAction.new("scan-qr", None)
            qr_action.connect("activate", self._on_scan_qr)
            action_group.add_action(qr_action)

        self._action_group = action_group
        self.insert_action_group("contacts", action_group)
        self._search_btn = None
        self._search_binding = None

        # Signal connections
        self._search_bar.connect_entry(self._search_entry)
        self._search_bar.connect("notify::search-mode-enabled", self._on_search_mode_changed)
        self._search_entry.connect("search-changed", self._on_search_changed)
        self._list_box.set_filter_func(self._filter_func)
        self._list_box.connect("row-activated", self._on_row_selected)

        # Initial populate
        self.update_contacts(self._window.contacts)

    def set_search_button(self, btn):
        if self._search_binding:
            self._search_binding.unbind()
        self._search_btn = btn
        self._search_binding = btn.bind_property(
            "active",
            self._search_bar,
            "search-mode-enabled",
            GObject.BindingFlags.BIDIRECTIONAL | GObject.BindingFlags.SYNC_CREATE,
        )

    def build_filter_menu(self):
        menu = Gio.Menu()
        for filter_id, label in (
            ("all", _("All")),
            ("favorites", _("Favourites")),
            ("users", _("Users")),
            ("repeaters", _("Repeaters")),
            ("rooms", _("Room Servers")),
            ("sensors", _("Sensors")),
        ):
            item = Gio.MenuItem.new(label, None)
            item.set_action_and_target_value("contacts.filter", GLib.Variant.new_string(filter_id))
            menu.append_item(item)
        return menu

    def build_sort_menu(self):
        menu = Gio.Menu()
        section1 = Gio.Menu()
        for sort_id, label in (
            ("az", _("A–Z")),
            ("heard", _("Heard Recently")),
            ("messages", _("Latest Messages")),
        ):
            item = Gio.MenuItem.new(label, None)
            item.set_action_and_target_value("contacts.sort", GLib.Variant.new_string(sort_id))
            section1.append_item(item)
        menu.append_section(None, section1)
        section2 = Gio.Menu()
        section2.append(_("Favorites First"), "contacts.favorites-first")
        menu.append_section(None, section2)
        return menu

    def _filter_func(self, row) -> bool:
        if not hasattr(row, "_contact"):
            return True
        contact = row._contact

        # Type filter
        f = self._current_filter
        if (
            f == self.FILTER_FAVORITES
            and not contact.is_favorite
            or f == self.FILTER_USERS
            and contact.type != ContactType.CHAT
            or f == self.FILTER_REPEATERS
            and contact.type != ContactType.REPEATER
            or f == self.FILTER_ROOMS
            and contact.type != ContactType.ROOM
            or f == self.FILTER_SENSORS
            and contact.type != ContactType.SENSOR
        ):
            return False

        # Search filter
        search = self._search_entry.get_text().lower()
        return not (search and search not in contact.name.lower())

    def _update_status_count(self):
        """Update the status label with visible/total contact count."""
        total = self._total_contacts
        if self._current_filter != self.FILTER_ALL or self._search_entry.get_text():
            # Count rows that pass the filter
            visible = sum(1 for row in self._contact_rows.values() if self._filter_func(row))
            self._status_label.set_label(
                _("{visible}/{total} contacts").format(visible=visible, total=total)
            )
        else:
            self._status_label.set_label(
                _("{total} contacts").format(total=total)
                if total != 1
                else _("{total} contact").format(total=total)
            )

    def _on_search_mode_changed(self, search_bar, pspec):
        if not search_bar.get_search_mode():
            self._search_entry.set_text("")

    def _on_search_changed(self, entry):
        self._list_box.invalidate_filter()
        GLib.idle_add(self._update_status_count)

    def _on_filter_changed(self, action, param):
        self._current_filter = param.get_string()
        action.set_state(param)
        self._list_box.invalidate_filter()
        GLib.idle_add(self._update_status_count)

    def _on_sort_changed(self, action, param):
        self._current_sort = param.get_string()
        action.set_state(param)
        settings = Gio.Settings(schema_id="page.codeberg.sesivany.Meshy")
        settings.set_string("contact-sort", self._current_sort)
        self.update_contacts(self._window.contacts)

    def _on_favorites_first_toggled(self, action, value):
        action.set_state(value)
        self._favorites_first = value.get_boolean()
        settings = Gio.Settings(schema_id="page.codeberg.sesivany.Meshy")
        settings.set_boolean("contact-favorites-first", self._favorites_first)
        self.update_contacts(self._window.contacts)

    def _on_discover_contacts(self, *args):
        discovered = [
            c
            for c in self._window.discovered_contacts
            if not self._window.is_contact_known(c.public_key_hex)
        ]
        if not discovered:
            dialog = Adw.AlertDialog(
                heading=_("Discover Contacts"),
                body=_(
                    "No new contacts have been heard yet. "
                    "Leave the app running and contacts will appear "
                    "as their adverts are received."
                ),
            )
            dialog.add_response("ok", _("OK"))
            dialog.present(self._window)
            return

        dev = self._window.device_info
        has_self_loc = (
            dev
            and dev.latitude is not None
            and dev.longitude is not None
            and (abs(dev.latitude) > 1e-6 or abs(dev.longitude) > 1e-6)
        )
        self_lat = dev.latitude if dev else None
        self_lon = dev.longitude if dev else None

        def _subtitle(contact):
            subtitle = contact.type_label
            if has_self_loc and contact.has_location:
                from meshy.utils import haversine_distance

                dist = haversine_distance(self_lat, self_lon, contact.latitude, contact.longitude)
                if dist < 1.0:
                    subtitle += f" · {format_number(dist * 1000, 0)} m"
                else:
                    subtitle += f" · {format_number(dist)} km"
            return subtitle

        ns = show_contact_picker(
            self._window,
            title=_("Discover Contacts"),
            contacts=discovered,
            on_add=self._window.add_discovered_contact,
            subtitle_func=_subtitle,
            status_format_all=_("{total} discovered"),
            status_format_filtered=_("{visible}/{total} discovered"),
        )

        # Filter menu
        ns.filter_btn.set_visible(True)
        filter_menu = Gio.Menu()
        for fid, label in (
            ("all", _("All")),
            ("users", _("Users")),
            ("repeaters", _("Repeaters")),
            ("rooms", _("Room Servers")),
            ("sensors", _("Sensors")),
        ):
            filter_menu.append_item(Gio.MenuItem.new(label, f"discover.filter::{fid}"))
        ns.filter_btn.set_menu_model(filter_menu)

        # Sort menu
        ns.sort_btn.set_visible(True)
        sort_menu = Gio.Menu()
        for sid, label in (
            ("name", _("Name")),
            ("last-seen", _("Last Seen")),
            ("arrival", _("Arrival Time")),
        ):
            sort_menu.append_item(Gio.MenuItem.new(label, f"discover.sort::{sid}"))
        if has_self_loc:
            sort_menu.append_item(Gio.MenuItem.new(_("Distance"), "discover.sort::distance"))
        ns.sort_btn.set_menu_model(sort_menu)

        # Actions
        action_group = Gio.SimpleActionGroup()
        filter_action = Gio.SimpleAction.new_stateful(
            "filter", GLib.VariantType.new("s"), GLib.Variant.new_string("all")
        )
        sort_action = Gio.SimpleAction.new_stateful(
            "sort", GLib.VariantType.new("s"), GLib.Variant.new_string("name")
        )
        action_group.add_action(filter_action)
        action_group.add_action(sort_action)
        ns.dialog.insert_action_group("discover", action_group)

        # Replace search-only filter with search + type filter
        ns.custom_filter.set_filter_func(
            self._discover_filter_func, (ns.search_entry, filter_action)
        )

        def _on_filter_activated(_action, param):
            filter_action.set_state(param)
            ns.custom_filter.changed(Gtk.FilterChange.DIFFERENT)
            ns.update_status()

        filter_action.connect("activate", _on_filter_activated)

        # Sorter
        custom_sorter = Gtk.CustomSorter.new(
            self._discover_sort_func, (sort_action, self_lat, self_lon)
        )

        def _on_sort_activated(_action, param):
            sort_action.set_state(param)
            custom_sorter.changed(Gtk.SorterChange.DIFFERENT)

        sort_action.connect("activate", _on_sort_activated)

        sort_model = Gtk.SortListModel(model=ns.filter_model, sorter=custom_sorter)
        ns.list_view.set_model(Gtk.NoSelection(model=sort_model))

        ns.dialog._refs.extend([custom_sorter, sort_model, action_group])
        ns.update_status()
        ns.present()

    def _discover_filter_func(self, item, user_data):
        search_entry, filter_action = user_data
        contact = item.contact
        search = search_entry.get_text().lower()
        if search and search not in contact.name.lower():
            return False
        f = filter_action.get_state().get_string()
        return not (
            f == "users"
            and contact.type != ContactType.CHAT
            or f == "repeaters"
            and contact.type != ContactType.REPEATER
            or f == "rooms"
            and contact.type != ContactType.ROOM
            or f == "sensors"
            and contact.type != ContactType.SENSOR
        )

    @staticmethod
    def _discover_sort_func(a, b, user_data=None):
        sort_action, self_lat, self_lon = user_data
        mode = sort_action.get_state().get_string()

        if mode == "last-seen":
            ta = a.contact.last_seen
            tb = b.contact.last_seen
            if ta is not None and tb is not None:
                return (tb > ta) - (tb < ta)
            if ta is not None:
                return -1
            if tb is not None:
                return 1
            na = a.contact.name.lower()
            nb = b.contact.name.lower()
            return (na > nb) - (na < nb)

        if mode == "arrival":
            ta = a.contact.received_at
            tb = b.contact.received_at
            if ta is not None and tb is not None:
                return (tb > ta) - (tb < ta)
            if ta is not None:
                return -1
            if tb is not None:
                return 1
            na = a.contact.name.lower()
            nb = b.contact.name.lower()
            return (na > nb) - (na < nb)

        if mode == "distance" and self_lat is not None and self_lon is not None:
            from meshy.utils import haversine_distance

            da = (
                haversine_distance(self_lat, self_lon, a.contact.latitude, a.contact.longitude)
                if a.contact.has_location
                else float("inf")
            )
            db = (
                haversine_distance(self_lat, self_lon, b.contact.latitude, b.contact.longitude)
                if b.contact.has_location
                else float("inf")
            )
            if da != db:
                return (da > db) - (da < db)

        na = a.contact.name.lower()
        nb = b.contact.name.lower()
        return (na > nb) - (na < nb)

    def _on_add_manual(self, *args):
        dialog = Adw.AlertDialog(
            heading=_("Add Contact"),
            body=_("Enter the contact details."),
        )
        builder = Gtk.Builder.new_from_resource(
            "/page/codeberg/sesivany/Meshy/ui/add-contact-content.ui"
        )
        dialog.set_extra_child(builder.get_object("content"))
        type_row = builder.get_object("type_row")
        type_list = Gtk.StringList()
        for label in [_("Chat"), _("Repeater"), _("Room Server"), _("Sensor")]:
            type_list.append(label)
        type_row.set_model(type_list)
        type_row.set_selected(0)
        name_row = builder.get_object("name_row")
        key_row = builder.get_object("key_row")
        dialog.add_response("cancel", _("Cancel"))
        dialog.add_response("add", _("Add"))
        dialog.set_response_appearance("add", Adw.ResponseAppearance.SUGGESTED)

        def _on_response(d, response):
            if response == "add":
                try:
                    name = name_row.get_text().strip()
                    key_text = key_row.get_text().strip()
                    pub_key = bytes.fromhex(key_text)
                    if len(pub_key) != 32 or not name:
                        return
                    if self._window.is_contact_known(key_text):
                        self._show_import_error(_("This contact is already in your list."))
                        return
                    contact_type = (
                        type_row.get_selected() + 1
                    )  # CHAT=1, REPEATER=2, ROOM=3, SENSOR=4
                    self._window.add_contact(pub_key, contact_type, name)
                except ValueError:
                    pass

        dialog.connect("response", _on_response)
        dialog.present(self._window)

    def _on_import_clipboard(self, *args):
        clipboard = self._window.get_clipboard()
        clipboard.read_text_async(None, self._on_clipboard_read)

    def _on_clipboard_read(self, clipboard, result):
        try:
            text = clipboard.read_text_finish(result)
        except Exception:
            text = None

        if not text or not text.strip().startswith("meshcore://"):
            dialog = Adw.AlertDialog(
                heading=_("Import Failed"),
                body=_("No meshcore:// link found in clipboard."),
            )
            dialog.add_response("ok", _("OK"))
            dialog.present(self._window)
            return

        app = self._window.get_application()
        app._handle_meshcore_uri(text.strip())

    def _on_scan_qr(self, *args):
        from meshy.camera import create_qr_scanner

        self._qr_scanner = create_qr_scanner(self._window, self._on_qr_result)
        self._qr_scanner.start()

    def _on_qr_result(self, data):
        """Handle a scanned QR code - meshcore:// URL or raw public key hex."""
        from urllib.parse import parse_qs, urlparse

        # meshcore://contact/add?name=...&public_key=...
        if data.lower().startswith("meshcore://"):
            parsed = urlparse(data)
            params = parse_qs(parsed.query)

            full_path = f"{parsed.netloc}{parsed.path}".rstrip("/")
            if full_path == "channel/add" and "secret" in params:
                # meshcore://channel/add?name=...&secret=...
                ch_name = params.get("name", [""])[0]
                secret_hex = params["secret"][0].strip()
                try:
                    secret = bytes.fromhex(secret_hex)
                except ValueError:
                    self._show_import_error(_("Invalid channel secret in QR code."))
                    return
                if len(secret) != 16:
                    self._show_import_error(
                        _("Channel secret must be 16 bytes, got {}.").format(len(secret))
                    )
                    return
                self._window.add_channel_from_qr(ch_name, secret)
                return

            if "public_key" in params:
                pub_key_hex = params["public_key"][0].strip()
                name = params.get("name", [""])[0]
                # Extract contact type: 1=Companion, 2=Repeater, 3=RoomServer, 4=Sensor
                try:
                    contact_type = int(params.get("type", ["1"])[0])
                except ValueError:
                    contact_type = 1
                try:
                    pub_key = bytes.fromhex(pub_key_hex)
                except ValueError:
                    self._show_import_error(_("Invalid public key in QR code."))
                    return

                if len(pub_key) != 32:
                    self._show_import_error(
                        _("Public key must be 32 bytes, got {}.").format(len(pub_key))
                    )
                    return

                if self._window.is_contact_known(pub_key_hex):
                    self._show_import_error(_("This contact is already in your list."))
                    return

                if name:
                    self._window.add_contact(pub_key, contact_type, name)
                else:
                    self._show_qr_contact_dialog(pub_key, pub_key_hex)
                return

            # Try as raw hex contact frame (old format)
            hex_data = data[len("meshcore://") :].strip()
            if "/" not in hex_data and "?" not in hex_data:
                try:
                    contact_frame = bytes.fromhex(hex_data)
                    self._window.import_contact(contact_frame)
                    return
                except ValueError:
                    pass

        # Try as raw hex public key (64 hex chars = 32 bytes)
        cleaned = data.strip().replace(" ", "").replace(":", "")
        try:
            pub_key = bytes.fromhex(cleaned)
            if len(pub_key) == 32:
                if self._window.is_contact_known(cleaned):
                    self._show_import_error(_("This contact is already in your list."))
                    return
                self._show_qr_contact_dialog(pub_key, cleaned)
                return
        except ValueError:
            pass

        self._show_import_error(_("Could not parse QR code data:\n{}").format(data[:120]))

    def _show_import_error(self, message):
        dialog = Adw.AlertDialog(heading=_("Import Failed"), body=message)
        dialog.add_response("ok", _("OK"))
        dialog.present(self._window)

    def _show_qr_contact_dialog(self, pub_key, hex_str):
        """Show dialog to complete contact details from a scanned public key."""
        dialog = Adw.AlertDialog(
            heading=_("QR Code Scanned"),
            body=_("Public key: {}...{}").format(hex_str[:16], hex_str[-16:]),
        )
        builder = Gtk.Builder.new_from_resource(
            "/page/codeberg/sesivany/Meshy/ui/qr-contact-content.ui"
        )
        dialog.set_extra_child(builder.get_object("content"))
        type_row = builder.get_object("type_row")
        type_list = Gtk.StringList()
        for label in [_("Chat"), _("Repeater"), _("Room Server"), _("Sensor")]:
            type_list.append(label)
        type_row.set_model(type_list)
        type_row.set_selected(0)
        name_row = builder.get_object("name_row")
        dialog.add_response("cancel", _("Cancel"))
        dialog.add_response("add", _("Add Contact"))
        dialog.set_response_appearance("add", Adw.ResponseAppearance.SUGGESTED)

        def _on_response(d, response):
            if response == "add":
                name = name_row.get_text().strip()
                if not name:
                    return
                contact_type = type_row.get_selected() + 1
                self._window.add_contact(pub_key, contact_type, name)

        dialog.connect("response", _on_response)
        dialog.present(self._window)

    def _on_row_selected(self, listbox, row):
        import logging

        log = logging.getLogger(__name__)
        if self._login_dialog_open:
            log.debug("Login dialog already open, ignoring row selection")
            return
        if row and hasattr(row, "_contact"):
            contact = row._contact
            log.info(
                f"Contact selected: {contact.name} (type={contact.type}, logged_in={self._window.is_room_logged_in(contact.public_key_hex)})"
            )
            if contact.type == ContactType.REPEATER:
                if self._window.is_room_logged_in(contact.public_key_hex):
                    self._window.show_repeater(
                        contact, is_admin=self._window.is_room_admin(contact.public_key_hex)
                    )
                else:
                    self._show_room_login(contact, repeater=True)
            elif contact.type == ContactType.ROOM and not self._window.is_room_logged_in(
                contact.public_key_hex
            ):
                log.info("Room not logged in, showing login dialog")
                self._show_room_login(contact)
            elif contact.type == ContactType.SENSOR:
                self._window.show_sensor(contact)
            else:
                self._window.show_chat(contact)

    def _show_room_login(self, contact: Contact, repeater: bool = False):
        """Show a login dialog for a room/repeater contact."""
        import logging

        log = logging.getLogger(__name__)
        log.info(
            f"Showing login dialog for {contact.name} (type={contact.type}, pub_key={contact.public_key_hex[:16]}...)"
        )
        self._login_dialog_open = True
        builder = Gtk.Builder.new_from_resource(
            "/page/codeberg/sesivany/Meshy/ui/room-login-dialog.ui"
        )
        dialog = builder.get_object("dialog")
        dialog.set_title(_("Login to {}").format(contact.name))
        password_entry = builder.get_object("password_entry")
        save_switch = builder.get_object("save_switch")
        spinner = builder.get_object("spinner")
        status_label = builder.get_object("status_label")
        login_btn = builder.get_object("login_btn")

        # Pre-fill saved password
        if self._window.storage:
            saved = self._window.storage.get_room_password(contact.public_key_hex)
            if saved:
                password_entry.set_text(saved)
                save_switch.set_active(True)

        timeout_id = [None]

        def on_login_result(success, login_timestamp=None, is_admin=True, acl_perms=3):
            spinner.set_spinning(False)
            if timeout_id[0]:
                GLib.source_remove(timeout_id[0])
                timeout_id[0] = None
            if success:
                status_label.set_label(_("Login successful"))
                # Save or remove password
                if self._window.storage:
                    if save_switch.get_active():
                        self._window.storage.save_room_password(
                            contact.public_key_hex, password_entry.get_text()
                        )
                    else:
                        self._window.storage.remove_room_password(contact.public_key_hex)
                self._window.mark_room_logged_in(contact.public_key_hex, acl_perms)
                # Immediately sync to fetch pending room messages
                self._window.send_frame(build_sync_next_message())
                dialog.close()
                if repeater:
                    self._window.show_repeater(contact, login_timestamp, is_admin)
                else:
                    self._window.show_chat(contact)
            else:
                status_label.set_label(_("Login failed — wrong password"))
                status_label.remove_css_class("dim-label")
                status_label.add_css_class("error")
                login_btn.set_sensitive(True)

        def on_timeout():
            spinner.set_spinning(False)
            status_label.set_label(_("Login timed out"))
            self._window.stop_login()
            login_btn.set_sensitive(True)
            timeout_id[0] = None
            return False

        def on_retry():
            status_label.set_label(_("Retrying via flood..."))

        def on_login_clicked(*args):
            log.info(f"Login button clicked for {contact.name}")
            password = password_entry.get_text()
            log.info(f"Password length: {len(password)}")
            spinner.set_spinning(True)
            status_label.set_label(_("Logging in..."))
            status_label.remove_css_class("error")
            status_label.add_css_class("dim-label")
            login_btn.set_sensitive(False)
            timeout_id[0] = GLib.timeout_add(15000, on_timeout)
            log.info(f"Calling send_login with pub_key={contact.public_key.hex()[:16]}...")
            self._window.send_login(contact.public_key, password, on_login_result, on_retry)

        login_btn.connect("clicked", on_login_clicked)
        password_entry.connect("apply", on_login_clicked)

        def on_dialog_closed(d):
            self._login_dialog_open = False
            self._window.stop_login()
            if timeout_id[0]:
                GLib.source_remove(timeout_id[0])

        dialog.connect("closed", on_dialog_closed)
        dialog.present(self._window)

    def _sort_key(self, c: Contact):
        """Compute sort key for a contact based on current sort setting."""
        return contact_sort_key(c, self._current_sort, self._favorites_first)

    def update_contacts(self, contacts: list[Contact]):
        sorted_contacts = sorted(contacts, key=self._sort_key)
        new_keys = [c.public_key_hex for c in sorted_contacts]
        old_keys = list(self._contact_rows.keys())

        # Fast path: same contacts in same order — update in-place
        if new_keys == old_keys:
            for contact in sorted_contacts:
                key = contact.public_key_hex
                row = self._contact_rows.get(key)
                if row:
                    row.set_title(GLib.markup_escape_text(contact.name))
                    row.set_subtitle(contact.path_label)
                    row._contact = contact
            self._total_contacts = len(contacts)
            self._update_status_count()
            return

        # Full rebuild: contact set or order changed
        self._full_rebuild(sorted_contacts)

    def _full_rebuild(self, sorted_contacts: list[Contact]):
        """Remove all rows and recreate from scratch."""
        selected_row = self._list_box.get_selected_row()
        selected_key = (
            selected_row._contact.public_key_hex
            if selected_row and hasattr(selected_row, "_contact")
            else None
        )

        clear_children(self._list_box)
        self._contact_rows.clear()

        new_selected = None
        for contact in sorted_contacts:
            row = self._create_contact_row(contact)
            self._list_box.append(row)
            self._contact_rows[contact.public_key_hex] = row
            if contact.public_key_hex == selected_key:
                new_selected = row

        if new_selected:
            self._list_box.select_row(new_selected)

        self._total_contacts = len(sorted_contacts)
        self._update_status_count()

    def _create_contact_row(self, contact: Contact) -> Gtk.ListBoxRow:
        row = Adw.ActionRow(
            title=GLib.markup_escape_text(contact.name),
            subtitle=contact.path_label,
        )
        row._contact = contact

        # Type icon with favorite star
        icon_name = {
            ContactType.CHAT: "avatar-default-symbolic",
            ContactType.REPEATER: "repeater-symbolic",
            ContactType.ROOM: "user-home-symbolic",
            ContactType.SENSOR: "weather-clear-symbolic",
        }.get(contact.type, "avatar-default-symbolic")
        prefix_box = Gtk.Box(spacing=2)
        star = Gtk.Image.new_from_icon_name("starred-symbolic")
        star.set_pixel_size(10)
        if not contact.is_favorite:
            star.set_opacity(0)
        prefix_box.append(star)
        prefix_box.append(Gtk.Image.new_from_icon_name(icon_name))
        row.add_prefix(prefix_box)

        # Unread badge — visible by default when count > 0, hidden on hover
        count = self._unread_counts.get(contact.public_key_hex, 0)
        unread_badge = Gtk.Label(label=str(count) if count else "")
        unread_badge.add_css_class("unread-badge")
        unread_badge.set_valign(Gtk.Align.CENTER)
        unread_badge.set_visible(count > 0)
        row.add_suffix(unread_badge)
        self._unread_dots[contact.public_key_hex] = unread_badge

        # "More" button + hover behavior + long press
        info_btn = Gtk.Button(icon_name="view-more-symbolic", valign=Gtk.Align.CENTER)
        info_btn.add_css_class("flat")
        info_btn.set_visible(False)
        on_detail = lambda *_, r=row: self._show_contact_detail(r._contact)
        info_btn.connect("clicked", on_detail)
        row.add_suffix(info_btn)
        _add_hover_swap(
            row,
            info_btn,
            unread_badge,
            lambda: self._unread_counts.get(contact.public_key_hex, 0),
            on_detail,
        )

        row.set_activatable(True)
        return row

    def mark_unread(self, public_key_hex: str, unread: bool):
        """Show or hide the unread badge for a contact."""
        if unread:
            self._unread_keys.add(public_key_hex)
            self._unread_counts[public_key_hex] = self._unread_counts.get(public_key_hex, 0) + 1
        else:
            self._unread_keys.discard(public_key_hex)
            self._unread_counts[public_key_hex] = 0
        if public_key_hex in self._unread_dots:
            badge = self._unread_dots[public_key_hex]
            count = self._unread_counts.get(public_key_hex, 0)
            badge.set_label(str(count) if count else "")
            badge.set_visible(count > 0)
        self._window.update_nav_unread_contacts()

    def _get_visible_rows(self):
        """Return visible rows in display order."""
        rows = []
        row = self._list_box.get_first_child()
        while row:
            if row.get_visible() and hasattr(row, "_contact"):
                rows.append(row)
            row = row.get_next_sibling()
        return rows

    def navigate(self, direction: int, unread_only: bool = False):
        """Move selection up (-1) or down (+1). If unread_only, skip to next unread."""
        rows = self._get_visible_rows()
        if not rows:
            return
        if unread_only:
            rows = [r for r in rows if r._contact.public_key_hex in self._unread_keys]
            if not rows:
                return
        selected = self._list_box.get_selected_row()
        if selected and selected in rows:
            idx = rows.index(selected)
            idx = (idx + direction) % len(rows)
        else:
            idx = 0 if direction > 0 else len(rows) - 1
        self._list_box.select_row(rows[idx])
        rows[idx].grab_focus()

    def _on_path_discovery(self, contact: Contact, btn: Gtk.Button):
        """Send a path discovery request for a contact."""
        btn.set_sensitive(False)
        self._discover_path_label.set_label(_("Searching..."))

        timeout_id = [None]

        def _on_response(data):
            if timeout_id[0]:
                GLib.source_remove(timeout_id[0])
                timeout_id[0] = None
            self._window.stop_path_discovery()
            btn.set_sensitive(True)
            # Parse the PATH_DISCOVERY_RESPONSE (0x8D)
            # Format: [code][reserved][prefix×6][out_path_len][out_path...][in_path_len][in_path...]
            try:
                i = 2  # skip code + reserved
                i += 6  # skip prefix
                opl_byte = data[i]
                i += 1
                opl_hlen = ((opl_byte & 0xC0) >> 6) + 1
                opl = opl_byte & 0x3F
                out_hops = []
                for _j in range(opl):
                    out_hops.append(data[i : i + opl_hlen].hex().upper())
                    i += opl_hlen
                ipl_byte = data[i]
                i += 1
                ipl_hlen = ((ipl_byte & 0xC0) >> 6) + 1
                ipl = ipl_byte & 0x3F
                in_hops = []
                for _j in range(ipl):
                    in_hops.append(data[i : i + ipl_hlen].hex().upper())
                    i += ipl_hlen

                if opl == 0 and ipl == 0:
                    self._discover_path_label.set_label(_("Direct"))
                else:
                    parts = []
                    if out_hops:
                        parts.append(",".join(out_hops))
                    self._discover_path_label.set_label(
                        " → ".join(parts) if parts else ngettext("%d hop", "%d hops", opl) % opl
                    )

                    # Apply discovered outbound path to the contact
                    if out_hops:
                        path_bytes = b"".join(bytes.fromhex(h) for h in out_hops)
                        hash_mode = opl_hlen - 1
                        path_len_byte = (hash_mode << 6) | (opl & 0x3F)
                        self._window.set_contact_path(contact, path_len_byte, path_bytes)
                        self._window.show_toast(f"Path set: {','.join(out_hops)}")
            except (IndexError, ValueError) as e:
                import logging

                logging.getLogger(__name__).warning(f"Path discovery parse error: {e}")
                self._discover_path_label.set_label(_("Path found"))
            self._window.refresh_contacts()

        def _on_timeout():
            self._window.stop_path_discovery()
            btn.set_sensitive(True)
            self._discover_path_label.set_label(_("No response"))
            timeout_id[0] = None
            return False

        timeout_id[0] = GLib.timeout_add(30000, _on_timeout)
        self._window.send_path_discovery(contact.public_key, _on_response)

    def _on_get_advert_path(self, contact: Contact):
        """Get and display the inbound advertisement path for a contact."""
        self._advert_path_label.set_label(_("Loading..."))

        # Set a timeout in case the response never comes (error consumed elsewhere)
        timeout_id = [None]

        def _on_response(result):
            if timeout_id[0]:
                GLib.source_remove(timeout_id[0])
                timeout_id[0] = None
            if not result:
                self._advert_path_label.set_label(_("No path cached"))
                return
            hops = result.get("hops", [])
            path_len = result.get("path_length", -1)
            if path_len < 0 or not hops:
                self._advert_path_label.set_label(_("Flood"))
            elif path_len == 0:
                self._advert_path_label.set_label(_("Direct"))
            else:
                self._advert_path_label.set_label(" → ".join(hops))

        def _on_timeout():
            self._window.set_advert_path_callback(None)
            self._advert_path_label.set_label(_("Not supported"))
            timeout_id[0] = None
            return False

        timeout_id[0] = GLib.timeout_add(3000, _on_timeout)
        self._window.get_advert_path(contact.public_key, _on_response)

    def _ping_contact(self, contact: Contact, btn: Gtk.Button):
        """Ping a repeater/room via trace path to get RTT and SNR."""
        # Trace protocol only supports 1B and 2B hashes (power-of-2 encoding)
        if self._window.device_info.path_hash_mode > 1:
            self._window.show_toast(_("Ping is not supported with 3-byte path hashes"))
            return

        import time

        btn.set_sensitive(False)
        start = time.monotonic()
        timeout_id = [None]

        hash_width = self._window.device_info.path_hash_mode + 1
        hop_hash = contact.public_key[:hash_width]

        def on_trace(result):
            if timeout_id[0]:
                GLib.source_remove(timeout_id[0])
                timeout_id[0] = None
            rtt = (time.monotonic() - start) * 1000
            snr_values = result.get("snr_values", [])
            parts = [format_trip_time(int(rtt))]
            if len(snr_values) >= 1:
                parts.append(f"SNR out: {format_number(snr_values[0], sign=True)} dB")
            if len(snr_values) >= 2:
                parts.append(f"SNR back: {format_number(snr_values[-1], sign=True)} dB")
            msg = _("Ping {}: {}").format(contact.name, ", ".join(parts))
            self._window.show_toast(msg, timeout=5)
            btn.set_sensitive(True)

        def on_device_timeout(timeout_ms):
            if timeout_id[0]:
                GLib.source_remove(timeout_id[0])
            timeout_id[0] = GLib.timeout_add(timeout_ms, on_timeout)

        def on_timeout():
            self._window.stop_trace_path()
            self._window.show_toast(_("Ping {}: timed out").format(contact.name), timeout=5)
            btn.set_sensitive(True)
            timeout_id[0] = None
            return False

        timeout_id[0] = GLib.timeout_add(15000, on_timeout)
        trace_flags = self._window.device_info.path_hash_mode
        self._window.send_trace_path(hop_hash, on_trace, on_device_timeout, flags=trace_flags)

    def _request_telemetry(self, contact: Contact, row: Adw.ActionRow):
        """Request and display telemetry from a contact."""
        from meshy.protocol import parse_cayenne_lpp

        row.set_subtitle(_("Requesting..."))

        timeout_id = [None]

        def on_timeout():
            row.set_subtitle(_("No response (timed out)"))
            timeout_id[0] = None
            return False

        def on_response(lpp_data):
            if timeout_id[0]:
                GLib.source_remove(timeout_id[0])
                timeout_id[0] = None
            if not lpp_data:
                row.set_subtitle(_("No telemetry data"))
                return
            entries = parse_cayenne_lpp(lpp_data)
            if not entries:
                row.set_subtitle(_("No telemetry data"))
                return
            self._show_telemetry_dialog(contact, entries)
            row.set_subtitle(_("Telemetry received"))

        timeout_id[0] = GLib.timeout_add(15000, on_timeout)
        self._window.get_telemetry(contact.public_key, on_response, contact_type=contact.type)

    @staticmethod
    def _battery_percent(volts: float) -> int:
        from meshy.models import battery_percent_from_mv

        return battery_percent_from_mv(int(volts * 1000))

    def _show_telemetry_dialog(self, contact: Contact, entries: list[dict]):
        """Show a dialog with parsed telemetry data and optional map."""
        from meshy.protocol import LPP_GPS, LPP_VOLTAGE

        # Check for GPS data
        gps_entry = next((e for e in entries if e["type"] == LPP_GPS), None)

        builder = Gtk.Builder.new_from_resource(
            "/page/codeberg/sesivany/Meshy/ui/telemetry-dialog.ui"
        )
        dialog = builder.get_object("dialog")
        content = builder.get_object("content")
        dialog.set_title(_("Telemetry — {}").format(contact.name))
        dialog.set_content_height(550 if gps_entry else 400)

        channels = {}
        for entry in entries:
            channels.setdefault(entry["channel"], []).append(entry)

        for ch in sorted(channels):
            group = Adw.PreferencesGroup(title=_("Channel {}").format(ch))

            for entry in channels[ch]:
                val = entry["value"]
                if isinstance(val, dict):
                    alt_str = (
                        f", alt {format_number(val['alt'], 0)} m" if abs(val["alt"]) > 0.01 else ""
                    )
                    subtitle = f"{val['lat']:.4f}, {val['lon']:.4f}{alt_str}"
                elif entry["type"] == LPP_VOLTAGE and ch == 1:
                    pct = self._battery_percent(val)
                    subtitle = f"{pct}% ({format_number(val, 2)} V)"
                elif isinstance(val, float):
                    subtitle = f"{format_number(val, 2)} {entry['unit']}"
                else:
                    subtitle = f"{val} {entry['unit']}"

                title = _("Battery") if entry["type"] == LPP_VOLTAGE and ch == 1 else entry["name"]
                row = Adw.ActionRow(title=title, subtitle=subtitle)
                group.add(row)

            content.append(group)

        # Show map if GPS data is present
        if gps_entry:
            try:
                from meshy.views import create_shumate_map, deregister_map_widget

                lat = gps_entry["value"]["lat"]
                lon = gps_entry["value"]["lon"]

                from meshy.views.map_view import _MARKER_COLORS, _MARKER_ICONS, _SELF_COLOR, MapView

                map_widget, marker_layer, viewport = create_shumate_map(
                    zoom_level=14, lat=lat, lon=lon
                )
                map_widget.set_vexpand(False)
                map_widget.set_size_request(-1, 250)

                r, g, b = _MARKER_COLORS.get(contact.type, (0.5, 0.5, 0.5))
                icon_name = _MARKER_ICONS.get(contact.type, "avatar-default-symbolic")
                marker = MapView.create_marker(r, g, b, icon_name, contact.name, lat, lon)
                marker_layer.add_marker(marker)

                # Show our companion's position too
                lats, lons = [lat], [lon]
                si = self._window.self_info
                self_lat = si.get("adv_lat", 0.0)
                self_lon = si.get("adv_lon", 0.0)
                if abs(self_lat) > 1e-6 or abs(self_lon) > 1e-6:
                    self_name = si.get("name", "") or _("My Device")
                    self_marker = MapView.create_marker(
                        *_SELF_COLOR, "avatar-default-symbolic", self_name, self_lat, self_lon
                    )
                    marker_layer.add_marker(self_marker)
                    lats.append(self_lat)
                    lons.append(self_lon)

                # Fit viewport to show all markers
                from meshy.views.map_view import MapView

                MapView.fit_viewport(viewport, lats, lons)

                map_frame = Gtk.Frame()
                map_frame.set_child(map_widget)
                content.append(map_frame)

            except Exception as e:
                import logging

                log = logging.getLogger(__name__)
                log.error(f"Failed to create map widget for telemetry display: {e}", exc_info=True)
                # Show coordinates as text instead
                lat = gps_entry["value"]["lat"]
                lon = gps_entry["value"]["lon"]
                coords_label = Gtk.Label()
                # Avoid emoji on macOS due to CoreText rendering crashes (Bus error 10)
                from meshy.platforms import is_macos

                if is_macos():
                    coords_label.set_markup(
                        f"<b>GPS Coordinates:</b>\nLat: {lat:.6f}, Lon: {lon:.6f}"
                    )
                else:
                    coords_label.set_markup(f"<b>GPS Coordinates:</b>\n📍 {lat:.6f}, {lon:.6f}")
                coords_label.set_margin_top(12)
                coords_label.set_margin_bottom(12)
                content.append(coords_label)

        if gps_entry:
            dialog.connect("closed", lambda _d: deregister_map_widget(map_widget))
        dialog.present(self._window)

    def _show_path_on_map(self, contact: Contact, hop_contacts: list, hop_prefixes: list = None):
        """Show the established path to a contact in a map dialog."""
        from meshy.views.map_view import (
            _MARKER_COLORS,
            _MARKER_ICONS,
            _SELF_COLOR,
            _UNKNOWN_COLOR,
            MapView,
            companion_too_far,
        )

        device = self._window.device_info
        self_lat = getattr(device, "latitude", None)
        self_lon = getattr(device, "longitude", None)
        has_self = self_lat and self_lon and (abs(self_lat) > 1e-6 or abs(self_lon) > 1e-6)

        # Build full hop list including unknowns: (lat, lon, contact, prefix, snr)
        raw_hops = []

        for i, hop_contact in enumerate(hop_contacts):
            prefix = hop_prefixes[i] if hop_prefixes and i < len(hop_prefixes) else None
            if hop_contact and hop_contact.has_location:
                raw_hops.append(
                    (hop_contact.latitude, hop_contact.longitude, hop_contact, prefix, None)
                )
            else:
                raw_hops.append((None, None, hop_contact, prefix, None))

        if contact.has_location:
            raw_hops.append((contact.latitude, contact.longitude, contact, None, None))

        if has_self and not companion_too_far(self_lat, self_lon, raw_hops):
            raw_hops.insert(0, (self_lat, self_lon, None, None, None))

        hops = MapView.interpolate_unknown_hops(raw_hops)

        if not any(h[0] is not None for h in hops):
            return

        dialog, map_widget, marker_layer, viewport = MapView.open_map_dialog(
            self._window, title=_("Path to {}").format(contact.name)
        )

        map_widget.get_map().remove_layer(marker_layer)
        path_layer = MapView.create_dashed_path_layer(viewport)
        map_widget.get_map().add_layer(path_layer)
        map_widget.get_map().add_layer(marker_layer)

        lats, lons = [], []
        hop_num = 0
        for lat, lon, hop_contact, prefix, _snr in hops:
            if lat is None:
                continue
            node = Shumate.Marker()
            node.set_location(lat, lon)
            path_layer.add_node(node)

            if hop_contact is None and prefix is None:
                # Self/device marker
                r, g, b = _SELF_COLOR
                icon_name = "network-wireless-symbolic"
                name = device.name or _("My Device")
                badge = ""
            elif hop_contact is None or not hop_contact.has_location:
                # Unknown/interpolated hop
                r, g, b = _UNKNOWN_COLOR
                icon_name = "repeater-symbolic"
                name = prefix or _("Unknown")
                hop_num += 1
                badge = str(hop_num)
            else:
                r, g, b = _MARKER_COLORS.get(hop_contact.type, (0.5, 0.5, 0.5))
                icon_name = _MARKER_ICONS.get(hop_contact.type, "avatar-default-symbolic")
                name = hop_contact.name
                hop_num += 1
                badge = str(hop_num)

            widget = MapView._build_marker_widget(r, g, b, icon_name, "", badge_text=badge)
            widget.set_tooltip_text(name)

            if hop_contact is not None:
                click = Gtk.GestureClick()
                click.connect(
                    "pressed", lambda g, n, x, y, c=hop_contact: self._show_contact_detail(c)
                )
                widget.add_controller(click)
            elif prefix is not None:
                click = Gtk.GestureClick()
                click.connect(
                    "pressed",
                    lambda g, n, x, y, w=widget, nm=name, la=lat, lo=lon: (
                        MapView.show_marker_popover(
                            w, nm, la, lo, contact_type=_("Unknown repeater"), interpolated=True
                        )
                    ),
                )
                widget.add_controller(click)

            hop_marker = Shumate.Marker()
            hop_marker.set_child(widget)
            hop_marker.set_location(lat, lon)
            marker_layer.add_marker(hop_marker)

            lats.append(lat)
            lons.append(lon)

        MapView.fit_viewport(viewport, lats, lons)
        dialog.present(self._window)

    def _show_on_map(self, contact: Contact):
        """Show a contact's location in a map dialog."""
        from meshy.views.map_view import _MARKER_COLORS, _MARKER_ICONS, MapView

        dialog, map_widget, marker_layer, viewport = MapView.open_map_dialog(
            self._window, title=contact.name
        )

        r, g, b = _MARKER_COLORS.get(contact.type, (0.5, 0.5, 0.5))
        icon_name = _MARKER_ICONS.get(contact.type, "avatar-default-symbolic")
        marker = MapView.create_marker(
            r, g, b, icon_name, contact.name, contact.latitude, contact.longitude
        )
        marker_layer.add_marker(marker)

        viewport.set_zoom_level(14)
        viewport.set_location(contact.latitude, contact.longitude)
        dialog.present(self._window)

    def _show_contact_detail(self, contact: Contact):
        """Show contact detail dialog."""
        from meshy.views.contact_detail_dialog import ContactDetailDialog

        dialog = ContactDetailDialog(self, contact)
        dialog.present(self._window)
