<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>OCR Web Client</title>
    <style>
      body {
        font-family: Arial, sans-serif;
        max-width: 800px;
        margin: auto;
      }
      #imagePreview {
        max-width: 100%;
      }
      #extractedText {
        width: 100%;
        min-height: 200px;
      }
    </style>
  </head>
  <body>
    <h1>OCR Text Extraction</h1>

    <div>
      <h2>Upload Image</h2>
      <input type="file" id="imageUpload" accept="image/*" />
      <input type="text" id="imageUrl" placeholder="Or paste image URL" />
      <button onclick="extractText()">Extract Text</button>
    </div>

    <div>
      <h2>Preview</h2>
      <img id="imagePreview" src="" alt="Image Preview" />
    </div>

    <div>
      <h2>Extracted Text</h2>
      <textarea id="extractedText" readonly></textarea>
    </div>

    <script>
      async function extractText() {
        const fileInput = document.getElementById("imageUpload");
        const urlInput = document.getElementById("imageUrl");
        const preview = document.getElementById("imagePreview");
        const textArea = document.getElementById("extractedText");

        const formData = new FormData();

        // Handle file upload
        if (fileInput.files.length > 0) {
          formData.append("image", fileInput.files[0]);
        }
        // Handle URL input
        else if (urlInput.value) {
          formData.append("image_url", urlInput.value);
        } else {
          alert("Please upload an image or provide an image URL");
          return;
        }

        try {
          const response = await fetch("http://localhost:5000/extract-text", {
            method: "POST",
            body: formData,
          });

          const data = await response.json();

          if (data.image) {
            preview.src = `data:image/png;base64,${data.image}`;
          }

          textArea.value = data.text;
        } catch (error) {
          console.error("Error:", error);
          alert("Failed to extract text");
        }
      }
    </script>
  </body>
</html>