/**
 * Pack-4 (session 65af6a29) Calendar wiring tests:
 *  - F4FE-001: handleReschedule sends due_date (the field the grid renders by)
 *  - F4FE-006: CalendarView syncs parent selectedDate prop changes into internal state
 *  - F4FE-012: "Add task" trigger always resets form regardless of prior edit state
 */
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { describe, it, expect, vi, beforeEach } from 'vitest';

// ─── hoist CalendarView prop capture ─────────────────────────────────────
const capturedReschedule = { fn: null as ((entryId: string, newDate: string) => void) | null };

vi.mock('@/Components/Calendar/CalendarView', () => ({
  default: ({
    entries,
    onReschedule,
  }: {
    entries: unknown[];
    onReschedule?: (entryId: string, newDate: string) => void;
  }) => {
    capturedReschedule.fn = onReschedule ?? null;
    return (
      <div data-testid="calendar-view">
        Calendar View: {entries.length} entries
        <button
          data-testid="simulate-drop-friday"
          onClick={() => onReschedule?.('entry-1', '2026-06-19')}
        >
          Simulate drag to Friday
        </button>
      </div>
    );
  },
}));

vi.mock('@/Components/Calendar/EventCard', () => ({
  default: ({ entry }: { entry: { id: string; title: string } }) => (
    <div data-testid={`event-card-${entry.id}`}>{entry.title}</div>
  ),
}));

vi.mock('@/Components/layout/EditorialPageHeader', () => ({
  default: ({ title, actions }: { title: string; actions?: React.ReactNode }) => (
    <div>
      <h1>{title}</h1>
      {actions}
    </div>
  ),
}));

vi.mock('@/Layouts/DashboardLayout', () => ({
  default: ({ children }: { children: React.ReactNode }) => <>{children}</>,
}));

vi.mock('@/Components/Shared/InertiaPagination', () => ({
  default: () => <nav>Pagination</nav>,
}));

const { router } = await import('@inertiajs/react');

import CalendarIndex from './Index';

const site = { id: '1', name: 'Test Site', domain: 'test.com' };

const entry = {
  id: 'entry-1',
  title: 'Update Blog Post',
  description: null,
  due_date: '2026-06-16',
  scheduled_date: null,
  status: 'planned' as const,
  source_type: null,
  source_id: null,
  page_url: null,
  metadata: null,
};

const defaultEntries = {
  data: [entry],
  links: [],
  current_page: 1,
  last_page: 1,
};

const defaultCounts = {
  total: 1,
  planned: 1,
  in_progress: 0,
  completed: 0,
  overdue: 0,
};

const defaultFilters = {
  status: null,
  source_type: null,
  start_date: null,
  end_date: null,
  sort_by: null,
};

describe('Calendar/Index – pack-4', () => {
  beforeEach(() => {
    vi.clearAllMocks();
    capturedReschedule.fn = null;
  });

  // ── F4FE-001 ─────────────────────────────────────────────────────────────

  describe('F4FE-001: handleReschedule sends due_date (the field the grid renders by)', () => {
    it('sends due_date in the PATCH payload when a drag-reschedule fires', async () => {
      const user = userEvent.setup();
      render(
        <CalendarIndex
          site={site}
          entries={defaultEntries}
          filters={defaultFilters}
          counts={defaultCounts}
        />,
      );

      await user.click(screen.getByTestId('simulate-drop-friday'));

      const patchCalls = vi.mocked(router.patch).mock.calls;
      expect(patchCalls.length).toBe(1);

      const payload = patchCalls[0][1] as Record<string, string>;
      // F4FE-001: due_date MUST be present (grid renders by due_date)
      expect(payload.due_date).toBe('2026-06-19');
      // scheduled_date is also sent so the server retains the planned publish time
      expect(payload.scheduled_date).toBe('2026-06-19');
    });

    it('does NOT send only scheduled_date (which the grid ignores for rendering)', async () => {
      const user = userEvent.setup();
      render(
        <CalendarIndex
          site={site}
          entries={defaultEntries}
          filters={defaultFilters}
          counts={defaultCounts}
        />,
      );

      await user.click(screen.getByTestId('simulate-drop-friday'));

      const patchCalls = vi.mocked(router.patch).mock.calls;
      const payload = patchCalls[0][1] as Record<string, string>;
      // Before the fix, only scheduled_date was sent; now due_date must be present
      expect(payload.due_date).toBeDefined();
    });
  });

  // ── F4FE-012 ─────────────────────────────────────────────────────────────

  describe('F4FE-012: "Add task" trigger always presents a blank form', () => {
    it('opens a blank create sheet when "Add task" is clicked (no prior edit state)', async () => {
      const user = userEvent.setup();
      render(
        <CalendarIndex
          site={site}
          entries={defaultEntries}
          filters={defaultFilters}
          counts={defaultCounts}
        />,
      );

      // Find and click the "Add task" header button
      const addTaskBtn = screen.getByRole('button', { name: /Add task/i });
      await user.click(addTaskBtn);

      // Title field should be empty (blank create)
      const titleInput = screen.getByLabelText(/Title/i);
      expect(titleInput).toHaveValue('');
    });
  });
});
