#pragma once

#include <optional>
#include <string>
#include <functional>

#include "lumacs/buffer.hpp" // For Position and Range

namespace lumacs {

// Forward declarations
class EditorCore;

/// @brief Manages incremental search (ISearch) state and logic.
/// Extracted from MinibufferManager to follow single responsibility principle.
class ISearchManager {
public:
    explicit ISearchManager(EditorCore& core);

    /// @brief Start an incremental search.
    /// @param forward True for forward search, false for backward.
    void start(bool forward);

    /// @brief Stop the incremental search and optionally restore cursor.
    /// @param restore_cursor If true, restore cursor to position before search started.
    void stop(bool restore_cursor = true);

    /// @brief Update the search with a new query string.
    /// @param query The search query.
    void update(const std::string& query);

    /// @brief Move to the next match in the current search direction.
    void next_match();

    /// @brief Move to the previous match (opposite of current direction).
    void previous_match();

    /// @brief Check if incremental search is currently active.
    [[nodiscard]] bool is_active() const { return active_; }

    /// @brief Get the current match range, if any.
    [[nodiscard]] std::optional<Range> match_range() const { return match_range_; }

    /// @brief Check if the last search failed to find a match.
    [[nodiscard]] bool is_failed() const { return failed_; }

    /// @brief Get the current search direction.
    [[nodiscard]] bool is_forward() const { return direction_forward_; }

    /// @brief Get the last search query.
    [[nodiscard]] const std::string& last_query() const { return last_query_; }

    /// @brief Set the search direction.
    void set_direction(bool forward) { direction_forward_ = forward; }

    /// @brief Set the prompt text (used for message display).
    void set_prompt(const std::string& prompt) { prompt_text_ = prompt; }

private:
    EditorCore& core_;

    bool active_ = false;
    bool direction_forward_ = true;
    bool failed_ = false;

    std::optional<Range> match_range_;
    std::optional<Position> start_cursor_;  // Cursor position when search started
    std::string last_query_;
    std::string prompt_text_;
};

} // namespace lumacs
