---
import DefaultLayout from "../../layouts/DefaultLayout.astro";
import MapGoogle from "../../components/maps/MapGoogle.astro";

import yaml from "js-yaml";
import fs from "fs";

const data = yaml.load(
  fs.readFileSync("./src/content/contact/contact.yaml", "utf8"),
);

const seo = yaml.load(
  fs.readFileSync("./src/content/internet-swiatlowodowy/seo.yaml", "utf8"),
);

const apiKey = import.meta.env.PUBLIC_GOOGLE_MAPS_KEY;
const form = data.form;
---

<DefaultLayout seo={seo}>
<section class="f-section">
  <div class="f-section-grid md:grid-cols-2 gap-10 items-start">
    <div>
      <h2 class="f-section-title">{data.title}</h2>
      <div class="f-contact-item" set:html={data.description} />
    </div>

    <div>
      <h2 class="f-section-title">{data.contactFormTitle}</h2>
      <form id="contactForm" class="f-contact-form">
        <div class="f-contact-form-inner">
          <input
            type="text"
            name="firstName"
            placeholder={form.firstName.placeholder}
            class="f-input"
            required
          />
          <input
            type="text"
            name="lastName"
            placeholder={form.lastName.placeholder}
            class="f-input"
            required
          />
        </div>

        <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
          <input
            type="email"
            name="email"
            placeholder={form.email.placeholder}
            class="f-input"
            required
            autocomplete="email"
          />
          <input
            type="tel"
            name="phone"
            placeholder={form.phone.placeholder}
            class="f-input"
            required
            autocomplete="tel"
          />
        </div>

        <input
          type="text"
          name="subject"
          placeholder={form.subject.placeholder}
          class="f-input"
          required
        />

        <textarea
          name="message"
          rows={form.message.rows}
          placeholder={form.message.placeholder}
          class="f-input"
          required></textarea>

        <label class="f-rodo">
          <input type="checkbox" name="rodo" required />
          <span>
            {form.rodo.label}
            <a href={form.rodo.policyLink} title={form.rodo.policyTitle}>
              {form.rodo.policyText}
            </a>.
          </span>
        </label>

        <button type="submit" class="btn btn-primary w-full py-3" title={form.submit.title}>
          {form.submit.label}
        </button>
      </form>
    </div>
  </div>

  <div class="mt-10">
    <div class="f-contact-map">
      <MapGoogle
        apiKey={apiKey}
        lat={data.lat}
        lon={data.lng}
        zoom={16}
        title={data.markerTitle}
        description={data.markerAddress}
        showMarker={true}
        mode="contact"
        mapStyleId={data.maps.mapId}
      />
    </div>
  </div>

  <div id="toast" class="f-toast"></div>

  <input type="hidden" name="offerConfig" id="offerConfig" />
</section>

  <!-- ReCaptcha v3 -->
  <script
    is:inline
    define:vars={{ siteKey: import.meta.env.PUBLIC_RECAPTCHA_SITE_KEY }}
  >
    window.FUZ_RECAPTCHA_KEY = siteKey;

    const s = document.createElement("script");
    s.src = "https://www.google.com/recaptcha/api.js?render=" + siteKey;
    s.async = true;
    document.head.appendChild(s);
  </script>

  <script
    is:inline
    define:vars={{
      successMsg: form.successMessage,
      errorMsg: form.errorMessage,
    }}
  >
    document.addEventListener("DOMContentLoaded", () => {
      const form = document.getElementById("contactForm");
      const toast = document.getElementById("toast");

      if (!form) return;

      form.addEventListener("submit", async (e) => {
        if (!form.reportValidity()) return;
        e.preventDefault();

        const data = Object.fromEntries(new FormData(form).entries());
        data.rodo = form.rodo.checked;

        const token = await grecaptcha.execute(window.FUZ_RECAPTCHA_KEY, {
          action: "submit",
        });
        data.recaptcha = token;

        const resp = await fetch("/api/contact/contact", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(data),
        });

        const json = await resp.json();

        showToast(
          json.ok ? successMsg : errorMsg,
          json.ok ? "success" : "error",
        );

        if (json.ok) form.reset();
      });

      function showToast(msg, type) {
        toast.innerHTML = `<div class="f-toast-msg ${type}">${msg}</div>`;
        toast.classList.remove("visible");
        void toast.offsetWidth;
        toast.classList.add("visible");

        setTimeout(() => toast.classList.remove("visible"), 3000);
      }

      // ----------
      const LS_KEY = "fuz_offer_config_v1";

function formatOfferSummary(o) {
  if (!o || !o.pkg) return "";

  const lines = [];
  lines.push(`Wybrana oferta: ${o.pkg.name} (${o.totals?.base ?? 0} ${o.totals?.currencyLabel ?? ""})`);

  if (o.decoder) lines.push(`Dekoder: ${o.decoder.name} (+${o.decoder.price} ${o.totals?.currencyLabel ?? ""})`);
  if (o.phone) lines.push(`Telefon: ${o.phone.name} (+${o.phone.price} ${o.totals?.currencyLabel ?? ""})`);

  if (Array.isArray(o.tvAddons) && o.tvAddons.length) {
    lines.push("Pakiety TV:");
    o.tvAddons.forEach((x) => {
      const term = x.term ? `, ${x.term}` : "";
      lines.push(`- ${x.nazwa} x${x.qty} (${x.unit} ${o.totals?.currencyLabel ?? ""}${term})`);
    });
  }

  if (Array.isArray(o.addons) && o.addons.length) {
    lines.push("Dodatki:");
    o.addons.forEach((x) =>
      lines.push(`- ${x.nazwa} x${x.qty} (${x.unit} ${o.totals?.currencyLabel ?? ""})`),
    );
  }

  lines.push(`RAZEM: ${o.totals?.total ?? 0} ${o.totals?.currencyLabel ?? ""}`);
  return lines.join("\n");
}

function hydrateOfferIntoForm() {
  try {
    const raw = localStorage.getItem(LS_KEY);
    if (!raw) return;

    const payload = JSON.parse(raw);
    const msg = document.querySelector('textarea[name="message"]');
    const subject = document.querySelector('input[name="subject"]');

    const offerText =
      typeof payload?.message === "string" && payload.message.trim()
        ? payload.message
        : null;

    if (!offerText) return;

    if (subject && !subject.value) {
      subject.value = `Zapytanie: ${payload?.pkg?.name || "Oferta"}`;
    }

    if (msg) {
      msg.value = (msg.value ? msg.value + "\n\n" : "") + offerText;
    }
  } catch {}
}

hydrateOfferIntoForm();

      // ----------
    });
  </script>
</DefaultLayout>
