import React from 'react';
import { describe, it, expect } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import BlogWizard from '@/features/blog/components/BlogWizard';

function makeGenerateResult() {
  return {
    blog: [
      { language: 'de', content: 'Hallo Welt' },
      { language: 'en', content: 'Hello World' },
    ],
  };
}

describe('BlogWizard presenter - generating flow', () => {
  it('topic + image upload -> generate -> result view', async () => {
    const user = userEvent.setup();

    const onNewBlog = vi.fn().mockResolvedValue('b1');
    const onUploadFile = vi.fn().mockResolvedValue({ success: true, url: 'https://example.com/img.jpg' });
    const onGenerate = vi.fn().mockResolvedValue(makeGenerateResult());

    render(
      <BlogWizard
        onComplete={() => {}}
        onNewBlog={onNewBlog}
        onUploadFile={onUploadFile}
        onGenerate={onGenerate}
      />
    );

    // Enter topic
    const topicInput = screen.getByPlaceholderText(/Zum Beispiel:/i);
    await user.type(topicInput, 'Mein Thema');

    // Upload image using hidden file input
    const fileInput = screen.getByRole('textbox', { hidden: true }) as HTMLInputElement | null;
    // The hidden input is not a textbox role; safer: query by input type
    const realFileInput = document.querySelector('input[type="file"]') as HTMLInputElement;
    const file = new File([new Uint8Array([1,2,3])], 'image.jpg', { type: 'image/jpeg' });
    fireEvent.change(realFileInput, { target: { files: [file] } });

    // After upload, the uploaded image should be part of the grid (selectedMediaId is set by upload handler)
    // Click Generate
    const generateBtn = await screen.findByRole('button', { name: /Beitrag generieren/i });
    await user.click(generateBtn);

    // Loading state then result view with textarea
    const textarea = await screen.findByRole('textbox');
    expect((textarea as HTMLTextAreaElement).value).toContain('Hallo Welt');

    // Ensure generators were called with expected arguments
    expect(onNewBlog).toHaveBeenCalled();
    expect(onGenerate).toHaveBeenCalled();
  });
});
