File size: 9,968 Bytes
4595df6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
// Elementos do DOM
const comicForm = document.getElementById('comic-form');
const loadingSection = document.getElementById('loading');
const resultSection = document.getElementById('result');
const comicViewer = document.getElementById('comic-viewer');
const newStoryBtn = document.getElementById('new-story-btn');
const generateBtn = document.getElementById('generate-btn');

// Função para mostrar/ocultar seções
function toggleSections(showLoading = false, showResult = false) {
    document.querySelector('.generator-form').style.display = 
        (!showLoading && !showResult) ? 'block' : 'none';
    loadingSection.style.display = showLoading ? 'block' : 'none';
    resultSection.style.display = showResult ? 'block' : 'none';
}

// Função para gerar uma história em quadrinhos
async function generateComicStory(formData) {
    try {
        console.log('Gerando história com os seguintes dados:', formData);
        
        // Fazer uma chamada AJAX para o endpoint de geração de histórias
        const response = await fetch('/api/generate-comic', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                theme: formData.theme,
                title: formData.title
            })
        });
        
        const result = await response.json();
        
        if (!result.success) {
            throw new Error(result.error || 'Erro ao gerar a história em quadrinhos');
        }
        
        // Carregar os metadados da história gerada
        const metadataResponse = await fetch(`/${result.directory}/story_metadata.json`);
        const metadata = await metadataResponse.json();
        
        return {
            title: metadata.title,
            theme: metadata.theme,
            mainCharacter: {
                characteristics: {
                    appearance: metadata.character.split(',')[0] || '',
                    clothing: metadata.character.split(',')[1] || '',
                    personality: '',
                    background: '',
                    abilities: ''
                }
            },
            panels: metadata.panels,
            directory: result.directory,
            createdAt: metadata.created_at
        };
    } catch (error) {
        console.error('Erro ao gerar história:', error);
        throw error;
    }
}

// Função para obter pontos de enredo com base no tema
function getPlotPoint(theme, type) {
    const plotPoints = {
        adventure: {
            action: "O herói embarca em uma jornada épica em busca de um tesouro perdido",
            climax: "O herói enfrenta o guardião do tesouro em uma batalha épica",
            resolution: "O herói obtém o tesouro e retorna como um herói"
        },
        mystery: {
            action: "O detetive começa a investigar um caso misterioso",
            climax: "O detetive revela o culpado em uma cena dramática",
            resolution: "A justiça é feita e a ordem é restaurada"
        },
        romance: {
            action: "Os dois protagonistas se encontram pela primeira vez",
            climax: "Os protagonistas enfrentam um obstáculo que ameaça seu amor",
            resolution: "Os protagonistas superam os desafios e ficam juntos"
        }
    };
    
    return plotPoints[theme][type] || plotPoints.adventure[type];
}

// Função para renderizar o visualizador de quadrinhos
function renderComicViewer(comicData) {
    const themeNames = {
        adventure: 'Aventura',
        mystery: 'Mistério',
        romance: 'Romance'
    };
    
    const viewerHTML = `
        <div class="comic-header">
            <h1>${comicData.title}</h1>
            <p>Uma história em quadrinhos gerada dinamicamente</p>
        </div>
        
        <div class="comic-character">
            <h2>Personagem Principal</h2>
            <div class="character-grid">
                <div class="character-item">
                    <strong>Aparência:</strong> ${comicData.mainCharacter.characteristics.appearance}
                </div>
                <div class="character-item">
                    <strong>Roupas:</strong> ${comicData.mainCharacter.characteristics.clothing}
                </div>
                <div class="character-item">
                    <strong>Personalidade:</strong> ${comicData.mainCharacter.characteristics.personality}
                </div>
                <div class="character-item">
                    <strong>Histórico:</strong> ${comicData.mainCharacter.characteristics.background}
                </div>
                <div class="character-item">
                    <strong>Habilidades:</strong> ${comicData.mainCharacter.characteristics.abilities}
                </div>
            </div>
        </div>
        
        <h2 style="text-align: center;">Painéis do Quadrinho</h2>
        <div class="comic-panels">
            ${comicData.panels.map(panel => `
                <div class="panel">
                    <h3>Painel ${panel.id}</h3>
                    <div class="panel-image">
                        <img src="/${panel.image}" alt="Painel ${panel.id}" onerror="this.style.display='none'; this.parentElement.innerHTML='<span>Imagem não disponível</span>'">
                    </div>
                    <p class="panel-description">${panel.description}</p>
                </div>
            `).join('')}
        </div>
        
        <div style="text-align: center; margin-top: 2rem; color: #7f8c8d; font-size: 0.9rem;">
            <p>História gerada em: ${new Date(comicData.createdAt).toLocaleString('pt-BR')}</p>
            <p>Tema: ${themeNames[comicData.theme] || comicData.theme}</p>
        </div>
    `;
    
    comicViewer.innerHTML = viewerHTML;
}

