const { app, BrowserWindow, ipcMain, dialog, shell, Menu } = require('electron');
const path = require('path');
const fs = require('fs');
const http = require('http');
const https = require('https');
const ExifParser = require('exif-parser');
const Jimp = require('jimp');
const CryptoJS = require('crypto-js');
const AdmZip = require('adm-zip');

let mainWindow;

function showAboutDialog() {
  const iconPath = path.join(__dirname, 'logo.jpg');
  
  dialog.showMessageBox(mainWindow, {
    type: 'info',
    title: 'O aplikaci / About',
    icon: fs.existsSync(iconPath) ? iconPath : undefined,
    message: 'Živé vzpomínky na dovolenou / Live Vacation Memories',
    detail: 'Verze / Version 1.0.0\n\nCopyright © 2026 Coolcode\nWeb: https://coolcode.cz\n\nVytvořte si úchvatné interaktivní deníky ze svých cest a dovolených.\nCreate stunning interactive diaries from your travels and vacations.',
    buttons: ['Zavřít / Close', 'Otevřít web / Open Website'],
    defaultId: 0
  }).then((result) => {
    if (result.response === 1) {
      shell.openExternal('https://coolcode.cz');
    }
  });
}

function createWindow() {
  mainWindow = new BrowserWindow({
    width: 1200,
    height: 800,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      contextIsolation: true,
      nodeIntegration: false
    },
    title: "Živé vzpomínky na dovolenou",
    backgroundColor: '#12181f'
  });

  mainWindow.maximize();
  mainWindow.loadFile('index.html');
  
  // Pipe renderer console logs to main process stdout for debugging
  mainWindow.webContents.on('console-message', (event, level, message, line, sourceId) => {
    console.log(`[Renderer] ${message} (at ${path.basename(sourceId)}:${line})`);
  });
  // mainWindow.webContents.openDevTools(); // Můžeme povolit pro ladění

  // Nastavení menu
  const menuTemplate = [
    {
      label: 'Soubor / File',
      submenu: [
        {
          label: 'Konec / Exit',
          role: 'quit'
        }
      ]
    },
    {
      label: 'Help',
      submenu: [
        {
          label: 'Rychlá pomoc',
          click: () => {
            if (mainWindow) {
              mainWindow.webContents.send('open-help-modal');
            }
          }
        },
        {
          label: 'O aplikaci / About',
          click: showAboutDialog
        }
      ]
    }
  ];
  
  const menu = Menu.buildFromTemplate(menuTemplate);
  Menu.setApplicationMenu(menu);
}

app.whenReady().then(() => {
  createWindow();

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) createWindow();
  });
});

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit();
});

// Pomocná funkce pro HTTP GET
function httpGet(url, headers = {}) {
  return new Promise((resolve, reject) => {
    const parsedUrl = new URL(url);
    const client = url.startsWith('https') ? https : http;
    const options = {
      hostname: parsedUrl.hostname,
      path: parsedUrl.pathname + parsedUrl.search,
      headers: headers
    };
    const req = client.get(options, (res) => {
      let data = '';
      res.on('data', (chunk) => { data += chunk; });
      res.on('end', () => {
        try {
          resolve(JSON.parse(data));
        } catch (e) {
          resolve(data);
        }
      });
    });
    req.on('error', (err) => reject(err));
  });
}


// --- IPC HANDLERS ---

// Výběr adresáře na počítači
ipcMain.handle('select-directory', async () => {
  const result = await dialog.showOpenDialog(mainWindow, {
    properties: ['openDirectory']
  });
  if (result.canceled) {
    return null;
  } else {
    return result.filePaths[0];
  }
});

// Výběr souboru na počítači (např. titulní fotka)
ipcMain.handle('select-file', async () => {
  const result = await dialog.showOpenDialog(mainWindow, {
    properties: ['openFile'],
    filters: [
      { name: 'Obrázky', extensions: ['jpg', 'jpeg', 'png', 'webp', 'gif'] }
    ]
  });
  if (result.canceled || result.filePaths.length === 0) {
    return null;
  } else {
    return result.filePaths[0];
  }
});

