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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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
import { useState, useRef } from "react";
import { toast } from "sonner";
import { MODELS } from "@/lib/providers";
import { Page } from "@/types";

interface UseCallAiProps {
  onNewPrompt: (prompt: string) => void;
  onSuccess: (page: Page[], p: string, n?: number[][]) => void;
  onScrollToBottom: () => void;
  setPages: React.Dispatch<React.SetStateAction<Page[]>>;
  setCurrentPage: React.Dispatch<React.SetStateAction<string>>;
  currentPage: Page;
  pages: Page[];
  isAiWorking: boolean;
  setisAiWorking: React.Dispatch<React.SetStateAction<boolean>>;
}

export const useCallAi = ({
  onNewPrompt,
  onSuccess,
  onScrollToBottom,
  setPages,
  setCurrentPage,
  pages,
  isAiWorking,
  setisAiWorking,
}: UseCallAiProps) => {
  const audio = useRef<HTMLAudioElement | null>(null);
  const [controller, setController] = useState<AbortController | null>(null);

  const callAiNewProject = async (prompt: string, model: string | undefined, provider: stringundefined, redesignMarkdown?: string, handleThink?: (think: string) => void, onFinishThink?: () => void) => {
    if (isAiWorking) return;
    if (!redesignMarkdown && !prompt.trim()) return;
    
    setisAiWorking(true);
    
    const abortController = new AbortController();
    setController(abortController);
    
    try {
      onNewPrompt(prompt);
      
      const request = await fetch("/api/ask-ai", {
        method: "POST",
        body: JSON.stringify({
          prompt,
          provider,
          model,
          redesignMarkdown,
        }),
        headers: {
          "Content-Type": "application/json",
          "x-forwarded-for": window.location.hostname,
        },
        signal: abortController.signal,
      });

      if (request && request.body) {
        const reader = request.body.getReader();
        const decoder = new TextDecoder("utf-8");
        const selectedModel = MODELS.find(
          (m: { value: string }) => m.value === model
        );
        let contentResponse = "";

        const read = async () => {
          const { done, value } = await reader.read();
          if (done) {
            const isJson =
              contentResponse.trim().startsWith("{") &&
              contentResponse.trim().endsWith("}");
            const jsonResponse = isJson ? JSON.parse(contentResponse) : null;
            
            if (jsonResponse && !jsonResponse.ok) {
              if (jsonResponse.openLogin) {
                // Handle login required
                return { error: "login_required" };
              } else if (jsonResponse.openSelectProvider) {
                // Handle provider selection required
                return { error: "provider_required", message: jsonResponse.message };
              } else if (jsonResponse.openProModal) {
                // Handle pro modal required
                return { error: "pro_required" };
              } else {
                toast.error(jsonResponse.message);
                setisAiWorking(false);
                return { error: "api_error", message: jsonResponse.message };
              }
            }

            toast.success("AI responded successfully");
            setisAiWorking(false);
            
            if (audio.current) audio.current.play();

            const newPages = formatPages(contentResponse);
            onSuccess(newPages, prompt);

            return { success: true, pages: newPages };
          }

          const chunk = decoder.decode(value, { stream: true });
          contentResponse += chunk;
          
          if (selectedModel?.isThinker) {
            const thinkMatch = contentResponse.match(/<think>[\s\S]*/)?.[0];
            if (thinkMatch && !contentResponse?.includes("</think>")) {
              handleThink?.(thinkMatch.replace("<think>", "").trim());
              return read();
            }
          }

          if (contentResponse.includes("</think>")) {
            onFinishThink?.();
          }

          formatPages(contentResponse);
          return read();
        };

        return await read();
      }
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    } catch (error: any) {
      setisAiWorking(false);
      toast.error(error.message);
      if (error.openLogin) {
        return { error: "login_required" };
      }
      return { error: "network_error", message: error.message };
    }
  };

  const callAiNewPage = async (prompt: string, model: string | undefined, provider: stringundefined, currentPagePath: string, previousPrompts?: string[]) => {
    if (isAiWorking) return;
    if (!prompt.trim()) return;
    
    setisAiWorking(true);
    
    const abortController = new AbortController();
    setController(abortController);
    
    try {
      onNewPrompt(prompt);
      
      const request = await fetch("/api/ask-ai", {
        method: "POST",
        body: JSON.stringify({
          prompt,
          provider,
          model,
          pages,
          previousPrompts,
        }),
        headers: {
          "Content-Type": "application/json",
          "x-forwarded-for": window.location.hostname,
        },
        signal: abortController.signal,
      });

      if (request && request.body) {
        const reader = request.body.getReader();
        const decoder = new TextDecoder("utf-8");
        const selectedModel = MODELS.find(
          (m: { value: string }) => m.value === model
        );
        let contentResponse = "";

        const read = async () => {
          const { done, value } = await reader.read();
          if (done) {
            const isJson =
              contentResponse.trim().startsWith("{") &&
              contentResponse.trim().endsWith("}");
            const jsonResponse = isJson ? JSON.parse(contentResponse) : null;
            
            if (jsonResponse && !jsonResponse.ok) {
              if (jsonResponse.openLogin) {
                // Handle login required
                return { error: "login_required" };
              } else if (jsonResponse.openSelectProvider) {
                // Handle provider selection required
                return { error: "provider_required", message: jsonResponse.message };
              } else if (jsonResponse.openProModal) {
                // Handle pro modal required
                return { error: "pro_required" };
              } else {
                toast.error(jsonResponse.message);
                setisAiWorking(false);
                return { error: "api_error", message: jsonResponse.message };
              }
            }

            toast.success("AI responded successfully");
            setisAiWorking(false);
            
            if (selectedModel?.isThinker) {
              // Reset to default model if using thinker model
              // Note: You might want to add a callback for this
            }
            
            if (audio.current) audio.current.play();

            const newPage = formatPage(contentResponse, currentPagePath);
            if (!newPage) { return { error: "api_error", message: "Failed to format page" } }
            onSuccess([...pages, newPage], prompt);

            return { success: true, pages: [...pages, newPage] };
          }

          const chunk = decoder.decode(value, { stream: true });
          contentResponse += chunk;
          
          if (selectedModel?.isThinker) {
            const thinkMatch = contentResponse.match(/<think>[\s\S]*/)?.[0];
            if (thinkMatch && !contentResponse?.includes("</think>")) {
              // contentThink += chunk;
              return read();
            }
          }

          formatPage(contentResponse, currentPagePath);
          return read();
        };

        return await read();
      }
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    } catch (error: any) {
      setisAiWorking(false);
      toast.error(error.message);
      if (error.openLogin) {
        return { error: "login_required" };
      }
      return { error: "network_error", message: error.message };
    }
  };

  const callAiFollowUp = async (prompt: string, model: string | undefined, provider: stringundefined, previousPrompts: string[], selectedElementHtml?: string, files?: string[]) => {
    if (isAiWorking) return;
    if (!prompt.trim()) return;
    
    setisAiWorking(true);
    
    const abortController = new AbortController();
    setController(abortController);
    
    try {
      onNewPrompt(prompt);
      
      const request = await fetch("/api/ask-ai", {
        method: "PUT",
        body: JSON.stringify({
          prompt,
          provider,
          previousPrompts,
          model,
          pages,
          selectedElementHtml,
          files,
        }),
        headers: {
          "Content-Type": "application/json",
          "x-forwarded-for": window.location.hostname,
        },
        signal: abortController.signal,
      });

      if (request && request.body) {
        const res = await request.json();
        
        if (!request.ok) {
          if (res.openLogin) {
            setisAiWorking(false);
            return { error: "login_required" };
          } else if (res.openSelectProvider) {
            setisAiWorking(false);
            return { error: "provider_required", message: res.message };
          } else if (res.openProModal) {
            setisAiWorking(false);
            return { error: "pro_required" };
          } else {
            toast.error(res.message);
            setisAiWorking(false);
            return { error: "api_error", message: res.message };
          }
        }

        toast.success("AI responded successfully");
        setisAiWorking(false);

        setPages(res.pages);
        onSuccess(res.pages, prompt, res.updatedLines);
        
        if (audio.current) audio.current.play();

        return { success: true, html: res.html, updatedLines: res.updatedLines };
      }
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    } catch (error: any) {
      setisAiWorking(false);
      toast.error(error.message);
      if (error.openLogin) {
        return { error: "login_required" };
      }
      return { error: "network_error", message: error.message };
    }
  };

  // Stop the current AI generation
  const stopController = () => {
    if (controller) {
      controller.abort();
      setController(null);
      setisAiWorking(false);
    }
  };

  const formatPages = (content: string) => {
    const pages: Page[] = [];
    if (!content.match(/<<<<<<< START_TITLE (.*?) >>>>>>> END_TITLE/)) {
      return pages;
    }

    const cleanedContent = content.replace(
      /[\s\S]*?<<<<<<< START_TITLE (.*?) >>>>>>> END_TITLE/,
      "<<<<<<< START_TITLE $1 >>>>>>> END_TITLE"
    );
    const htmlChunks = cleanedContent.split(
      /<<<<<<< START_TITLE (.*?) >>>>>>> END_TITLE/
    );
    const processedChunks = new Set<number>();

    htmlChunks.forEach((chunk, index) => {
      if (processedChunks.has(index) || !chunk?.trim()) {
        return;
      }
      const htmlContent = extractHtmlContent(htmlChunks[index + 1]);

      if (htmlContent) {
        const page: Page = {
          path: chunk.trim(),
          html: htmlContent,
        };
        pages.push(page);

        if (htmlContent.length > 200) {
          onScrollToBottom();
        }

        processedChunks.add(index);
        processedChunks.add(index + 1);
      }
    });
    if (pages.length > 0) {
      setPages(pages);
      const lastPagePath = pages[pages.length - 1]?.path;
      setCurrentPage(lastPagePath || "index.html");
    }

    return pages;
  };

  const formatPage = (content: string, currentPagePath: string) => {
    if (!content.match(/<<<<<<< START_TITLE (.*?) >>>>>>> END_TITLE/)) {
      return null;
    }

    const cleanedContent = content.replace(
      /[\s\S]*?<<<<<<< START_TITLE (.*?) >>>>>>> END_TITLE/,
      "<<<<<<< START_TITLE $1 >>>>>>> END_TITLE"
    );

    const htmlChunks = cleanedContent.split(
      /<<<<<<< START_TITLE (.*?) >>>>>>> END_TITLE/
    )?.filter(Boolean);

    const pagePath = htmlChunks[0]?.trim() || "";
    const htmlContent = extractHtmlContent(htmlChunks[1]);

    if (!pagePath || !htmlContent) {
      return null;
    }

    const page: Page = {
      path: pagePath,
      html: htmlContent,
    };

    setPages(prevPages => {
      const existingPageIndex = prevPages.findIndex(p => p.path === currentPagePath || p.path === pagePath);
      
      if (existingPageIndex !== -1) {
        const updatedPages = [...prevPages];
        updatedPages[existingPageIndex] = page;
        return updatedPages;
      } else {
        return [...prevPages, page];
      }
    });

    setCurrentPage(pagePath);

    if (htmlContent.length > 200) {
      onScrollToBottom();
    }

    return page;
  };

  // Helper function to extract and clean HTML content
  const extractHtmlContent = (chunk: string): string => {
    if (!chunk) return "";

    // Extract HTML content
    const htmlMatch = chunk.trim().match(/<!DOCTYPE html>[\s\S]*/);
    if (!htmlMatch) return "";

    let htmlContent = htmlMatch[0];

    // Ensure proper HTML structure
    htmlContent = ensureCompleteHtml(htmlContent);

    // Remove markdown code blocks if present
    htmlContent = htmlContent.replace(/```/g, "");

    return htmlContent;
  };

  // Helper function to ensure HTML has complete structure
  const ensureCompleteHtml = (html: string): string => {
    let completeHtml = html;

    // Add missing head closing tag
    if (completeHtml.includes("<head>") && !completeHtml.includes("</head>")) {
      completeHtml += "\n</head>";
    }

    // Add missing body closing tag
    if (completeHtml.includes("<body") && !completeHtml.includes("</body>")) {
      completeHtml += "\n</body>";
    }

    // Add missing html closing tag
    if (!completeHtml.includes("</html>")) {
      completeHtml += "\n</html>";
    }

    return completeHtml;
  };

  return {
    callAiNewProject,
    callAiFollowUp,
    callAiNewPage,
    stopController,
    controller,
    audio,
  };
};