// Evento de envio do formulário
comicForm.addEventListener('submit', async (e) => {
    e.preventDefault();
    
    // Coletar dados do formulário
    const formData = {
        theme: document.getElementById('theme').value,
        title: document.getElementById('title').value,
        appearance: document.getElementById('appearance').value,
        clothing: document.getElementById('clothing').value,
        personality: document.getElementById('personality').value,
        background: document.getElementById('background').value,
        abilities: document.getElementById('abilities').value
    };
    
    // Validar dados
    if (!formData.title || !formData.appearance || !formData.clothing || 
        !formData.personality || !formData.background || !formData.abilities) {
        alert('Por favor, preencha todos os campos do personagem.');
        return;
    }
    
    // Desabilitar botão e mostrar loading
    generateBtn.disabled = true;
    toggleSections(true, false);
    
    try {
        // Gerar história
        const comicData = await generateComicStory(formData);
        
        // Renderizar visualizador
        renderComicViewer(comicData);
        
        // Mostrar resultado
        toggleSections(false, true);
    } catch (error) {
        console.error('Erro ao gerar história:', error);
        alert('Ocorreu um erro ao gerar a história. Por favor, tente novamente.');
        toggleSections(false, false);
    } finally {
        // Reabilitar botão
        generateBtn.disabled = false;
    }
});

// Evento para criar nova história
newStoryBtn.addEventListener('click', () => {
    toggleSections(false, false);
});

// Preencher título automaticamente com base no tema
document.getElementById('theme').addEventListener('change', (e) => {
    const titleInput = document.getElementById('title');
    if (!titleInput.value) {
        const themeTitles = {
            adventure: 'A Jornada do Herói',
            mystery: 'O Mistério da Cidade',
            romance: 'Amor Além das Estrelas'
        };
        titleInput.value = themeTitles[e.target.value] || '';
    }
});

// Preencher personagem automaticamente com base no tema
document.getElementById('theme').addEventListener('change', (e) => {
    const theme = e.target.value;
    
    // Preencher campos de personagem com exemplos
    if (!document.getElementById('appearance').value) {
        const appearances = {
            adventure: 'elfo com cabelos prateados e olhos esmeralda',
            mystery: 'detetive com sobretudo e chapéu',
            romance: 'explorador espacial com uniforme futurista'
        };
        document.getElementById('appearance').value = appearances[theme] || '';
    }
    
    if (!document.getElementById('clothing').value) {
        const clothings = {
            adventure: 'armadura élfica brilhante',
            mystery: 'sobretudo marrom e gravata',
            romance: 'uniforme espacial branco e azul'
        };
        document.getElementById('clothing').value = clothings[theme] || '';
    }
    
    if (!document.getElementById('personality').value) {
        const personalities = {
            adventure: 'corajoso e determinado',
            mystery: 'perspicaz e metódico',
            romance: 'aventureiro e sensível'
        };
        document.getElementById('personality').value = personalities[theme] || '';
    }
    
    if (!document.getElementById('background').value) {
        const backgrounds = {
            adventure: 'guerreiro de um reino antigo',
            mystery: 'ex-policial reformado',
            romance: 'explorador de novos planetas'
        };
        document.getElementById('background').value = backgrounds[theme] || '';
    }
    
    if (!document.getElementById('abilities').value) {
        const abilities = {
            adventure: 'mestre em combate com espada e magia elemental',
            mystery: 'habilidade de dedução e rastreamento',
            romance: 'piloto habilidoso e conhecimento de tecnologia avançada'
        };
        document.getElementById('abilities').value = abilities[theme] || '';
    }
});