// Načtení existujících dovolených (projektů)
const getProjectsFilePath = () => {
  const dir = path.join(app.getPath('userData'), 'dovoleny');
  if (!fs.existsSync(dir)) {
    fs.mkdirSync(dir, { recursive: true });
  }
  return path.join(dir, 'projects.json');
};

ipcMain.handle('load-projects', async () => {
  const filePath = getProjectsFilePath();
  if (fs.existsSync(filePath)) {
    try {
      const data = fs.readFileSync(filePath, 'utf8');
      return JSON.parse(data);
    } catch (e) {
      return [];
    }
  }
  return [];
});

ipcMain.handle('save-project', async (event, project) => {
  const filePath = getProjectsFilePath();
  let projects = [];
  if (fs.existsSync(filePath)) {
    try {
      projects = JSON.parse(fs.readFileSync(filePath, 'utf8'));
    } catch (e) {
      projects = [];
    }
  }

  const index = projects.findIndex(p => p.id === project.id);
  if (index !== -1) {
    projects[index] = project;
  } else {
    projects.push(project);
  }

  fs.writeFileSync(filePath, JSON.stringify(projects, null, 2), 'utf8');
  return projects;
});

ipcMain.handle('delete-project', async (event, projectId) => {
  const filePath = getProjectsFilePath();
  if (fs.existsSync(filePath)) {
    try {
      let projects = JSON.parse(fs.readFileSync(filePath, 'utf8'));
      projects = projects.filter(p => p.id !== projectId);
      fs.writeFileSync(filePath, JSON.stringify(projects, null, 2), 'utf8');
      return projects;
    } catch (e) {
      return [];
    }
  }
  return [];
});

