"""Reference picker overlay widget."""

from __future__ import annotations

import importlib
from typing import Any


def _load_static_base() -> type[Any]:
    try:
        return importlib.import_module("textual.widgets").Static
    except Exception:  # pragma: no cover

        class _FallbackStatic:
            def __init__(self, *args: object, **kwargs: object) -> None:
                self._text = ""

            def update(self, text: str) -> None:
                self._text = text

        return _FallbackStatic


_StaticBase = _load_static_base()


class ReferencePickerOverlay(_StaticBase):
    """Simple overlay displaying reference suggestions."""

    def __init__(self, *args: object, **kwargs: object) -> None:
        super().__init__(*args, **kwargs)
        self._visible = False
        self._text = ""

    @property
    def visible(self) -> bool:
        """Return whether the overlay is currently visible."""

        return self._visible

    def hide(self) -> None:
        """Hide the overlay and clear its content."""

        self._visible = False
        self._text = ""
        self.update("")

    def set_suggestions(self, query: str, suggestions: list[str]) -> None:
        if not query:
            self.hide()
            return

        lines = [f"@{query}"]
        if not suggestions:
            lines.append("  (no matches)")
        else:
            for item in suggestions[:10]:
                lines.append(f"  {item}")

        self._visible = True
        self._text = "\n".join(lines)
        self.update(self._text)
