import sys
import os
import logging
import time
from collections import OrderedDict

try:
    from PyQt5.QtWidgets import (QLabel, QLineEdit, QPushButton, QGraphicsView, QGraphicsScene, QHBoxLayout, 
                                 QSpinBox, QFileDialog, QMessageBox, QSlider, QInputDialog, QColorDialog, 
                                 QDockWidget, QListWidget, QListWidgetItem, QVBoxLayout, QToolButton, QComboBox, 
                                 QTextEdit, QDialog, QCheckBox, QProgressBar)
    from PyQt5.QtCore import (Qt, QRunnable, QThreadPool, pyqtSignal, QPropertyAnimation, QEasingCurve, QTimer, 
                              QSize, QPointF, QRectF, QEvent, QMimeData, QParallelAnimationGroup, QSettings,
                              QObject)  # Adicionado QObject aqui
    from PyQt5.QtGui import (QPixmap, QImage, QKeySequence, QFont, QPen, QColor, QPainter, QIcon, QTextDocument,
                             QCursor, QBrush)
    import fitz
    import qtawesome as qta
    from PyQt5.QtWidgets import QShortcut
    import multiprocessing
except ImportError as e:
    print(f"Erro: Uma dependência está faltando - {e}")
    print("Instale as dependências com:")
    print("  python -m pip install PyQt5 PyMuPDF qtawesome")
    sys.exit(1)