ipcMain.handle('import-mobile-zip', async () => {
  // 1. Show file open dialog
  const result = await dialog.showOpenDialog(mainWindow, {
    title: 'Importovat mobilní projekt (ZIP)',
    properties: ['openFile'],
    filters: [
      { name: 'ZIP archiv', extensions: ['zip'] }
    ]
  });

  if (result.canceled || result.filePaths.length === 0) {
    return { success: false, error: 'Import byl zrušen.' };
  }

  const zipPath = result.filePaths[0];

  try {
    // 2. Open and extract ZIP
    const zip = new AdmZip(zipPath);
    const entries = zip.getEntries();
    
    // Find the trip.json entry and determine the path prefix (if any)
    let tripEntry = null;
    let prefix = '';
    
    for (const entry of entries) {
      if (entry.entryName === 'trip.json') {
        tripEntry = entry;
        prefix = '';
        break;
      } else if (entry.entryName.endsWith('/trip.json')) {
        tripEntry = entry;
        prefix = entry.entryName.substring(0, entry.entryName.length - 9); // e.g. "export123/"
        break;
      }
    }
    
    if (!tripEntry) {
      return { success: false, error: 'Vybraný soubor není platný export cesty (chybí trip.json).' };
    }

    // Read trip data to get the ID
    const tripJson = JSON.parse(zip.readAsText(tripEntry));
    const tripId = tripJson.id;
    if (!tripId) {
      return { success: false, error: 'Neplatná data cesty v trip.json.' };
    }

    // Define target directory for extraction
    const targetDir = path.join(app.getPath('userData'), 'dovoleny', tripId);
    if (!fs.existsSync(targetDir)) {
      fs.mkdirSync(targetDir, { recursive: true });
    }

    // Extract all entries directly to targetDir (flattening the prefix if it exists)
    if (prefix) {
      for (const entry of entries) {
        if (entry.entryName.startsWith(prefix) && !entry.isDirectory) {
          const relPath = entry.entryName.substring(prefix.length);
          const destPath = path.join(targetDir, relPath);
          const destDir = path.dirname(destPath);
          if (!fs.existsSync(destDir)) {
            fs.mkdirSync(destDir, { recursive: true });
          }
          fs.writeFileSync(destPath, zip.readFile(entry));
        }
      }
    } else {
      zip.extractAllTo(targetDir, true);
    }

    // 3. Read other json files
    const placesEntry = zip.getEntry(prefix + 'places.json');
    const photosEntry = zip.getEntry(prefix + 'photos.json');
    
    const placesJson = placesEntry ? JSON.parse(zip.readAsText(placesEntry)) : [];
    const photosJson = photosEntry ? JSON.parse(zip.readAsText(photosEntry)) : [];

    // 4. Map mobile trip date bounds to dateText
    let dateText = '';
    if (tripJson.startTimeUtc || tripJson.finishTimeUtc) {
      const options = { day: 'numeric', month: 'numeric', year: 'numeric' };
      const startText = tripJson.startTimeUtc 
        ? new Date(tripJson.startTimeUtc).toLocaleDateString('cs-CZ', options) 
        : '?';
      const endText = tripJson.finishTimeUtc 
        ? new Date(tripJson.finishTimeUtc).toLocaleDateString('cs-CZ', options) 
        : 'probíhá';
      dateText = `${startText} – ${endText}`;
    }

    // 5. Build Days array from places
    const dayNumbers = [...new Set(placesJson.map(p => p.dayNumber))].sort((a, b) => a - b);
    const colors = [
      '#d73027', '#fc8d59', '#e6ab02', '#66a61e', '#1b9e77',
      '#1f78b4', '#7570b3', '#e7298a', '#8c510a', '#543005'
    ];
    const days = dayNumbers.map((d, idx) => {
      const dayPlaces = placesJson.filter(p => p.dayNumber === d);
      const title = dayPlaces.slice(0, 3).map(p => p.name || 'Zastávka').join(' – ') || 'Program dne';
      const summary = dayPlaces.filter(p => p.description).map(p => p.description).join(' ') || 'Fotovýlet a objevování okolí.';
      return {
        day: d,
        label: `Den ${d}`,
        color: colors[(d - 1) % colors.length],
        title: title,
        summary: summary
      };
    });

    // 6. Build Points array from places and pair with photos
    const points = placesJson.map((place, index) => {
      // Find photos taken at this place (based on arrival/departure time)
      const placePhotos = [];
      if (place.arrivalTimeUtc && place.departureTimeUtc) {
        photosJson.forEach(photo => {
          const time = photo.dateTakenUtc || 0;
          if (time >= place.arrivalTimeUtc && time <= place.departureTimeUtc) {
            placePhotos.push(photo.displayName);
          }
        });
      }

      return {
        day: place.dayNumber,
        order: index + 1,
        name: place.name || `Zastávka ${index + 1}`,
        type: 'zastávka',
        lat: place.latitude,
        lon: place.longitude,
        description: place.description || '',
        photos: placePhotos
      };
    });

    // 7. Determine cover photo
    let coverPhoto = null;
    if (tripJson.coverPhotoId) {
      const cp = photosJson.find(p => p.id === tripJson.coverPhotoId);
      if (cp) {
        coverPhoto = path.join(targetDir, 'originals', cp.displayName);
      }
    }
    if (!coverPhoto && photosJson.length > 0) {
      coverPhoto = path.join(targetDir, 'originals', photosJson[0].displayName);
    }

    // 8. Create desktop project object
    const desktopProject = {
      id: tripId,
      title: tripJson.name || 'Dovolená z mobilu',
      dateText: dateText,
      description: tripJson.description || '',
      colorScheme: 'dark', // default to dark
      passwordProtected: false,
      password: '',
      photoSource: 'local',
      localPath: path.join(targetDir, 'originals'),
      exportPath: '', // can be generated on re-export
      days: days,
      points: points,
      coverPhoto: coverPhoto
    };

    // 9. Load, append/replace, and save project in projects.json
    const projectsFilePath = getProjectsFilePath();
    let projects = [];
    if (fs.existsSync(projectsFilePath)) {
      try {
        projects = JSON.parse(fs.readFileSync(projectsFilePath, 'utf8'));
      } catch (e) {
        projects = [];
      }
    }

    const existingIdx = projects.findIndex(p => p.id === tripId);
    if (existingIdx !== -1) {
      projects[existingIdx] = desktopProject;
    } else {
      projects.push(desktopProject);
    }

    fs.writeFileSync(projectsFilePath, JSON.stringify(projects, null, 2), 'utf8');

    return { success: true, projects: projects };

  } catch (err) {
    console.error('Chyba při importu mobilního projektu:', err);
    return { success: false, error: 'Chyba při extrakci nebo čtení dat: ' + err.toString() };
  }
});

