import fs from 'fs';
import path from 'path';

const files = [
  "src/components/sections/BlogsHero.tsx",
  "src/components/sections/AboutHero.tsx",
  "src/components/sections/SingleBlog.tsx",
  "src/components/sections/ContactsHero.tsx",
  "src/components/sections/IndexHero.tsx",
  "src/components/sections/SolutionsHero.tsx",
  "src/components/sections/MileTruthHero.tsx",
  "src/components/sections/HowItWorksHero.tsx"
];

for (const f of files) {
  let content = fs.readFileSync(f, 'utf8');
  
  const match = content.match(/<link\s+rel="preload"\s+as="image"\s+href="([^"]+)"\s*\/>/);
  if (match) {
    const href = match[1];
    
    if (!content.includes('import { preload } from "react-dom"')) {
      const lastImportIndex = content.lastIndexOf('import ');
      const endOfLastImport = content.indexOf('\n', lastImportIndex);
      content = content.substring(0, endOfLastImport + 1) + 'import { preload } from "react-dom";\n' + content.substring(endOfLastImport + 1);
    }
    
    content = content.replace(match[0], '');
    
    // Find the default export function
    const fnMatch = content.match(/export default function\s+\w+\s*\([^)]*\)\s*\{/);
    if (fnMatch) {
      const insertIdx = fnMatch.index + fnMatch[0].length;
      content = content.substring(0, insertIdx) + `\n  preload("${href}", { as: "image" });` + content.substring(insertIdx);
    } else {
        // try non-default export
        const fnMatch2 = content.match(/export function\s+\w+\s*\([^)]*\)\s*\{/);
        if (fnMatch2) {
            const insertIdx = fnMatch2.index + fnMatch2[0].length;
            content = content.substring(0, insertIdx) + `\n  preload("${href}", { as: "image" });` + content.substring(insertIdx);
        } else {
            console.log("Could not find function for " + f);
        }
    }
    
    fs.writeFileSync(f, content, 'utf8');
    console.log("Fixed " + f);
  }
}