class PriorityPageRenderer(QRunnable):
    class Signals(QObject):  # Agora QObject está definido
        pageRendered = pyqtSignal(QPixmap, int)
        errorOccurred = pyqtSignal(str)

    def __init__(self, doc, page_num, zoom_level, priority=0):
        super().__init__()
        self.doc = doc
        self.page_num = page_num
        self.zoom_level = zoom_level
        self.priority = priority
        self.signals = self.Signals()
        self.setAutoDelete(True)

    def run(self):
        try:
            pix = self.doc[self.page_num].get_pixmap(matrix=fitz.Matrix(self.zoom_level, self.zoom_level))
            img = QImage(pix.samples, pix.width, pix.height, pix.stride, QImage.Format_RGB888)
            pixmap = QPixmap.fromImage(img.scaled(img.width() // 2, img.height() // 2, Qt.KeepAspectRatio, Qt.SmoothTransformation))
            self.signals.pageRendered.emit(pixmap, self.page_num)
        except Exception as e:
            self.signals.errorOccurred.emit(str(e))
  class QProgressIndicator(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.angle = 0
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.update)
        self.setStyleSheet("background: transparent;")

    def resizeEvent(self, event):
        size = min(self.parent().width(), self.parent().height()) // 10
        self.setFixedSize(size, size)

    def startAnimation(self):
        self.timer.start(30)

    def stopAnimation(self):
        self.timer.stop()

    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        theme = self.parent().parent().parent().theme if hasattr(self.parent().parent().parent(), 'theme') else "dark"
        pen = QPen(QColor(74, 144, 226) if theme == "dark" else QColor(52, 152, 219), 5)
        painter.setPen(pen)
        margin = self.width() // 5
        painter.drawArc(margin, margin, self.width() - 2 * margin, self.height() - 2 * margin, self.angle * 16, 180 * 16)
        self.angle = (self.angle + 30) % 360

class SettingsDialog(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("Configurações")
        self.settings = QSettings("PDFViewer", "Settings")
        layout = QVBoxLayout(self)
        self.zoom_spin = QSpinBox()
        self.zoom_spin.setRange(20, 200)
        self.zoom_spin.setValue(self.settings.value("initial_zoom", 50, type=int))
        layout.addWidget(QLabel("Zoom Inicial (%):"))
        layout.addWidget(self.zoom_spin)
        self.animations_check = QCheckBox("Ativar Animações")
        self.animations_check.setChecked(self.settings.value("animations_enabled", True, type=bool))
        layout.addWidget(self.animations_check)
        save_btn = QPushButton("Salvar")
        save_btn.clicked.connect(self._save_settings)
        layout.addWidget(save_btn)

    def _save_settings(self):
        self.settings.setValue("initial_zoom", self.zoom_spin.value())
        self.settings.setValue("animations_enabled", self.animations_check.isChecked())
        self.accept()

class PDFViewerWidget(BaseTabWidget):
    def __init__(self, tab_name, parent=None):
        super().__init__(tab_name, parent)
        self.doc = None
        self.current_page = 0
        self.settings = QSettings("PDFViewer", "Settings")
        self.zoom_level = self.settings.value("initial_zoom", 50, type=int) / 100
        self.animations_enabled = self.settings.value("animations_enabled", True, type=bool)
        self.page_cache = OrderedDict()
        self.max_cache_size = max(5, os.sysconf('SC_PAGE_SIZE') // (1024 * 1024))
        self.max_cache_bytes = 150 * 1024 * 1024  # 150MB
        self.current_cache_bytes = 0
        self.max_file_size_mb = 50
        self.thread_pool = QThreadPool()
        self.thread_pool.setMaxThreadCount(max(2, multiprocessing.cpu_count() // 2))
        self.pending_page = None
        self.annotations = {}  # {page_num: [(type, data), ...]} ex: ("text", (text, font_size, color, (x, y)))
        self.status_history = []
        self.navigation_history = []
        self.navigation_index = -1
        self.bookmarks = set()
        self.search_results = []
        self.search_index = -1
        self.navigation_direction = 0
        self.drawing_mode = None  # "rect", "highlight", None

        self.status_bar = QWidget(self)
        self.status_layout = QHBoxLayout(self.status_bar)
        self.status_label = QLabel()
        self.status_label.setTextInteractionFlags(Qt.TextSelectableByMouse)
        self.status_label.linkActivated.connect(self._open_file_location)
        self.status_expand_btn = QToolButton()
        self.status_expand_btn.setIcon(qta.icon("fa5s.history", options=[{'scale_factor': 1.2}]))
        self.status_expand_btn.clicked.connect(self._show_status_history)
        self.status_layout.addWidget(self.status_label)
        self.status_layout.addWidget(self.status_expand_btn)
        self._update_theme()
        self.layout.addWidget(self.status_bar, 6, 0, 1, 2)

        self.progress_bar = QProgressBar(self)
        self.progress_bar.setVisible(False)
        self.layout.addWidget(self.progress_bar, 7, 0, 1, 2)

        self._create_widgets()

    def _update_theme(self):
        theme = self.parent().parent().theme if hasattr(self.parent().parent(), 'theme') else "dark"
        self.status_bar.setStyleSheet(f"background: qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 {'#2E2E2E' if theme == 'dark' else '#E0E0E0'}, stop:1 {'#3B3B3B' if theme == 'dark' else '#F0F0F0'}); padding: 2px; border-radius: 4px;")
        self.page_label.setStyleSheet(f"color: {'#E0E0E0' if theme == 'dark' else '#2E2E2E'};")
        self.page_spin.setStyleSheet(f"background: {'#3B4A6A' if theme == 'dark' else '#FFFFFF'}; color: {'#E0E0E0' if theme == 'dark' else '#2E2E2E'}; border: 1px solid {'#4A5A78' if theme == 'dark' else '#BDC3C7'};")

    def _create_widgets(self):
        self.layout.addWidget(QLabel("Arquivo PDF para visualizar *"), 0, 0)
        self.input_file = QLineEdit()
        self.input_file.setReadOnly(True)
        self.input_file.setToolTip("Arraste um PDF aqui ou clique em 'Procurar' (Ctrl+Roda para zoom, Ctrl+F para buscar).")
        self.input_file.setAccessibleName("Campo de entrada de arquivo")
        browse_btn = QPushButton("Procurar")
        browse_btn.setIcon(qta.icon("fa5s.folder-open", options=[{'scale_factor': 1.2}]))
        browse_btn.clicked.connect(lambda: self._browse(self.input_file, mode="file", title="Selecionar PDF"))
        browse_btn.setStyleSheet("background: qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 #4A90E2, stop:1 #357ABD); color: white; border: none; padding: 5px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.2); &:hover {background: qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 #5AA0F2, stop:1 #458ACD);}")
        self.layout.addWidget(self.input_file, 1, 0)
        self.layout.addWidget(browse_btn, 1, 1)

        self.preview = QGraphicsView()
        self.scene = QGraphicsScene()
        self.preview.setScene(self.scene)
        self.preview.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.preview.setMinimumSize(400, 500)
        self.preview.setStyleSheet("border: 1px solid #4A5A78; background: #3B4A6A; box-shadow: 0 4px 12px rgba(0,0,0,0.3); border-radius: 4px;")
        self.preview.setDragMode(QGraphicsView.ScrollHandDrag)
        self.preview.viewport().installEventFilter(self)
        self.preview.setAcceptDrops(True)
        self.layout.addWidget(self.preview, 2, 0, 1, 2)

        self.loading_indicator = QProgressIndicator(self.preview)
        self.loading_indicator.setVisible(False)

        self.thumbnails_dock = QDockWidget("Miniaturas", self.parent().parent())
        self.thumbnails_list = QListWidget()
        self.thumbnails_list.setMinimumWidth(150)
        self.thumbnails_list.itemClicked.connect(self._thumbnail_clicked)
        self.thumbnails_list.verticalScrollBar().valueChanged.connect(self._load_more_thumbnails)
        self.thumbnails_dock.setWidget(self.thumbnails_list)
        self.thumbnails_dock.setVisible(False)
        self.parent().parent().addDockWidget(Qt.LeftDockWidgetArea, self.thumbnails_dock)

        self.layout.addWidget(QLabel("Senha (se protegido):"), 3, 0)
        self.password_input = QLineEdit()
        self.password_input.setEchoMode(QLineEdit.Password)
        self.password_input.setToolTip("Digite a senha se o PDF for protegido.")
        self.password_input.setAccessibleName("Campo de senha")
        self.password_input.textChanged.connect(self._update_page)
        self.layout.addWidget(self.password_input, 4, 0, 1, 2)

        nav_layout = QHBoxLayout()
        self.page_label = QLabel("Página 1 de 1")
        self.page_label.setFont(QFont("Segoe UI", 10))

        self.page_spin = QSpinBox()
        self.page_spin.setRange(1, 1)
        self.page_spin.setToolTip("Digite ou selecione o número da página (Setas para navegar).")
        self.page_spin.setAccessibleName("Seleção de página")
        self.page_spin.valueChanged.connect(self._update_page_navigation)

        back_btn = QPushButton()
        back_btn.setIcon(qta.icon("fa5s.arrow-left", options=[{'scale_factor': 1.2}]))
        back_btn.setToolTip("Voltar na navegação (Ctrl+B)")
        back_btn.clicked.connect(self._go_back)
        back_btn.setStyleSheet("background: qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 #4A90E2, stop:1 #357ABD); color: white; border: none; padding: 5px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.2); &:hover {background: qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 #5AA0F2, stop:1 #458ACD);}")

        forward_btn = QPushButton()
        forward_btn.setIcon(qta.icon("fa5s.arrow-right", options=[{'scale_factor': 1.2}]))
        forward_btn.setToolTip("Avançar na navegação (Ctrl+N)")
        forward_btn.clicked.connect(self._go_forward)
        forward_btn.setStyleSheet("background: qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 #4A90E2, stop:1 #357ABD); color: white; border: none; padding: 5px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.2); &:hover {background: qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 #5AA0F2, stop:1 #458ACD);}")

        prev_btn = QPushButton()
        prev_btn.setIcon(qta.icon("fa5s.chevron-left", options=[{'scale_factor': 1.2}]))
        prev_btn.setToolTip("Página anterior (Seta Esquerda)")
        prev_btn.clicked.connect(lambda: self.page_spin.setValue(self.page_spin.value() - 1))
        prev_btn.setStyleSheet("background: qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 #4A90E2, stop:1 #357ABD); color: white; border: none; padding: 5px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.2); &:hover {background: qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 #5AA0F2, stop:1 #458ACD);}")

        next_btn = QPushButton()
        next_btn.setIcon(qta.icon("fa5s.chevron-right", options=[{'scale_factor': 1.2}]))
        next_btn.setToolTip("Próxima página (Seta Direita)")
        next_btn.clicked.connect(lambda: self.page_spin.setValue(self.page_spin.value() + 1))
        next_btn.setStyleSheet("background: qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 #4A90E2, stop:1 #357ABD); color: white; border: none; padding: 5px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.2); &:hover {background: qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 #5AA0F2, stop:1 #458ACD);}")

        zoom_slider = QSlider(Qt.Horizontal)
        zoom_slider.setRange(20, 200)
        zoom_slider.setValue(int(self.zoom_level * 100))
        zoom_slider.setToolTip("Ajuste o nível de zoom (Ctrl+Roda ou gestos).")
        zoom_slider.valueChanged.connect(lambda v: self._adjust_zoom((v / 100) - self.zoom_level))
        zoom_slider.setStyleSheet("QSlider::groove:horizontal {height: 4px; background: #4A5A78; border-radius: 2px;} QSlider::handle:horizontal {width: 12px; background: #4A90E2; border-radius: 6px; box-shadow: 0 2px 4px rgba(0,0,0,0.2);}")

        annotate_btn = QPushButton()
        annotate_btn.setIcon(qta.icon("fa5s.pencil-alt", options=[{'scale_factor': 1.2}]))
        annotate_btn.setToolTip("Adicionar/editar anotações (Ctrl+A)")
        annotate_btn.clicked.connect(self._manage_annotations)
        annotate_btn.setStyleSheet("background: qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 #4A90E2, stop:1 #357ABD); color: white; border: none; padding: 5px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.2); &:hover {background: qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 #5AA0F2, stop:1 #458ACD);}")

        export_btn = QPushButton("Exportar")
        export_btn.setIcon(qta.icon("fa5s.download", options=[{'scale_factor': 1.2}]))
        export_btn.setToolTip("Exportar página/PDF (Ctrl+E)")
        export_btn.clicked.connect(self._export_page)
        export_btn.setStyleSheet("background: qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 #4A90E2, stop:1 #357ABD); color: white; border: none; padding: 5px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.2); &:hover {background: qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 #5AA0F2, stop:1 #458ACD);}")

        thumbnails_btn = QPushButton()
        thumbnails_btn.setIcon(qta.icon("fa5s.th-list", options=[{'scale_factor': 1.2}]))
        thumbnails_btn.setToolTip("Alternar miniaturas")
        thumbnails_btn.clicked.connect(lambda: self.thumbnails_dock.setVisible(not self.thumbnails_dock.isVisible()))
        thumbnails_btn.setStyleSheet("background: qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 #4A90E2, stop:1 #357ABD); color: white; border: none; padding: 5px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.2); &:hover {background: qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 #5AA0F2, stop:1 #458ACD);}")

        search_btn = QPushButton()
        search_btn.setIcon(qta.icon("fa5s.search", options=[{'scale_factor': 1.2}]))
        search_btn.setToolTip("Pesquisar texto (Ctrl+F)")
        search_btn.clicked.connect(self._search_text)
        search_btn.setStyleSheet("background: qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 #4A90E2, stop:1 #357ABD); color: white; border: none; padding: 5px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.2); &:hover {background: qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 #5AA0F2, stop:1 #458ACD);}")

        search_next_btn = QPushButton()
        search_next_btn.setIcon(qta.icon("fa5s.chevron-down", options=[{'scale_factor': 1.2}]))
        search_next_btn.setToolTip("Próximo resultado da busca")
        search_next_btn.clicked.connect(self._go_to_next_search_result)
        search_next_btn.setStyleSheet("background: qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 #4A90E2, stop:1 #357ABD); color: white; border: none; padding: 5px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.2); &:hover {background: qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 #5AA0F2, stop:1 #458ACD);}")

        bookmark_btn = QPushButton()
        bookmark_btn.setIcon(qta.icon("fa5s.star", options=[{'scale_factor': 1.2}]))
        bookmark_btn.setToolTip("Adicionar/remover favorito (Ctrl+D)")
        bookmark_btn.clicked.connect(self._toggle_bookmark)
        bookmark_btn.setStyleSheet("background: qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 #4A90E2, stop:1 #357ABD); color: white; border: none; padding: 5px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.2); &:hover {background: qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 #5AA0F2, stop:1 #458ACD);}")

        mode_combo = QComboBox()
        mode_combo.addItems(["Página Única", "Leitura Contínua"])
        mode_combo.setToolTip("Alternar modo de visualização")
        mode_combo.currentIndexChanged.connect(self._toggle_view_mode)
        mode_combo.setStyleSheet(f"background: {'#3B4A6A' if self.parent().parent().theme == 'dark' else '#FFFFFF'}; color: {'#E0E0E0' if self.parent().parent().theme == 'dark' else '#2E2E2E'}; border: 1px solid {'#4A5A78' if self.parent().parent().theme == 'dark' else '#BDC3C7'}; padding: 2px; border-radius: 4px;")

        settings_btn = QPushButton()
        settings_btn.setIcon(qta.icon("fa5s.cog", options=[{'scale_factor': 1.2}]))
        settings_btn.setToolTip("Configurações")
        settings_btn.clicked.connect(self._show_settings)
        settings_btn.setStyleSheet("background: qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 #4A90E2, stop:1 #357ABD); color: white; border: none; padding: 5px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.2); &:hover {background: qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 #5AA0F2, stop:1 #458ACD);}")

        nav_layout.addWidget(back_btn)
        nav_layout.addWidget(forward_btn)
        nav_layout.addWidget(prev_btn)
        nav_layout.addWidget(self.page_spin)
        nav_layout.addWidget(self.page_label)
        nav_layout.addWidget(next_btn)
        nav_layout.addWidget(QLabel("Zoom:"))
        nav_layout.addWidget(zoom_slider)
        nav_layout.addWidget(annotate_btn)
        nav_layout.addWidget(export_btn)
        nav_layout.addWidget(thumbnails_btn)
        nav_layout.addWidget(search_btn)
        nav_layout.addWidget(search_next_btn)
        nav_layout.addWidget(bookmark_btn)
        nav_layout.addWidget(mode_combo)
        nav_layout.addWidget(settings_btn)
        self.layout.addLayout(nav_layout, 5, 0, 1, 2)

        QShortcut(QKeySequence(Qt.Key_Left), self, lambda: self.page_spin.setValue(self.page_spin.value() - 1))
        QShortcut(QKeySequence(Qt.Key_Right), self, lambda: self.page_spin.setValue(self.page_spin.value() + 1))
        QShortcut(QKeySequence("Ctrl+F"), self, self._search_text)
        QShortcut(QKeySequence("Ctrl+E"), self, self._export_page)
        QShortcut(QKeySequence("Ctrl+A"), self, self._manage_annotations)
        QShortcut(QKeySequence("Ctrl+D"), self, self._toggle_bookmark)
        QShortcut(QKeySequence("Ctrl+B"), self, self._go_back)
        QShortcut(QKeySequence("Ctrl+N"), self, self._go_forward)

    def eventFilter(self, obj, event):
        if obj == self.preview.viewport():
            if event.type() == QEvent.Wheel and event.modifiers() == Qt.ControlModifier:
                self._zoom_event(event)
                return True
            elif event.type() == QEvent.Gesture:
                gesture = event.gesture(Qt.PinchGesture)
                if gesture and gesture.state() == Qt.GestureUpdated:
                    scale = gesture.scaleFactor()
                    if scale != 1.0:
                        self._adjust_zoom((scale - 1.0) * 0.5)
                    return True
            elif event.type() == QEvent.Drop:
                mime = event.mimeData()
                if mime.hasUrls():
                    url = mime.urls()[0].toLocalFile()
                    if url.endswith(".pdf"):
                        self.input_file.setText(url)
                        self._update_page()
                return True
            elif event.type() == QEvent.MouseButtonPress and self.drawing_mode:
                self._draw_shape(event)
                return True
        return super().eventFilter(obj, event)

    def dragEnterEvent(self, event):
        if event.mimeData().hasUrls():
            event.acceptProposedAction()

    def _zoom_event(self, event):
        zoom_in = event.angleDelta().y() > 0
        self._adjust_zoom(0.1 if zoom_in else -0.1)

    def _adjust_zoom(self, delta):
        self.zoom_level = min(max(self.zoom_level + delta, 0.2), 2.0)
        self.page_cache.clear()
        self.current_cache_bytes = 0
        self._update_page()

    def _manage_annotations(self):
        if not self.doc or self.current_page >= len(self.doc):
            self._set_status("Erro: Nenhuma página válida para anotar.", "#FF5555")
            return
        options = ["Adicionar Texto", "Desenhar Retângulo", "Destacar Texto", "Editar Anotação", "Remover Anotação"]
        choice, ok = QInputDialog.getItem(self, "Gerenciar Anotações", "Escolha uma ação:", options, 0, False)
        if not ok:
            return
        if choice == "Adicionar Texto":
            text, ok = QInputDialog.getText(self, "Anotação", "Digite o texto da anotação:")
            if ok and text:
                font_size, ok = QInputDialog.getInt(self, "Tamanho da Fonte", "Digite o tamanho da fonte:", 12, 6, 72)
                if ok:
                    color = QColorDialog.getColor(initial=QColor(255, 0, 0), parent=self, title="Escolha a cor da anotação")
                    if color.isValid():
                        x, ok_x = QInputDialog.getInt(self, "Posição X", "Digite a coordenada X:", 50, 0, 1000)
                        y, ok_y = QInputDialog.getInt(self, "Posição Y", "Digite a coordenada Y:", 50, 0, 1000)
                        if ok_x and ok_y:
                            if self.current_page not in self.annotations:
                                self.annotations[self.current_page] = []
                            self.annotations[self.current_page].append(("text", (text, font_size, color, (x, y))))
                            try:
                                self.doc[self.current_page].insert_text((x, y), text, fontsize=font_size, color=(color.red()/255, color.green()/255, color.blue()/255))
                                self._update_page()
                                self._set_status("Anotação de texto adicionada.", "#55FF55")
                            except Exception as e:
                                self._set_status(f"Erro ao adicionar texto: {e}", "#FF5555")
        elif choice in ["Desenhar Retângulo", "Destacar Texto"]:
            self.drawing_mode = "rect" if choice == "Desenhar Retângulo" else "highlight"
            self.preview.setCursor(QCursor(Qt.CrossCursor))
            self._set_status(f"Clique na página para adicionar {choice.lower()}.", "#55FF55")
        elif choice == "Editar Anotação" and self.current_page in self.annotations and self.annotations[self.current_page]:
            items = [f"{i+1}: {ann[1][0] if ann[0] == 'text' else ann[0]}" for i, ann in enumerate(self.annotations[self.current_page])]
            item, ok = QInputDialog.getItem(self, "Editar Anotação", "Selecione a anotação:", items, 0, False)
            if ok:
                idx = int(item.split(":")[0]) - 1
                ann_type, ann_data = self.annotations[self.current_page][idx]
                if ann_type == "text":
                    text, ok = QInputDialog.getText(self, "Editar Texto", "Digite o novo texto:", QLineEdit.Normal, ann_data[0])
                    if ok:
                        font_size, ok = QInputDialog.getInt(self, "Tamanho da Fonte", "Digite o novo tamanho:", ann_data[1], 6, 72)
                        if ok:
                            color = QColorDialog.getColor(initial=ann_data[2], parent=self, title="Escolha a nova cor")
                            if color.isValid():
                                x, ok_x = QInputDialog.getInt(self, "Posição X", "Digite a nova coordenada X:", ann_data[3][0], 0, 1000)
                                y, ok_y = QInputDialog.getInt(self, "Posição Y", "Digite a nova coordenada Y:", ann_data[3][1], 0, 1000)
                                if ok_x and ok_y:
                                    try:
                                        self.doc[self.current_page].delete_annotation(self.doc[self.current_page].annotations()[idx])
                                        self.annotations[self.current_page][idx] = ("text", (text, font_size, color, (x, y)))
                                        self.doc[self.current_page].insert_text((x, y), text, fontsize=font_size, color=(color.red()/255, color.green()/255, color.blue()/255))
                                        self._update_page()
                                        self._set_status("Anotação editada com sucesso.", "#55FF55")
                                    except Exception as e:
                                        self._set_status(f"Erro ao editar anotação: {e}", "#FF5555")
        elif choice == "Remover Anotação" and self.current_page in self.annotations and self.annotations[self.current_page]:
            items = [f"{i+1}: {ann[1][0] if ann[0] == 'text' else ann[0]}" for i, ann in enumerate(self.annotations[self.current_page])]
            item, ok = QInputDialog.getItem(self, "Remover Anotação", "Selecione a anotação:", items, 0, False)
            if ok:
                idx = int(item.split(":")[0]) - 1
                try:
                    if self.annotations[self.current_page][idx][0] == "text":
                        self.doc[self.current_page].delete_annotation(self.doc[self.current_page].annotations()[idx])
                    del self.annotations[self.current_page][idx]
                    if not self.annotations[self.current_page]:
                        del self.annotations[self.current_page]
                    self._update_page()
                    self._set_status("Anotação removida com sucesso.", "#55FF55")
                except Exception as e:
                    self._set_status(f"Erro ao remover anotação: {e}", "#FF5555")

    def _draw_shape(self, event):
        if not self.drawing_mode or not self.doc:
            return
        pos = self.preview.mapToScene(event.pos())
        x, y = int(pos.x()), int(pos.y())
        if self.drawing_mode == "rect":
            color = QColorDialog.getColor(initial=QColor(255, 0, 0), parent=self, title="Escolha a cor do retângulo")
            if color.isValid():
                if self.current_page not in self.annotations:
                    self.annotations[self.current_page] = []
                self.annotations[self.current_page].append(("rect", (color, (x, y, x + 100, y + 50))))
                self._update_page()
                self._set_status("Retângulo adicionado.", "#55FF55")
        elif self.drawing_mode == "highlight":
            if self.current_page not in self.annotations:
                self.annotations[self.current_page] = []
            self.annotations[self.current_page].append(("highlight", (QColor(255, 255, 0, 100), (x, y, x + 150, y + 20))))
            self._update_page()
            self._set_status("Destaque adicionado.", "#55FF55")
        self.drawing_mode = None
        self.preview.setCursor(QCursor(Qt.ArrowCursor))

    def _export_page(self):
        if not self.doc or self.current_page >= len(self.doc):
            self._set_status("Erro: Nenhuma página válida para exportar.", "#FF5555")
            return
        options = ["Página Atual (PDF)", "Página Atual (PNG)", "Página Atual (JPG)", "Faixa de Páginas (PDF)", "PDF Completo", "Salvar Alterações no Original"]
        choice, ok = QInputDialog.getItem(self, "Exportar", "Escolha uma opção:", options, 0, False)
        if not ok:
            return
        if choice == "Faixa de Páginas (PDF)":
            start, ok1 = QInputDialog.getInt(self, "Início", "Página inicial:", 1, 1, len(self.doc))
            end, ok2 = QInputDialog.getInt(self, "Fim", "Página final:", len(self.doc), start, len(self.doc))
            if not (ok1 and ok2):
                return
        if choice != "Salvar Alterações no Original":
            output_file, _ = QFileDialog.getSaveFileName(self, "Salvar Como", "", "PDF Files (*.pdf);;PNG Files (*.png);;JPG Files (*.jpg)")
            if not output_file:
                return
            output_dir = os.path.dirname(output_file)
            if not os.access(output_dir, os.W_OK):
                self._set_status(f"Erro: Sem permissão para gravar em {output_dir}.", "#FF5555")
                return
        self.progress_bar.setVisible(True)
        self.progress_bar.setRange(0, 100)
        self.progress_bar.setValue(0)
        if "PDF" in choice or choice == "Salvar Alterações no Original":
            pdf_writer = fitz.open()
            if choice == "Página Atual (PDF)":
                pdf_writer.insert_pdf(self.doc, from_page=self.current_page, to_page=self.current_page)
            elif choice == "Faixa de Páginas (PDF)":
                pdf_writer.insert_pdf(self.doc, from_page=start-1, to_page=end-1)
            else:
                pdf_writer.insert_pdf(self.doc)
            if choice == "Salvar Alterações no Original":
                self.doc.save(self.doc.name, incremental=True)
                self._set_status(f"Alterações salvas em: {self.doc.name}", "#55FF55")
            else:
                if not output_file.endswith(".pdf"):
                    output_file += ".pdf"
                pdf_writer.save(output_file)
                self._set_status(f"Exportado para: <a href='file://{output_file}'>{output_file}</a>", "#55FF55")
            pdf_writer.close()
        else:
            pix = self.doc[self.current_page].get_pixmap(matrix=fitz.Matrix(self.zoom_level, self.zoom_level))
            img = QImage(pix.samples, pix.width, pix.height, pix.stride, QImage.Format_RGB888)
            painter = QPainter(img)
            if self.current_page in self.annotations:
                for ann_type, ann_data in self.annotations[self.current_page]:
                    if ann_type == "text":
                        text, font_size, color, (x, y) = ann_data
                        painter.setFont(QFont("Segoe UI", font_size))
                        painter.setPen(QPen(color))
                        painter.drawText(x, y, text)
                    elif ann_type == "rect":
                        color, (x1, y1, x2, y2) = ann_data
                        painter.setPen(QPen(color, 2))
                        painter.drawRect(x1, y1, x2 - x1, y2 - y1)
                    elif ann_type == "highlight":
                        color, (x1, y1, x2, y2) = ann_data
                        painter.fillRect(x1, y1, x2 - x1, y2 - y1, color)
            painter.end()
            if "PNG" in choice:
                if not output_file.endswith(".png"):
                    output_file += ".png"
                img.save(output_file, "PNG")
            elif "JPG" in choice:
                if not output_file.endswith(".jpg"):
                    output_file += ".jpg"
                img.save(output_file, "JPG", 85)
            self._set_status(f"Exportado para: <a href='file://{output_file}'>{output_file}</a>", "#55FF55")
        self.progress_bar.setValue(100)
        QTimer.singleShot(1000, lambda: self.progress_bar.setVisible(False))

    def _open_file_location(self, link):
        if link.startswith("file://"):
            os.startfile(link[7:])  # Windows-specific; use QDesktopServices.openUrl for cross-platform

    def _search_text(self):
        if not self.doc:
            self._set_status("Erro: Nenhum PDF carregado.", "#FF5555")
            return
        text, ok = QInputDialog.getText(self, "Pesquisar", "Digite o texto a procurar:")
        if ok and text:
            self.search_results = []
            self.progress_bar.setVisible(True)
            self.progress_bar.setRange(0, len(self.doc))
            for i in range(len(self.doc)):
                found = self.doc[i].search_for(text)
                if found:
                    self.search_results.append((i, found))
                self.progress_bar.setValue(i + 1)
            self.progress_bar.setVisible(False)
            if self.search_results:
                self.search_index = 0
                self._go_to_search_result()
                self._set_status(f"{len(self.search_results)} ocorrências de '{text}' encontradas.", "#55FF55")
            else:
                self._set_status(f"Texto '{text}' não encontrado.", "#FF5555")

    def _go_to_search_result(self):
        if self.search_results and 0 <= self.search_index < len(self.search_results):
            page_num, rects = self.search_results[self.search_index]
            self.page_spin.setValue(page_num + 1)
            self._update_page()
            self._highlight_search_results(rects)

    def _go_to_next_search_result(self):
        if self.search_results:
            self.search_index = (self.search_index + 1) % len(self.search_results)
            self._go_to_search_result()

    def _highlight_search_results(self, results):
        for rect in results:
            item = self.scene.addRect(rect.x0, rect.y0, rect.width, rect.height, QPen(Qt.NoPen), QColor(255, 255, 0, 100))
            QTimer.singleShot(3000, lambda: self.scene.removeItem(item))

    def _toggle_view_mode(self, index):
        if index == 1:  # Leitura Contínua
            self.preview.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
            self.preview.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
            self._render_continuous_view()
        else:  # Página Única
            self.preview.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
            self.preview.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded)
            self._update_page()

    def _render_continuous_view(self):
        self.scene.clear()
        total_height = 0
        for i in range(max(0, self.current_page - 2), min(len(self.doc), self.current_page + 3)):
            pix = self.doc[i].get_pixmap(matrix=fitz.Matrix(self.zoom_level, self.zoom_level))
            pixmap = QPixmap.fromImage(QImage(pix.samples, pix.width, pix.height, pix.stride, QImage.Format_RGB888))
            item = self.scene.addPixmap(pixmap.scaled(pixmap.width(), pixmap.height(), Qt.KeepAspectRatio))
            item.setPos(0, total_height)
            total_height += pixmap.height() * self.zoom_level
            if i == self.current_page:
                self.preview.ensureVisible(item)
            if i in self.annotations:
                for ann_type, ann_data in self.annotations[i]:
                    if ann_type == "text":
                        text, font_size, color, (x, y) = ann_data
                        ann_item = self.scene.addText(text, QFont("Segoe UI", font_size))
                        ann_item.setDefaultTextColor(color)
                        ann_item.setPos(x, y + item.pos().y())
                    elif ann_type == "rect":
                        color, (x1, y1, x2, y2) = ann_data
                        self.scene.addRect(x1, y1 + item.pos().y(), x2 - x1, y2 - y1, QPen(color, 2))
                    elif ann_type == "highlight":
                        color, (x1, y1, x2, y2) = ann_data
                        self.scene.addRect(x1, y1 + item.pos().y(), x2 - x1, y2 - y1, QPen(Qt.NoPen), color)

    def _update_page_navigation(self, value):
        new_page = min(max(value - 1, 0), len(self.doc) - 1) if self.doc else 0
        self.navigation_direction = 1 if new_page > self.current_page else -1
        if self.current_page != new_page:
            if self.navigation_index < len(self.navigation_history) - 1:
                self.navigation_history = self.navigation_history[:self.navigation_index + 1]
            self.navigation_history.append(new_page)
            self.navigation_index = len(self.navigation_history) - 1
        self.current_page = new_page
        self._update_page()

    def _go_back(self):
        if self.navigation_index > 0:
            self.navigation_index -= 1
            self.current_page = self.navigation_history[self.navigation_index]
            self.page_spin.setValue(self.current_page + 1)
            self._update_page()

    def _go_forward(self):
        if self.navigation_index < len(self.navigation_history) - 1:
            self.navigation_index += 1
            self.current_page = self.navigation_history[self.navigation_index]
            self.page_spin.setValue(self.current_page + 1)
            self._update_page()

    def _toggle_bookmark(self):
        if not self.doc:
            return
        if self.current_page in self.bookmarks:
            self.bookmarks.remove(self.current_page)
            self._set_status(f"Página {self.current_page + 1} removida dos favoritos.", "#55FF55")
        else:
            self.bookmarks.add(self.current_page)
            self._set_status(f"Página {self.current_page + 1} adicionada aos favoritos.", "#55FF55")
        self._update_thumbnail_highlight()

    def _update_page(self):
        if not self.input_file.text() or not os.path.exists(self.input_file.text()):
            self.scene.clear()
            self.scene.addText("Arquivo não encontrado.")
            self.page_spin.setMaximum(1)
            self.page_label.setText("Página 1 de 1")
            self.thumbnails_dock.setVisible(False)
            return

        file_size = os.path.getsize(self.input_file.text()) / (1024 * 1024)
        if file_size > self.max_file_size_mb and QMessageBox.question(self, "Aviso", f"O PDF é grande (>{self.max_file_size_mb}MB). Pode haver lentidão. Continuar?") != QMessageBox.Yes:
            self.input_file.clear()
            return

        try:
            if not self.doc or self.doc.name != self.input_file.text():
                if self.doc:
                    self.thread_pool.waitForDone(1000)
                    for _ in range(3):
                        try:
                            self.doc.close()
                            break
                        except Exception as e:
                            logging.error(f"Falha ao fechar o documento: {e}")
                            self._set_status(f"Erro ao fechar o documento anterior: {e}", "#FF5555")
                            time.sleep(0.5)
                    else:
                        self._set_status("Não foi possível fechar o documento anterior.", "#FF5555")
                self.progress_bar.setVisible(True)
                self.progress_bar.setRange(0, 100)
                self.progress_bar.setValue(0)
                self.doc = fitz.open(self.input_file.text())
                self.page_cache.clear()
                self.current_cache_bytes = 0
                self.annotations.clear()
                self.bookmarks.clear()
                self.navigation_history = [0]
                self.navigation_index = 0
                self._load_initial_thumbnails()
                self.progress_bar.setValue(100)
                QTimer.singleShot(500, lambda: self.progress_bar.setVisible(False))
                if self.doc.is_encrypted:
                    if self.password_input.text():
                        if not self.doc.authenticate(self.password_input.text()):
                            self.scene.clear()
                            self.scene.addText("Senha incorreta.")
                            self.doc.close()
                            self.doc = None
                            self.page_spin.setMaximum(1)
                            self.page_label.setText("Página 1 de 1")
                            return
                    else:
                        self.scene.clear()
                        self.scene.addText("PDF protegido. Forneça uma senha.")
                        self.doc.close()
                        self.doc = None
                        self.page_spin.setMaximum(1)
                        self.page_label.setText("Página 1 de 1")
                        return
            if not self.doc.is_pdf:
                raise ValueError("Arquivo não é um PDF válido.")
            self.page_spin.setMaximum(len(self.doc))
            self.page_label.setText(f"Página {self.current_page + 1} de {len(self.doc)}")
            page_num = self.current_page

            if page_num != self.pending_page:
                self.pending_page = page_num
                if page_num in self.page_cache and not self.page_cache[page_num].isNull():
                    self._display_page(self.page_cache[page_num], page_num)
                else:
                    self._render_page(page_num, priority=1)
                    self._preload_pages()

        except fitz.FileDataError:
            self.scene.clear()
            self.scene.addText("PDF corrompido ou inválido.")
            logging.error(f"Erro ao abrir PDF: {self.input_file.text()}")
        except Exception as e:
            self.scene.clear()
            self.scene.addText(f"Erro: {str(e)}")
            logging.error(f"Erro na visualização: {e}")

    def _render_page(self, page_num, priority=0):
        if page_num not in self.page_cache or self.page_cache[page_num].isNull():
            self.loading_indicator.move(self.preview.width() // 2 - self.loading_indicator.width() // 2, self.preview.height() // 2 - self.loading_indicator.height() // 2)
            self.loading_indicator.setVisible(True)
            self.loading_indicator.startAnimation()
            renderer = PriorityPageRenderer(self.doc, page_num, self.zoom_level, priority)
            renderer.signals.pageRendered.connect(self._display_page)
            renderer.signals.errorOccurred.connect(self._handle_render_error)
            self.thread_pool.start(renderer)

    def _display_page(self, pixmap, page_num):
        if self.pending_page != page_num and self.priority != 1:
            self._add_to_cache(pixmap, page_num)
            return
        self.loading_indicator.stopAnimation()
        self.loading_indicator.setVisible(False)
        self.scene.clear()
        item = self.scene.addPixmap(pixmap.scaled(self.preview.width() - 20, self.preview.height() - 20, Qt.KeepAspectRatio, Qt.SmoothTransformation))
        self.preview.setSceneRect(self.scene.itemsBoundingRect())
        self.preview.fitInView(item, Qt.KeepAspectRatio)
        self.current_page = page_num
        self._add_to_cache(pixmap, page_num)
        if page_num in self.annotations:
            for ann_type, ann_data in self.annotations[page_num]:
                if ann_type == "text":
                    text, font_size, color, (x, y) = ann_data
                    ann_item = self.scene.addText(text, QFont("Segoe UI", font_size))
                    ann_item.setDefaultTextColor(color)
                    ann_item.setPos(x, y)
                elif ann_type == "rect":
                    color, (x1, y1, x2, y2) = ann_data
                    self.scene.addRect(x1, y1, x2 - x1, y2 - y1, QPen(color, 2))
                elif ann_type == "highlight":
                    color, (x1, y1, x2, y2) = ann_data
                    self.scene.addRect(x1, y1, x2 - x1, y2 - y1, QPen(Qt.NoPen), color)
        if self.animations_enabled:
            group = QParallelAnimationGroup()
            pos_anim = QPropertyAnimation(item, b"pos")
            pos_anim.setStartValue(QPointF(-pixmap.width() * self.zoom_level if self.navigation_direction > 0 else pixmap.width() * self.zoom_level, item.pos().y()))
            pos_anim.setEndValue(QPointF(0, item.pos().y()))
            pos_anim.setDuration(300)
            pos_anim.setEasingCurve(QEasingCurve.InOutCubic)
            opacity_anim = QPropertyAnimation(item, b"opacity")
            opacity_anim.setStartValue(0.0)
            opacity_anim.setEndValue(1.0)
            opacity_anim.setDuration(300)
            opacity_anim.setEasingCurve(QEasingCurve.InOutCubic)
            group.addAnimation(pos_anim)
            group.addAnimation(opacity_anim)
            group.start(QPropertyAnimation.DeleteWhenStopped)
        self._set_status(f"Página {page_num + 1} carregada.", "#55FF55")
        self._update_thumbnail_highlight()

    def _add_to_cache(self, pixmap, page_num):
        pixmap_size = pixmap.toImage().byteCount()
        while (self.current_cache_bytes + pixmap_size > self.max_cache_bytes or 
               len(self.page_cache) >= self.max_cache_size) and self.page_cache:
            old_page, old_pixmap = self.page_cache.popitem(last=False)
            self.current_cache_bytes -= old_pixmap.toImage().byteCount()
        if page_num not in self.page_cache:
            self.page_cache[page_num] = pixmap
            self.current_cache_bytes += pixmap_size

    def _preload_pages(self):
        step = self.navigation_direction if self.navigation_direction != 0 else 1
        for i in range(1, 3):
            next_page = self.current_page + step * i
            if 0 <= next_page < len(self.doc) and next_page not in self.page_cache and self.thread_pool.activeThreadCount() < self.thread_pool.maxThreadCount():
                self._render_page(next_page, priority=0)

    def _handle_render_error(self, error):
        self.loading_indicator.stopAnimation()
        self.loading_indicator.setVisible(False)
        self.scene.clear()
        self.scene.addText(f"Erro ao renderizar: {error}")
        logging.error(f"Erro ao renderizar página: {error}")
        self._set_status(f"Erro ao renderizar: {error}", "#FF5555")

    def _load_initial_thumbnails(self):
        self.thumbnails_list.clear()
        for i in range(min(10, len(self.doc))):
            self._add_thumbnail(i)
        self.thumbnails_dock.setVisible(True)

    def _load_more_thumbnails(self, value):
        if not self.doc:
            return
        visible_items = self.thumbnails_list.count()
        if visible_items < len(self.doc) and value > self.thumbnails_list.verticalScrollBar().maximum() - 100:
            for i in range(visible_items, min(visible_items + 10, len(self.doc))):
                if not any(self.thumbnails_list.item(j).data(Qt.UserRole) == i for j in range(self.thumbnails_list.count())):
                    self._add_thumbnail(i)

    def _add_thumbnail(self, page_num):
        pix = self.doc[page_num].get_pixmap(matrix=fitz.Matrix(0.1, 0.1))
        pixmap = QPixmap.fromImage(QImage(pix.samples, pix.width, pix.height, pix.stride, QImage.Format_RGB888))
        item = QListWidgetItem(f"Página {page_num + 1}{' ★' if page_num in self.bookmarks else ''}")
        item.setIcon(QIcon(pixmap))
        item.setData(Qt.UserRole, page_num)
        self.thumbnails_list.addItem(item)
        if page_num == self.current_page:
            item.setBackground(QColor(74, 144, 226, 100))
        elif page_num in self.bookmarks:
            item.setBackground(QColor(255, 215, 0, 100))

    def _update_thumbnail_highlight(self):
        for i in range(self.thumbnails_list.count()):
            item = self.thumbnails_list.item(i)
            page_num = item.data(Qt.UserRole)
            item.setText(f"Página {page_num + 1}{' ★' if page_num in self.bookmarks else ''}")
            item.setBackground(QColor(74, 144, 226, 100) if page_num == self.current_page else QColor(255, 215, 0, 100) if page_num in self.bookmarks else QColor(0, 0, 0, 0))

    def _thumbnail_clicked(self, item):
        page_num = item.data(Qt.UserRole)
        self.page_spin.setValue(page_num + 1)

    def _set_status(self, message, color):
        self.status_label.setText(message)
        self.status_label.setStyleSheet(f"color: {color};")
        self.status_history.append((message, color))
        self.status_bar.setVisible(True)
        QTimer.singleShot(5000, lambda: self.status_bar.setVisible(False) if self.status_label.text() == message else None)

    def _show_status_history(self):
        dialog = QDialog(self)
        dialog.setWindowTitle("Histórico de Status")
        dialog.setStyleSheet("background: #3B4A6A; color: #E0E0E0; border-radius: 4px;")
        layout = QVBoxLayout(dialog)
        text_edit = QTextEdit()
        text_edit.setReadOnly(True)
        text_edit.setStyleSheet("background: #2E2E2E; color: #E0E0E0; border: none; padding: 5px; border-radius: 4px;")
        for msg, color in self.status_history:
            text_edit.append(f"<span style='color:{color}'>{msg}</span>")
        layout.addWidget(text_edit)
        dialog.setLayout(layout)
        dialog.resize(400, 300)
        dialog.exec_()

    def _show_settings(self):
        dialog = SettingsDialog(self)
        if dialog.exec_():
            self.zoom_level = self.settings.value("initial_zoom", 50, type=int) / 100
            self.animations_enabled = self.settings.value("animations_enabled", True, type=bool)
            self._update_page()

    def reset_ui(self):
        super().reset_ui()
        self.thread_pool.waitForDone(1000)
        self.input_file.clear()
        self.password_input.clear()
        self.page_spin.setValue(1)
        self.zoom_level = self.settings.value("initial_zoom", 50, type=int) / 100
        self.current_page = 0
        self.page_cache.clear()
        self.current_cache_bytes = 0
        self.pending_page = None
        self.annotations.clear()
        self.bookmarks.clear()
        self.navigation_history = []
        self.navigation_index = -1
        self.search_results = []
        self.search_index = -1
        self.thread_pool.clear()
        self.page_label.setText("Página 1 de 1")
        self.thumbnails_dock.setVisible(False)
        self.drawing_mode = None
        self.preview.setCursor(QCursor(Qt.ArrowCursor))
        if self.doc:
            for _ in range(3):
                try:
                    self.doc.close()
                    break
                except Exception as e:
                    logging.error(f"Falha ao fechar o documento em reset_ui: {e}")
                    self._set_status(f"Erro ao fechar o documento: {e}", "#FF5555")
                    time.sleep(0.5)
            else:
                self._set_status("Não foi possível fechar o documento.", "#FF5555")
            self.doc = None.  Consegues corrigir e fornecer o código completo funcional?