// Skenování fotek ve složce a extrakce EXIF
ipcMain.handle('scan-photos', async (event, dirPath) => {
  if (!fs.existsSync(dirPath)) return [];
  
  const files = fs.readdirSync(dirPath);
  const photos = [];

  for (const file of files) {
    const ext = path.extname(file).toLowerCase();
    if (ext === '.jpg' || ext === '.jpeg') {
      const filePath = path.join(dirPath, file);
      try {
        const buffer = fs.readFileSync(filePath);
        const parser = ExifParser.create(buffer);
        const result = parser.parse();
        
        let lat = null;
        let lon = null;
        let date = null;

        if (result.tags) {
          if (result.tags.GPSLatitude && result.tags.GPSLongitude) {
            lat = result.tags.GPSLatitude;
            lon = result.tags.GPSLongitude;
          }
          if (result.tags.DateTimeOriginal) {
            // EXIF timestamp je v sekundách, převedeme na čitelný formát YYYY-MM-DD
            const d = new Date(result.tags.DateTimeOriginal * 1000);
            date = d.toISOString().split('T')[0];
          }
        }

        photos.push({
          name: file,
          path: filePath,
          lat,
          lon,
          date
        });
      } catch (e) {
        // Soubor mohl mít poškozený EXIF, přidáme ho bez metadat
        photos.push({
          name: file,
          path: filePath,
          lat: null,
          lon: null,
          date: null
        });
      }
    }
  }
  return photos;
});

// Reverse Geocoding přes Nominatim API s rate limitací (využívá frontend)
ipcMain.handle('reverse-geocode', async (event, lat, lon) => {
  const url = `https://nominatim.openstreetmap.org/reverse?format=jsonv2&lat=${lat}&lon=${lon}&zoom=18`;
  const headers = {
    'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
    'Accept-Language': 'cs-CZ,cs;q=0.9,en;q=0.8',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8'
  };
  try {
    return await httpGet(url, headers);
  } catch (e) {
    return null;
  }
});

// Wikipedia Geosearch
ipcMain.handle('wikipedia-geosearch', async (event, lat, lon) => {
  const searchUrl = `https://cs.wikipedia.org/w/api.php?action=query&list=geosearch&gscoord=${lat}|${lon}&gsradius=10000&gslimit=5&format=json`;
  const headers = {
    'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
    'Accept-Language': 'cs-CZ,cs;q=0.9,en;q=0.8'
  };
  try {
    const res = await httpGet(searchUrl, headers);
    if (res.query && res.query.geosearch && res.query.geosearch.length > 0) {
      const bestMatch = res.query.geosearch[0];
      // Získat úvod z článku
      const detailUrl = `https://cs.wikipedia.org/w/api.php?action=query&prop=extracts&exintro&explaintext&titles=${encodeURIComponent(bestMatch.title)}&format=json`;
      const detailRes = await httpGet(detailUrl, headers);
      const pages = detailRes.query.pages;
      const pageId = Object.keys(pages)[0];
      const extract = pages[pageId].extract || '';
      return {
        title: bestMatch.title,
        summary: extract.split('\n')[0] // Použít pouze první odstavec
      };
    }
    return null;
  } catch (e) {
    return null;
  }
});


