(function () {
  const data = window.PinetaConfirmationData || null;
  if (!data) return;

  const STORAGE_KEY = 'hotel-pineta-lang';
  const supported = ['it','en','ru','uk','fr','de'];
  const localeMap = {it:'it-IT', en:'en-GB', ru:'ru-RU', uk:'uk-UA', fr:'fr-FR', de:'de-DE'};

  let lang = String(data.forceLanguage ? (data.language || 'ru') : (data.language || localStorage.getItem(STORAGE_KEY) || document.documentElement.lang || 'it')).toLowerCase().split('-')[0];
  if (!supported.includes(lang)) lang = data.forceLanguage ? 'ru' : 'it';

  const T = {
    it:{confirmationTitle:'Conferma della prenotazione',confirmationHelp:'La prenotazione è stata confermata dall’amministratore. Il messaggio può essere letto, copiato o scaricato.',copyConfirmation:'Copia conferma',downloadConfirmation:'Scarica conferma',downloadAs:'Formato',copied:'Copiato',hotel:'Hotel Pineta',confirmed:'Prenotazione confermata!',bookingCode:'Codice',discountCode:'Codice sconto fino al 25%',meal:'Pasto',name:'Cognome, Nome',details:'Dettagli prenotazione',nightsGuestsChildren:'Notti / ospiti / bambini fino a 2 anni',breakfastYes:'Con colazione',breakfastNo:'Senza colazione',arrival:'Data di arrivo',source:'Prenotato tramite',total:'Pagamento totale',prepayment:'Acconto',remaining:'Saldo',phone:'Telefono ospite',confirmedAt:'Data di conferma',children:'bambini fino a 2 anni',nightShort:' notte',guestShort:' ospiti'},
    en:{confirmationTitle:'Booking confirmation',confirmationHelp:'The booking has been confirmed by the administrator. The message can be read, copied or downloaded.',copyConfirmation:'Copy confirmation',downloadConfirmation:'Download confirmation',downloadAs:'Format',copied:'Copied',hotel:'Hotel Pineta',confirmed:'Booking confirmed!',bookingCode:'Code',discountCode:'Discount code up to 25%',meal:'Meal',name:'Last name, First name',details:'Booking details',nightsGuestsChildren:'Nights / guests / children under 2',breakfastYes:'With breakfast',breakfastNo:'Without breakfast',arrival:'Arrival date',source:'Booked via',total:'Total payment',prepayment:'Prepayment',remaining:'Balance',phone:'Guest phone',confirmedAt:'Confirmation date',children:'children under 2',nightShort:' night',guestShort:' guests'},
    ru:{confirmationTitle:'Подтверждение бронирования',confirmationHelp:'Бронь подтверждена администратором. Сообщение можно прочитать, скопировать или скачать.',copyConfirmation:'Скопировать подтверждение',downloadConfirmation:'Скачать подтверждение',downloadAs:'Формат',copied:'Скопировано',hotel:'Hotel Pineta',confirmed:'Бронирование подтверждено!',bookingCode:'Код',discountCode:'Код скидки До 25%',meal:'Питание',name:'Фамилия, Имя',details:'Детали бронирования',nightsGuestsChildren:'Кол-во ночей / кол-во гостей / дети до 2 лет',breakfastYes:'С завтраком',breakfastNo:'Без завтрака',arrival:'Дата заезда',source:'Забронировано через',total:'Оплата Итого',prepayment:'Предоплата',remaining:'Остаток',phone:'Телефон гостя',confirmedAt:'Дата подтверждения',children:'дети до 2 лет',nightShort:'ноч',guestShort:' чел'},
    uk:{confirmationTitle:'Підтвердження бронювання',confirmationHelp:'Бронь підтверджена адміністратором. Повідомлення можна прочитати, скопіювати або завантажити.',copyConfirmation:'Скопіювати підтвердження',downloadConfirmation:'Завантажити підтвердження',downloadAs:'Формат',copied:'Скопійовано',hotel:'Hotel Pineta',confirmed:'Бронювання підтверджено!',bookingCode:'Код',discountCode:'Код знижки До 25%',meal:'Харчування',name:'Прізвище, Ім’я',details:'Деталі бронювання',nightsGuestsChildren:'К-сть ночей / к-сть гостей / діти до 2 років',breakfastYes:'Зі сніданком',breakfastNo:'Без сніданку',arrival:'Дата заїзду',source:'Заброньовано через',total:'Оплата разом',prepayment:'Передоплата',remaining:'Залишок',phone:'Телефон гостя',confirmedAt:'Дата підтвердження',children:'діти до 2 років',nightShort:'ніч',guestShort:' осіб'},
    fr:{confirmationTitle:'Confirmation de réservation',confirmationHelp:'La réservation a été confirmée par l’administrateur. Le message peut être lu, copié ou téléchargé.',copyConfirmation:'Copier la confirmation',downloadConfirmation:'Télécharger la confirmation',downloadAs:'Format',copied:'Copié',hotel:'Hotel Pineta',confirmed:'Réservation confirmée !',bookingCode:'Code',discountCode:'Code de remise jusqu’à 25 %',meal:'Repas',name:'Nom, prénom',details:'Détails de la réservation',nightsGuestsChildren:'Nuits / clients / enfants de moins de 2 ans',breakfastYes:'Avec petit-déjeuner',breakfastNo:'Sans petit-déjeuner',arrival:'Date d’arrivée',source:'Réservé via',total:'Paiement total',prepayment:'Acompte',remaining:'Solde',phone:'Téléphone du client',confirmedAt:'Date de confirmation',children:'enfants de moins de 2 ans',nightShort:' nuit',guestShort:' pers.'},
    de:{confirmationTitle:'Buchungsbestätigung',confirmationHelp:'Die Buchung wurde vom Administrator bestätigt. Die Nachricht kann gelesen, kopiert oder heruntergeladen werden.',copyConfirmation:'Bestätigung kopieren',downloadConfirmation:'Bestätigung herunterladen',downloadAs:'Format',copied:'Kopiert',hotel:'Hotel Pineta',confirmed:'Buchung bestätigt!',bookingCode:'Code',discountCode:'Rabattcode bis zu 25 %',meal:'Verpflegung',name:'Nachname, Vorname',details:'Buchungsdetails',nightsGuestsChildren:'Nächte / Gäste / Kinder unter 2 Jahren',breakfastYes:'Mit Frühstück',breakfastNo:'Ohne Frühstück',arrival:'Anreisedatum',source:'Gebucht über',total:'Zahlung gesamt',prepayment:'Anzahlung',remaining:'Restbetrag',phone:'Telefon des Gastes',confirmedAt:'Bestätigungsdatum',children:'Kinder unter 2 Jahren',nightShort:' Nacht',guestShort:' Pers.'}
  };

  const tr = (k) => (T[lang] && T[lang][k]) || T.ru[k] || '';
  const money = (v) => { const n = Number(v || 0); return isFinite(n) ? `${n.toFixed(2)} €` : '—'; };
  const formatDate = (iso) => {
    if (!iso) return '—';
    const m = String(iso).match(/^(\d{4})-(\d{2})-(\d{2})$/);
    if (!m) return iso;
    return new Intl.DateTimeFormat(localeMap[lang] || 'ru-RU').format(new Date(Number(m[1]), Number(m[2]) - 1, Number(m[3])));
  };
  const sourceText = (src) => {
    const map = {site:'Site', booking:'Booking', whatsapp:'WhatsApp', telegram:'Telegram', admin:'Admin'};
    return map[String(src || '').toLowerCase()] || src || '—';
  };
  const normalizeGuestName = (name) => String(name || '—')
    .trim()
    .replace(/([а-яёіїєґ])([А-ЯЁІЇЄҐ])/g, '$1 $2')
    .replace(/([a-z])([A-Z])/g, '$1 $2')
    .replace(/\s+/g, ' ');
  const detailsValue = () => {
    const nights = data.nights || '—';
    const guests = data.guests || '—';
    const children = Number(data.childrenUnder2 || 0);
    const base = `${nights} ${String(tr('nightShort')).trim()}/${guests}${tr('guestShort')}`;
    return children > 0 ? `${base}/${tr('children')}` : base;
  };
  const prefixedBookingNumber = () => {
    const code = String(data.bookingNumber || '').trim();
    return code ? `№ ${code}` : '—';
  };
  const lineData = [
    [tr('bookingCode'), prefixedBookingNumber()],
    ...(data.discountCode ? [[tr('discountCode'), data.discountCode]] : []),
    [tr('name'), normalizeGuestName(data.guestName)],
    [tr('details'), detailsValue()],
    [tr('meal'), data.breakfast ? tr('breakfastYes') : tr('breakfastNo')],
    [tr('arrival'), formatDate(data.arrivalDate)],
    [tr('source'), sourceText(data.source)],
    [tr('total'), money(data.fullAmount)],
    [tr('prepayment'), money(data.prepaymentAmount)],
    [tr('remaining'), money(data.remainingAmount)],
    [tr('phone'), data.phone || '—'],
    [tr('confirmedAt'), formatDate(data.confirmedAt)]
  ];
  const text = `${tr('hotel')}
${tr('bookingCode')}: ${prefixedBookingNumber()}
${tr('confirmed')}

${lineData.slice(1).map(([k,v]) => k ? `${k}: ${v}` : v).join('\n')}`;

  function escapeHtml(value) {
    return String(value ?? '').replace(/[&<>"']/g, (ch) => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#039;'}[ch]));
  }

  document.querySelectorAll('[data-i18n="confirmationTitle"]').forEach(el => el.textContent = tr('confirmationTitle'));
  document.querySelectorAll('[data-i18n="confirmationHelp"]').forEach(el => el.textContent = tr('confirmationHelp'));
  document.querySelectorAll('[data-i18n="copyConfirmation"]').forEach(el => el.textContent = tr('copyConfirmation'));
  document.querySelectorAll('[data-i18n="downloadConfirmation"]').forEach(el => el.textContent = tr('downloadConfirmation'));
  document.querySelectorAll('[data-i18n="downloadAs"]').forEach(el => el.textContent = tr('downloadAs'));

  const preview = document.getElementById('bookingConfirmationPreview');
  if (preview) {
    preview.innerHTML = `<div class="confirm-top confirm-top-row"><img src="${escapeHtml(data.emblemUrl || '')}" alt="Hotel Pineta" class="created-emblem"><div class="confirm-heading-row"><div><div class="confirm-hotel">${escapeHtml(tr('hotel'))}</div><div class="confirm-code">${escapeHtml(tr('bookingCode'))}: ${escapeHtml(prefixedBookingNumber())}</div></div><div class="confirm-title">${escapeHtml(tr('confirmed'))}</div></div></div><div class="confirmation-lines">${lineData.slice(1).map(([k,v]) => k ? `<div><strong>${escapeHtml(k)}: </strong><span>${escapeHtml(v)}</span></div>` : `<div><strong></strong><span>${escapeHtml(v)}</span></div>`).join('')}</div>`;
  }

  const copyBtn = document.getElementById('copyBookingConfirmation');
  if (copyBtn) {
    copyBtn.addEventListener('click', () => {
      const old = copyBtn.textContent;
      navigator.clipboard.writeText(text).then(() => {
        copyBtn.textContent = tr('copied');
        setTimeout(() => copyBtn.textContent = old, 1400);
      });
    });
  }

  function loadImage(src) {
    return new Promise((resolve) => {
      if (!src) return resolve(null);
      const img = new Image();
      img.onload = () => resolve(img);
      img.onerror = () => resolve(null);
      img.src = src;
    });
  }

  function wrapText(ctx, textValue, maxWidth) {
    const words = String(textValue || '').split(/\s+/);
    const lines = [];
    let line = '';
    words.forEach((word) => {
      const test = line ? `${line} ${word}` : word;
      if (ctx.measureText(test).width > maxWidth && line) {
        lines.push(line);
        line = word;
      } else {
        line = test;
      }
    });
    if (line) lines.push(line);
    return lines.length ? lines : [''];
  }

  async function createConfirmationCanvas() {
    const width = 760;
    const padding = 40;
    const scale = 2;
    const rowGap = 18;
    const baseLines = 8 + lineData.length * 2;
    const height = Math.max(640, 230 + baseLines * 24);
    const canvas = document.createElement('canvas');
    canvas.width = width * scale;
    canvas.height = height * scale;
    const ctx = canvas.getContext('2d');
    ctx.scale(scale, scale);
    ctx.fillStyle = '#ffffff';
    ctx.fillRect(0, 0, width, height);
    ctx.strokeStyle = '#d9e7f5';
    ctx.lineWidth = 2;
    ctx.strokeRect(22, 22, width - 44, height - 44);

    let y = padding;
    const emblem = await loadImage(data.emblemUrl || '');
    if (emblem) {
      ctx.drawImage(emblem, padding, y, 68, 68);
    }
    ctx.fillStyle = '#0f172a';
    ctx.font = 'bold 28px Arial, sans-serif';
    ctx.fillText(tr('hotel'), padding + 88, y + 26);
    ctx.font = 'bold 18px Arial, sans-serif';
    ctx.fillText(`${tr('bookingCode')}: ${prefixedBookingNumber()}`, padding + 88, y + 54);
    ctx.fillStyle = '#166534';
    ctx.font = 'bold 26px Arial, sans-serif';
    ctx.fillText(tr('confirmed'), padding, y + 110);
    y += 145;

    ctx.fillStyle = '#0f172a';
    ctx.font = '16px Arial, sans-serif';
    lineData.slice(1).forEach(([label, value]) => {
      if (!label) {
        ctx.font = '18px Arial, sans-serif';
        const lines = wrapText(ctx, value, width - padding * 2);
        lines.forEach((ln) => {
          ctx.fillText(ln, padding, y);
          y += 24;
        });
        y += 4;
        return;
      }

      ctx.font = 'bold 17px Arial, sans-serif';
      const labelText = `${label}: `;
      ctx.fillText(labelText, padding, y);
      const labelWidth = ctx.measureText(labelText).width;
      ctx.font = '17px Arial, sans-serif';
      const valueLines = wrapText(ctx, value, width - padding * 2 - labelWidth);
      ctx.fillText(valueLines[0] || '', padding + labelWidth, y);
      y += 24;
      valueLines.slice(1).forEach((ln) => {
        ctx.fillText(ln, padding, y);
        y += 24;
      });
      y += rowGap - 16;
    });

    return canvas;
  }

  function downloadBlob(blob, filename) {
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    a.remove();
    URL.revokeObjectURL(url);
  }

  function binaryStringToUint8Array(str) {
    const arr = new Uint8Array(str.length);
    for (let i = 0; i < str.length; i += 1) arr[i] = str.charCodeAt(i) & 0xff;
    return arr;
  }

  function buildPdfFromJpeg(dataUrl, imageWidth, imageHeight) {
    const imgBinary = atob(dataUrl.split(',')[1] || '');
    const pageW = 595.28;
    const pageH = 841.89;
    const margin = 28;
    let drawW = pageW - margin * 2;
    let drawH = imageHeight / imageWidth * drawW;
    if (drawH > pageH - margin * 2) {
      drawH = pageH - margin * 2;
      drawW = imageWidth / imageHeight * drawH;
    }
    const x = (pageW - drawW) / 2;
    const y = pageH - margin - drawH;
    const content = `q\n${drawW.toFixed(2)} 0 0 ${drawH.toFixed(2)} ${x.toFixed(2)} ${y.toFixed(2)} cm\n/Im0 Do\nQ\n`;
    const objects = [
      '<< /Type /Catalog /Pages 2 0 R >>',
      '<< /Type /Pages /Kids [3 0 R] /Count 1 >>',
      `<< /Type /Page /Parent 2 0 R /MediaBox [0 0 ${pageW} ${pageH}] /Resources << /XObject << /Im0 4 0 R >> >> /Contents 5 0 R >>`,
      `<< /Type /XObject /Subtype /Image /Width ${imageWidth} /Height ${imageHeight} /ColorSpace /DeviceRGB /BitsPerComponent 8 /Filter /DCTDecode /Length ${imgBinary.length} >>\nstream\n${imgBinary}\nendstream`,
      `<< /Length ${content.length} >>\nstream\n${content}endstream`
    ];
    let pdf = '%PDF-1.4\n';
    const offsets = [0];
    objects.forEach((obj, idx) => {
      offsets.push(pdf.length);
      pdf += `${idx + 1} 0 obj\n${obj}\nendobj\n`;
    });
    const xref = pdf.length;
    pdf += `xref\n0 ${objects.length + 1}\n0000000000 65535 f \n`;
    for (let i = 1; i < offsets.length; i += 1) {
      pdf += `${String(offsets[i]).padStart(10, '0')} 00000 n \n`;
    }
    pdf += `trailer\n<< /Size ${objects.length + 1} /Root 1 0 R >>\nstartxref\n${xref}\n%%EOF`;
    return new Blob([binaryStringToUint8Array(pdf)], {type:'application/pdf'});
  }

  const downloadBtn = document.getElementById('downloadBookingConfirmation');
  if (downloadBtn) {
    downloadBtn.addEventListener('click', async () => {
      const format = String(document.getElementById('bookingConfirmationFormat')?.value || 'txt').toLowerCase();
      const safeNumber = String(data.bookingNumber || 'booking').replace(/[^A-Za-z0-9_-]+/g, '-');
      if (format === 'txt') {
        downloadBlob(new Blob([text], {type:'text/plain;charset=utf-8'}), `Hotel-Pineta-confirmation-${safeNumber}.txt`);
        return;
      }
      const oldText = downloadBtn.textContent;
      downloadBtn.disabled = true;
      try {
        const canvas = await createConfirmationCanvas();
        if (format === 'jpg' || format === 'jpeg') {
          canvas.toBlob((blob) => {
            if (blob) downloadBlob(blob, `Hotel-Pineta-confirmation-${safeNumber}.jpg`);
            downloadBtn.disabled = false;
            downloadBtn.textContent = oldText;
          }, 'image/jpeg', 0.92);
          return;
        }
        const dataUrl = canvas.toDataURL('image/jpeg', 0.92);
        const pdfBlob = buildPdfFromJpeg(dataUrl, canvas.width, canvas.height);
        downloadBlob(pdfBlob, `Hotel-Pineta-confirmation-${safeNumber}.pdf`);
      } finally {
        if (format !== 'jpg' && format !== 'jpeg') {
          downloadBtn.disabled = false;
          downloadBtn.textContent = oldText;
        }
      }
    });
  }
})();
