import React from 'react';
import { describe, it, expect } from 'vitest';
import { render, screen } 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 - result save & publish', () => {
  it('saves changes and can publish afterwards', 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());
    const onUpdate = vi.fn().mockResolvedValue({ saved: true });
    const onPublish = vi.fn().mockResolvedValue({ ok: true });

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

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

    // Upload image
    const fileInput = document.querySelector('input[type="file"]') as HTMLInputElement;
    const file = new File([new Uint8Array([1,2,3])], 'image.jpg', { type: 'image/jpeg' });
    await user.upload(fileInput, file);

    // Generate to go to result view
    const generateBtn = await screen.findByRole('button', { name: /Beitrag generieren/i });
    await user.click(generateBtn);

    // Edit textarea to create changes
    const textarea = await screen.findByRole('textbox');
    await user.clear(textarea);
    await user.type(textarea, 'Geänderter Inhalt');

    // Save changes button should be enabled now, click save
    const saveBtn = screen.getByRole('button', { name: /Änderungen speichern/i });
    await user.click(saveBtn);
    expect(onUpdate).toHaveBeenCalled();

    // After save, Publish button should be enabled; click publish in SocialSchedulingPanel
    const publishBtn = screen.getByRole('button', { name: /Veröffentlichen/i });
    await user.click(publishBtn);
    expect(onPublish).toHaveBeenCalled();
  });
});