// Generování webu dovolené
ipcMain.handle('generate-web', async (event, project, outputDir) => {
  try {
    const slug = project.title.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, "").replace(/[^a-z0-9]+/g, "-").replace(/(^-|-$)+/g, "") || "vacation";
    const folderName = `LVM-${slug}`;
    let targetDir = outputDir;
    
    // Pokud vybraná složka nekončí na folderName, vytvoříme podsložku přímo v ní
    if (!outputDir.endsWith(folderName)) {
      targetDir = path.join(outputDir, folderName);
    }

    if (!fs.existsSync(targetDir)) {
      fs.mkdirSync(targetDir, { recursive: true });
    }

    const photosDir = path.join(targetDir, 'fotky');    // 1. Zpracování a optimalizace fotek přes Jimp v paralelním worker poolu
    mainWindow.webContents.send('generation-progress', 'Optimalizace a kopírování fotografií...');
    
    // Nejprve sesbíráme všechny úlohy pro zpracování obrázků
    const tasks = [];
    for (const point of project.points) {
      for (const photoPath of point.photos) {
        if (fs.existsSync(photoPath)) {
          const baseName = path.basename(photoPath);
          const ext = path.extname(photoPath);
          const cleanName = baseName.replace(ext, '');
          
          const webPhotoName = `web_${cleanName}.jpg`;
          const thumbPhotoName = `thumb_${cleanName}.jpg`;
          
          const webPath = path.join(photosDir, webPhotoName);
          const thumbPath = path.join(photosDir, thumbPhotoName);
          
          tasks.push({
            photoPath,
            webPath,
            thumbPath,
            webPhotoName,
            thumbPhotoName
          });
        }
      }
    }

    const concurrency = 4;
    let activeIndex = 0;
    
    const processTask = async (task) => {
      if (!fs.existsSync(task.webPath) || !fs.existsSync(task.thumbPath)) {
        try {
          const image = await Jimp.read(task.photoPath);
          // Optimalizace: webová i náhledová verze se generují a ukládají paralelně
          await Promise.all([
            image.clone().resize(1600, Jimp.AUTO).quality(80).writeAsync(task.webPath),
            image.clone().resize(300, Jimp.AUTO).quality(75).writeAsync(task.thumbPath)
          ]);
        } catch (err) {
          // Fallback pokud Jimp selže - zkopírujeme přímo
          fs.copyFileSync(task.photoPath, task.webPath);
          fs.copyFileSync(task.photoPath, task.thumbPath);
        }
      }
    };

    const worker = async () => {
      while (activeIndex < tasks.length) {
        const currentIndex = activeIndex++;
        if (currentIndex >= tasks.length) break;
        const task = tasks[currentIndex];
        
        mainWindow.webContents.send(
          'generation-progress', 
          `Optimalizace fotek (${currentIndex + 1}/${tasks.length})...`
        );
        
        await processTask(task);
      }
    };

    // Spustíme pool workerů
    const workers = [];
    for (let i = 0; i < Math.min(concurrency, tasks.length); i++) {
      workers.push(worker());
    }
    await Promise.all(workers);

    // Namapujeme zpracované fotky zpět na jednotlivé body
    const pointsWithProcessedPhotos = project.points.map(point => {
      const processedPhotos = [];
      point.photos.forEach(photoPath => {
        if (fs.existsSync(photoPath)) {
          const baseName = path.basename(photoPath);
          const ext = path.extname(photoPath);
          const cleanName = baseName.replace(ext, '');
          
          const webPhotoName = `web_${cleanName}.jpg`;
          const thumbPhotoName = `thumb_${cleanName}.jpg`;
          
          processedPhotos.push({
            web: `fotky/${webPhotoName}`,
            thumb: `fotky/${thumbPhotoName}`
          });
        }
      });
      return {
        ...point,
        processedPhotos
      };
    });

    // 2. Příprava dat
    mainWindow.webContents.send('generation-progress', 'Zápis datových souborů...');
    const finalData = {
      title: project.title,
      dateText: project.dateText,
      description: project.description,
      colorScheme: project.colorScheme,
      days: project.days,
      points: pointsWithProcessedPhotos
    };

    let dataJsContent = '';
    if (project.passwordProtected && project.password) {
      // Šifrování dat pomocí AES-256
      const encrypted = CryptoJS.AES.encrypt(JSON.stringify(finalData), project.password).toString();
      dataJsContent = `// Šifrovaná data pro ochranu heslem\nconst isEncrypted = true;\nconst encryptedData = "${encrypted}";\n`;
    } else {
      dataJsContent = `// Otevřená data\nconst isEncrypted = false;\nconst vacationData = ${JSON.stringify(finalData, null, 2)};\n`;
    }

    fs.writeFileSync(path.join(targetDir, 'data.js'), dataJsContent, 'utf8');

    // 3. Kopírování a přizpůsobení šablon
    mainWindow.webContents.send('generation-progress', 'Kopírování šablony webu...');
    const templateDir = path.join(__dirname, 'template');
    
    // Kopírování index.html, style.css, script.js, crypto-js.js
    if (fs.existsSync(templateDir)) {
      const files = ['index.html', 'style.css', 'script.js', 'crypto-js.js'];
      files.forEach(file => {
        if (fs.existsSync(path.join(templateDir, file))) {
          let content = fs.readFileSync(path.join(templateDir, file), 'utf8');
          
          // Možnost nahradit některé základní proměnné přímo v souborech při sestavení
          if (file === 'index.html') {
            content = content.replace('{{TITLE}}', project.title);
          }
          
          fs.writeFileSync(path.join(targetDir, file), content, 'utf8');
        }
      });
    }

    mainWindow.webContents.send('generation-progress', 'Dokončeno!');
    return { success: true, exportPath: targetDir };
  } catch (e) {
    return { success: false, error: e.message };
  }
});

