#include "mainFrame.h"

#include "core/context.h"
#include "uiEventHandler/uiEventHandler.h"


using namespace std;
using namespace gui;
//--------------------------------------------------------------
/* Constructor */
MainFrame::MainFrame(core::Context &ctx)
  : wxFrame(nullptr, wxID_ANY, "KwaFr")
  , Node(ctx.eventBus)
  , m_ctx(ctx)
{
  // Initialization
  const auto minSize = wxSize(1024, 768);
  SetSize(minSize);
  SetMinSize(minSize);

  // Creating controls
  createControls();

  // Post initialization
  m_uiEventHandler = make_unique<UiEventHandler>(*this, ctx);
}
//--------------------------------------------------------------
/* Default destructor */
MainFrame::~MainFrame()
{
  m_uiEventHandler.reset();
}
//--------------------------------------------------------------
/* Creating controls */
void MainFrame::createControls()
{
  m_browser = wxWebView::New(this,
                             wxID_ANY,
                             "http://localhost:5173",
                             wxDefaultPosition,
                             wxDefaultSize,
                             wxWebViewBackendEdge);
  if (!m_browser)
    throw runtime_error("Failed to create WebView control");

  Bind(wxEVT_WEBVIEW_SCRIPT_MESSAGE_RECEIVED, &MainFrame::onScriptMessage, this);

  // Register the script message handler with the same name used in the web view
  m_browser->AddScriptMessageHandler("ui_bridge_handler");

  // Controls positioning
  const auto mainSizer = new wxBoxSizer(wxVERTICAL);
  mainSizer->Add(m_browser, wxSizerFlags(1).Expand());

  SetSizer(mainSizer);
}
//--------------------------------------------------------------
/* UI message handler */
void MainFrame::onScriptMessage(wxWebViewEvent &event)
{
  try
  {
    // Get the message data as a JSON object and pass it to the
    // UI event handler
    const auto data = json::parse(event.GetString());
    m_uiEventHandler->processIncomingMessage(data);
  }
  catch (const std::exception &e)
  {
    cerr << "Error parsing message from WebView: " << e.what() << "\n"
         << event.GetString() << "\n"
         << endl;
  }
}
//--------------------------------------------------------------

/* export const useRequirementsStore = defineStore('requirements', () => {
  const requirements = ref<Requirement[]>([
    {
      reference: 'REQ-101',
      uuid: '9f6c4f7a-9d2f-4dc0-8fa2-7ac2d79b0c11',
      title: 'Full requirement traceability',
      status: 'Approved',
      priority: 'Critical',
      owner: 'Claire Martin',
      progress: 86,
      dueDate: 'May 21, 2026',
      description:
        'Each requirement must be linked to a source, a validation status, and the design or test artifacts that depend on it.',
      rationale:
        'The team must be able to audit functional decisions, reduce scope drift, and prepare compliance reviews.',
      acceptanceCriteria: [
        'The source for each requirement is visible in the detail view.',
        'The validation status is recorded in the history.',
        'Links to related test cases are available from the detail panel.',
      ],
      impactedModules: ['Backlog', 'Tests', 'Audit', 'Reporting'],
      blockers: [],
      notes: 'Plan a PDF export for milestone reviews.',
      stakeholders: ['QA Team', 'Product Owner', 'Tech Lead'],
      flexibility: 'Low—cannot alter core traceability chain without major rework',
      tolerances: 'Maximum 5% of requirements can have incomplete artifact links',
    },
    {
      reference: 'REQ-102',
      uuid: '8aa1b6f5-2378-4c47-b490-2b92c7ee8b5f',
      title: 'Business status management',
      status: 'In Review',
      priority: 'High',
      owner: 'Julien Bernard',
      progress: 54,
      dueDate: 'May 24, 2026',
      description:
        'The product must provide consistent statuses to track a requirement from creation to delivery.',
      rationale:
        'Business and product teams do not use the same words at the same time. A stable naming scheme avoids ambiguity.',
      acceptanceCriteria: [
        'Statuses are readable at a glance.',
        'The status list is consistent across the application.',
        'Blocked items are visually highlighted.',
      ],
      impactedModules: ['Workflow', 'Detail', 'Dashboard'],
      blockers: ['Final label approval from the Product Owner'],
      notes: 'Can be connected to workflow transitions later.',
      stakeholders: ['Product Managers', 'Business Analysts', 'UI Team'],
      flexibility: 'Medium—limited room for additional statuses, current labels are firm',
      tolerances: 'Terminology must match approved glossary within 95% confidence',
    },
    {
      reference: 'REQ-103',
      uuid: '6f99d740-67bf-4a1f-88f2-4fd947f9cb8a',
      title: 'Fast search and filtering',
      status: 'Draft',
      priority: 'Medium',
      owner: 'Nadia Petit',
      progress: 28,
      dueDate: 'May 29, 2026',
      description:
        'Users must be able to find a requirement by title, reference, owner, or functional keyword.',
      rationale:
        'Once the project reaches a moderate volume, manual navigation becomes too expensive and slows down reviews.',
      acceptanceCriteria: [
        'Search filters the list instantly.',
        'The number of visible items remains clear.',
        'No result state is displayed explicitly.',
      ],
      impactedModules: ['Sidebar', 'Search', 'Performance'],
      blockers: ['Definition of the priority search criteria'],
      notes: 'To be extended with type and batch filters.',
      stakeholders: ['End Users', 'Performance Team'],
      flexibility: 'High—can adapt search algorithm and UI patterns to user feedback',
      tolerances: 'Search response time must stay under 200ms for 99% of queries',
    },
    {
      reference: 'REQ-104',
      uuid: 'f47e5f4a-c54d-46c9-8fef-f5f56e5e4d7a',
      title: 'Delivery scope by release',
      status: 'Blocked',
      priority: 'Critical',
      owner: 'Sophie Laurent',
      progress: 41,
      dueDate: 'May 31, 2026',
      description:
        'Each requirement must be linked to a target release so batch and delivery decisions can be prepared.',
      rationale:
        'Decision makers need a concise view to balance load and dependencies across releases.',
      acceptanceCriteria: [
        'The target release appears in the interface.',
        'Blocked requirements are visually identified.',
        'The delivery batch is readable in the detail view.',
      ],
      impactedModules: ['Release', 'Roadmap', 'Governance'],
      blockers: ['Architecture decision pending'],
      notes: 'To be linked to a milestone calendar.',
      stakeholders: ['Release Manager', 'Governance Board', 'Architects'],
      flexibility: 'Low—release scope is constrained by business commitments',
      tolerances: '100% of deliverables must link to a release before code freeze',
    },
  ]) */