// Otevření vygenerovaného HTML v prohlížeči
ipcMain.handle('open-project-html', async (event, exportPath) => {
  const htmlPath = path.join(exportPath, 'index.html');
  if (fs.existsSync(htmlPath)) {
    await shell.openPath(htmlPath);
    return { success: true };
  }
  return { success: false, error: 'Soubor index.html nebyl v cílové složce nalezen.' };
});

// Zabalení projektu do ZIPu a otevření Netlify Drop
ipcMain.handle('zip-and-open-netlify', async (event, folderPath) => {
  try {
    if (!fs.existsSync(folderPath)) {
      return { success: false, error: 'Složka neexistuje.' };
    }
    
    const parentDir = path.dirname(folderPath);
    const folderName = path.basename(folderPath);
    const zipPath = path.join(parentDir, `${folderName}.zip`);
    
    const zip = new AdmZip();
    zip.addLocalFolder(folderPath);
    zip.writeZip(zipPath);
    
    // Otevřít složku a zvýraznit ZIP soubor
    await shell.showItemInFolder(zipPath);
    
    // Otevřít Netlify Drop ve výchozím prohlížeči
    await shell.openExternal('https://app.netlify.com/drop');
    
    return { success: true, zipPath };
  } catch (e) {
    return { success: false, error: e.message };
  }
});


// Pomocný slugify pro názvy Netlify
function slugify(text) {
  return text
    .toString()
    .toLowerCase()
    .normalize('NFD') // Rozdělení diakritiky
    .replace(/[\u0300-\u036f]/g, '') // Odstranění diakritiky
    .replace(/[^a-z0-9 -]/g, '') // Odstranění nepovolených znaků
    .replace(/\s+/g, '-') // Mezery na pomlčky
    .replace(/-+/g, '-') // Vícenásobné pomlčky
    .trim();
}

// Získání uloženého Netlify tokenu ze souboru na disku (pokud existuje)
ipcMain.handle('get-netlify-token', async () => {
  const tokenPath = path.join(__dirname, 'Netlify token.txt');
  if (fs.existsSync(tokenPath)) {
    try {
      const content = fs.readFileSync(tokenPath, 'utf8').trim();
      if (content) return content;
    } catch (e) {}
  }
  return null;
});

// Automatický upload na Netlify
ipcMain.handle('deploy-to-netlify', async (event, project, token) => {
  try {
    const folderPath = project.exportPath;
    if (!fs.existsSync(folderPath)) {
      return { success: false, error: 'Exportní složka neexistuje. Nejdříve vygenerujte web.' };
    }

    const parentDir = path.dirname(folderPath);
    const folderName = path.basename(folderPath);
    const zipPath = path.join(parentDir, `${folderName}.zip`);

    // 1. Zabalit složku do ZIPu
    const zip = new AdmZip();
    zip.addLocalFolder(folderPath);
    zip.writeZip(zipPath);

    // 2. Načíst bytes ZIP souboru
    const zipBuffer = fs.readFileSync(zipPath);

    let siteId = project.netlifySiteId || null;
    let siteUrl = project.netlifyUrl || null;

    // 3. Ověřit zda web na Netlify existuje
    if (siteId) {
      try {
        const checkRes = await fetch(`https://api.netlify.com/api/v1/sites/${siteId}`, {
          headers: { 'Authorization': `Bearer ${token}` }
        });
        if (checkRes.status === 404) {
          siteId = null;
          siteUrl = null;
        }
      } catch (e) {
        // Ignorujeme síťové chyby při ověření, zkusíme pokračovat
      }
    }

    // 4. Vytvořit web pokud neexistuje
    if (!siteId) {
      let customName = slugify(project.title || 'dovolena');
      if (!customName) {
        customName = `dovolena-${Date.now()}`;
      }

      let createRes = await fetch('https://api.netlify.com/api/v1/sites', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ name: customName })
      });

      // Pokud je název obsazen (422), zkusíme název s náhodným číslem
      if (createRes.status === 422) {
        const randomSuffix = Math.floor(1000 + Math.random() * 9000);
        createRes = await fetch('https://api.netlify.com/api/v1/sites', {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({ name: `${customName}-${randomSuffix}` })
        });
      }

      // Pokud stále selhává, necháme Netlify zvolit náhodné jméno
      if (!createRes.ok) {
        createRes = await fetch('https://api.netlify.com/api/v1/sites', {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({})
        });
      }

      if (!createRes.ok) {
        const errText = await createRes.text();
        return { success: false, error: `Nepodařilo se vytvořit stránku na Netlify (kód ${createRes.status}): ${errText}` };
      }

      const siteData = await createRes.json();
      siteId = siteData.id;
      siteUrl = siteData.ssl_url || siteData.url;
    }

    // 5. Nahrát ZIP na Netlify
    const deployRes = await fetch(`https://api.netlify.com/api/v1/sites/${siteId}/deploys`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/zip'
      },
      body: zipBuffer
    });

    if (!deployRes.ok) {
      const errText = await deployRes.text();
      return { success: false, error: `Nahrávání selhalo (kód ${deployRes.status}): ${errText}` };
    }

    const deployData = await deployRes.json();
    const deployId = deployData.id;

    // 6. Pollovat stav deploye dokud není "ready" nebo neuběhne timeout
    let state = deployData.state;
    let attempts = 0;
    const maxAttempts = 30; // 30s timeout

    while (state !== 'ready' && state !== 'error' && attempts < maxAttempts) {
      await new Promise(r => setTimeout(r, 1000));
      attempts++;
      try {
        const checkRes = await fetch(`https://api.netlify.com/api/v1/deploys/${deployId}`, {
          headers: { 'Authorization': `Bearer ${token}` }
        });
        if (checkRes.ok) {
          const checkData = await checkRes.json();
          state = checkData.state;
          if (checkData.ssl_url || checkData.url) {
            siteUrl = checkData.ssl_url || checkData.url;
          }
        }
      } catch (e) {
        // Ignorujeme dočasné výpadky sítě při dotazování
      }
    }

    if (state === 'error') {
      return { success: false, error: 'Zpracování deploye na Netlify selhalo.' };
    }

    if (!siteUrl) {
      siteUrl = deployData.ssl_url || deployData.url;
    }

    // 7. Odstranit lokální ZIP soubor
    try {
      fs.unlinkSync(zipPath);
    } catch (e) {}

    return { success: true, siteId, siteUrl };
  } catch (e) {
    return { success: false, error: e.message };
  }
});

// Otevření Netlify hlavní stránky pro vytvoření tokenu
ipcMain.handle('open-netlify', async () => {
  await shell.openExternal('https://app.netlify.com/user/settings/applications#personal-access-tokens');
  return true;
});

// Načtení obsahu HELP.md z disku
ipcMain.handle('read-help-file', async () => {
  const filePath = path.join(__dirname, 'HELP.md');
  if (fs.existsSync(filePath)) {
    try {
      return fs.readFileSync(filePath, 'utf8');
    } catch (e) {
      return '';
    }
  }
  return '';
});


