<template>
  <div class="min-h-screen w-full p-4">
    <div class="container mx-auto flex items-center md:flex-row flex-col">
      <div class="
            flex flex-col
            md:pr-10 md:mb-0
            mb-6
            pr-0
            w-full
            md:w-auto md:text-left
            cursor-pointer
            text-center text-black
            dark:text-gray-200
          ">
        <img src="/favicon-lfk.png" class="h-20 mx-auto" />
        <h1 class="mb-6 text-3xl font-extrabold leading-none tracking-normal md:tracking-tight font-[Athiti]">
          Lauf Für Kaya!<br>2025</h1>
        <hr>
        <p class="mt-6 text-3xl font-bold whitespace-nowrap font-[Athiti]" v-text="(state.firstname || '') +
          ' ' +
          (state.middlename || '') +
          ' ' +
          (state.lastname || '')
          "></p>
        <p class="text-md whitespace-nowrap">Team: {{ state.group }}</p>
      </div>
      <div class="inline-flex md:ml-auto md:mr-0 mx-auto items-center">
        <div v-if="state.delete_active === false">
          <button type="button" class="
                focus:border-black focus:ring-2 focus:ring-black
                text-white text-base md:text-sm
                py-3.5
                px-5
                md:py-2.5
                md:px-5
                rounded-md
                bg-blue-500
                hover:bg-blue-600 hover:shadow-lg
                w-full
                md:w-auto
                cursor-pointer
                mb-1
                md:mr-1
              " @click="get_certificate">
            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none"
              stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
              class="inline h-4 align-sub">
              <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
              <polyline points="7 10 12 15 17 10" />
              <line x1="12" y1="15" x2="12" y2="3" />
            </svg>
            {{ $t("download_certificate") }}
          </button>

        </div>
      </div>
      <div class="flex flex-wrap">
        <div class="w-full">
          <div class="flex flex-wrap flex-col w-full tabs">
            <div class="flex lg:flex-wrap flex-row lg:space-x-2 justify-center">
              <div class="flex-none">
                <button @click="() => {
                  state.activetab = 'profile';
                }
                " :class="{
                  'tab-active border-b-2 font-medium border-blue-500':
                    state.activetab === 'profile',
                }" class="tab tab-underline cursor-pointer py-4 px-6 block" type="button">
                  {{ $t("profile") }}
                </button>
              </div>
              <div class="flex-none">
                <button @click="() => {
                  state.activetab = 'laptimes';
                }
                " :class="{
                  'tab-active border-b-2 font-medium border-blue-500':
                    state.activetab === 'laptimes',
                }" class="tab tab-underline cursor-pointer py-4 px-6 block" type="button">
                  {{ $t("lap_times") }}
                </button>
              </div>
              <div class="flex-none">
                <button @click="() => {
                  state.activetab = 'sponsorings';
                }
                " :class="{
                  'tab-active border-b-2 font-medium border-blue-500':
                    state.activetab === 'sponsorings',
                }" class="tab tab-underline cursor-pointer py-4 px-6 block" type="button">
                  {{ $t("sponsoring") }}
                </button>
              </div>
            </div>
            <div v-if="state.activetab === 'profile'" class="tab-content block container">
              <div class="lg:w-2/3 w-full mx-auto overflow-auto">
                <div class="flex flex-col container">
                  <form class="form flex flex-wrap w-full">
                    <div class="w-full">
                      <div class="form-element">
                        <div class="text-lg">{{ $t("registrationcode") }}</div>
                        <img class="w-full md:w-auto mb-2 bg-white p-2" alt="Registrierungscode" :src="state.barcode" />
                        <button type="button" class="
                focus:border-black focus:ring-2 focus:ring-black
                text-white text-base md:text-sm
                py-3.5
                px-5
                md:py-2.5
                md:px-5
                rounded-md
                bg-blue-500
                hover:bg-blue-600 hover:shadow-lg
                w-full
                md:w-auto
                cursor-pointer
                mb-1
                md:mr-1
              " @click="get_registration">
                          <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none"
                            stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
                            class="inline h-4 align-sub">
                            <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
                            <polyline points="7 10 12 15 17 10" />
                            <line x1="12" y1="15" x2="12" y2="3" />
                          </svg>
                          {{ $t("download_registrationcode") }}
                        </button>
                      </div>
                      <div class="form-element">
                        <div class="text-lg">{{ $t("e_mail_adress") }}</div>
                        <p class="
                          h-10
                          w-full
                          dark:bg-gray-800
                          rounded
                          text-base
                          outline-none
                          dark:text-gray-100
                          text-gray-600
                          py-1
                          px-3
                          leading-8
                          transition-colors
                          duration-200
                          ease-in-out
                        " v-text="state.email || '---'" />
                      </div>
                      <div class="form-element">
                        <div class="text-lg">{{ $t("phone_number") }}</div>
                        <p class="
                          h-10
                          w-full
                          dark:bg-gray-800
                          rounded
                          text-base
                          outline-none
                          dark:text-gray-100
                          text-gray-600
                          py-1
                          px-3
                          leading-8
                          transition-colors
                          duration-200
                          ease-in-out
                        " v-text="state.phone || '---'" />
                      </div>
                    </div>
                  </form>
                  <button type="button" class="
                focus:border-black focus:ring-2 focus:ring-black
                text-white text-base md:text-sm
                py-3.5
                px-5
                md:py-2.5
                md:px-5
                rounded-md
                bg-red-600
                hover:bg-red-700 hover:shadow-lg
                w-full
                md:w-auto
                cursor-pointer
              " @click="() => {
                state.delete_active = true;
              }
              ">
                    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none"
                      stroke="none" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
                      class="inline h-4 align-sub">
                      <path d="M0 0h24v24H0z" />
                      <path fill="currentColor"
                        d="M17 6h5v2h-2v13a1 1 0 01-1 1H5a1 1 0 01-1-1V8H2V6h5V3a1 1 0 011-1h8a1 1 0 011 1v3zm1 2H6v12h12V8zm-5 6l2 2-1 1-2-2-2 2-1-1 2-2-2-2 1-1 2 2 2-2 1 1-2 2zM9 4v2h6V4H9z" />
                    </svg>
                    {{ $t("delete_my_data") }}
                  </button>
                </div>
                <div v-if="state.delete_active === true">
                  <button type="button" class="
                focus:border-black focus:ring-2 focus:ring-black
                text-white text-base md:text-sm
                py-3.5
                px-5
                md:py-2.5
                md:px-5
                rounded-md
                mb-1
                md:mb-auto
                w-full
                md:w-auto
                cursor-pointer
                bg-blue-500
                hover:bg-blue-600 hover:shadow-lg
              " @click="() => {
                state.delete_active = false;
              }
              ">
                    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none"
                      stroke="none" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
                      class="inline h-4 align-sub">
                      <path fill="none" d="M0 0h24v24H0z" />
                      <path fill="currentColor" d="M12 11l5-5 1 1-5 5 5 5-1 1-5-5-5 5-1-1 5-5-5-5 1-1z" />
                    </svg>
                    {{ $t("cancel_keep_my_data") }}
                  </button>
                  <button type="button" class="
                focus:border-black focus:ring-2 focus:ring-black
                text-white text-base md:text-sm
                py-3.5
                px-5
                md:py-2.5
                md:px-5
                rounded-md
                w-full
                md:w-auto
                cursor-pointer
                bg-red-600
                hover:bg-red-700 hover:shadow-lg
                md:ml-1
              " @click="delete_me">
                    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none"
                      stroke="none" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
                      class="inline h-4 align-sub">
                      <path d="M0 0h24v24H0z" />
                      <path fill="currentColor"
                        d="M17 6h5v2h-2v13a1 1 0 01-1 1H5a1 1 0 01-1-1V8H2V6h5V3a1 1 0 011-1h8a1 1 0 011 1v3zm1 2H6v12h12V8zm-5 6l2 2-1 1-2-2-2 2-1-1 2-2-2-2 1-1 2 2 2-2 1 1-2 2zM9 4v2h6V4H9z" />
                    </svg>
                    {{ $t("confirm_delete_all_of_my_data") }}
                  </button>
                </div>
              </div>
            </div>
          </div>
          <div v-if="state.activetab === 'laptimes'" class="tab-content block">
            <div class="py-4 w-full">
              <section class="dark:bg-gray-900 body-font">
                <div class="container mx-auto">
                  <div class="lg:w-2/3 w-full mx-auto">
                    <p class="mb-2">
                      {{ $t('total_distance') }}: {{ getReadableDistanceForUI() }}
                    </p>
                    <table v-if="state.scans.length > 0" class="table-auto w-full text-left whitespace-no-wrap">
                      <thead class="
                          text-black
                          bg-gray-300
                          dark:text-white
                          text-sm
                          dark:bg-gray-800
                        ">
                        <tr>
                          <th class="
                              px-4
                              py-3
                              title-font
                              tracking-wider
                              font-medium
                            ">
                            {{ $t("distance") }}
                          </th>
                          <th class="
                              px-4
                              py-3
                              title-font
                              tracking-wider
                              font-medium
                            ">
                            {{ $t("lap_time") }}
                          </th>
                        </tr>
                      </thead>
                      <tbody class="text-gray-900 dark:text-gray-50">
                        <tr v-for="s in state.scans" :key="s.id">
                          <td class="px-4 py-3">
                            <span v-text="s.distance_readable"></span>
                          </td>
                          <td class="px-4 py-3" v-text="s.lapTime_readable"></td>
                        </tr>
                      </tbody>
                    </table>
                    <div v-else class="
                        text-center
                        font-bold
                        text-black
                        dark:text-white
                        text-2xl
                      ">
                      <img src="../assets/empty_laps.svg" style="height: 25rem; margin: 0 auto"
                        :alt="[[$t('no_laps_scans_were_recorded_yet')]]" />
                      {{ $t("no_laps_scans_were_recorded_yet") }}
                    </div>
                  </div>
                </div>
              </section>
            </div>
          </div>
          <div v-if="state.activetab === 'sponsorings'" class="tab-content block">
            <div v-if="mode === 'add_sponsoring'">
              <h1 class="text-3xl">Sponsoring hinzufügen</h1>

              <form>
                <div class="mt-6 grid gap-4 lg:gap-6">
                  <!-- Grid -->
                  <div class="grid grid-cols-1 sm:grid-cols-2 gap-4 lg:gap-6">
                    <div>
                      <label for="sponsorvorname"
                        class="block mb-2 text-sm text-gray-700 font-medium dark:text-white">Vorname</label>
                      <input type="text" name="sponsorvorname" id="sponsorvorname" placeholder="Vorname des Sponsors"
                        class="py-2.5 sm:py-3 px-4 block w-full border-gray-200 rounded-lg border sm:text-sm focus:border-blue-500 focus:ring-blue-500 disabled:opacity-50 disabled:pointer-events-none dark:bg-neutral-900 dark:border-neutral-700 dark:text-neutral-400 dark:placeholder-neutral-500 dark:focus:ring-neutral-600">
                    </div>

                    <div>
                      <label for="sponsornachname"
                        class="block mb-2 text-sm text-gray-700 font-medium dark:text-white">Nachname</label>
                      <input type="text" name="sponsornachname" id="sponsornachname" placeholder="Nachname des Sponsors"
                        class="py-2.5 sm:py-3 px-4 block w-full border-gray-200 rounded-lg border sm:text-sm focus:border-blue-500 focus:ring-blue-500 disabled:opacity-50 disabled:pointer-events-none dark:bg-neutral-900 dark:border-neutral-700 dark:text-neutral-400 dark:placeholder-neutral-500 dark:focus:ring-neutral-600">
                    </div>
                  </div>
                  <div class="grid grid-cols-1 sm:grid-cols-2 gap-4 lg:gap-6">
                    <!-- End Grid -->

                    <div>
                      <label for="sponsortel"
                        class="block mb-2 text-sm text-gray-700 font-medium dark:text-white">Telefonnummer des
                        Sponsors</label>
                      <input type="tel" name="sponsortel" id="sponsortel" autocomplete="tel"
                        class="py-2.5 sm:py-3 px-4 block w-full border-gray-200 rounded-lg border sm:text-sm focus:border-blue-500 focus:ring-blue-500 disabled:opacity-50 disabled:pointer-events-none dark:bg-neutral-900 dark:border-neutral-700 dark:text-neutral-400 dark:placeholder-neutral-500 dark:focus:ring-neutral-600">
                    </div>

                    <div>
                      <label for="sponsormail"
                        class="block mb-2 text-sm text-gray-700 font-medium dark:text-white">E-Mail
                        des Sponsors</label>
                      <input type="email" name="sponsormail" id="sponsormail"
                        class="py-2.5 sm:py-3 px-4 block w-full border-gray-200 rounded-lg border sm:text-sm focus:border-blue-500 focus:ring-blue-500 disabled:opacity-50 disabled:pointer-events-none dark:bg-neutral-900 dark:border-neutral-700 dark:text-neutral-400 dark:placeholder-neutral-500 dark:focus:ring-neutral-600">
                    </div>

                  </div>
                  <div>
                    <label for="eurokilometer"
                      class="block mb-2 text-sm text-gray-700 font-medium dark:text-white">Sponsoring pro Kilometer in
                      €</label>
                    <input type="number" name="eurokilometer" id="eurokilometer" placeholder="z.B. 1€ ODER 0,50€"
                      class="py-2.5 sm:py-3 px-4 block w-full border-gray-200 rounded-lg border sm:text-sm focus:border-blue-500 focus:ring-blue-500 disabled:opacity-50 disabled:pointer-events-none dark:bg-neutral-900 dark:border-neutral-700 dark:text-neutral-400 dark:placeholder-neutral-500 dark:focus:ring-neutral-600">
                  </div>
                </div>
              </form>
              <!-- End Grid -->

              <!-- Checkbox -->
              <div class="mt-3 flex">
                <div class="flex">
                  <input id="remember-me" name="remember-me" type="checkbox"
                    class="shrink-0 mt-1.5 border-gray-200 rounded-sm text-blue-600 focus:ring-blue-500 dark:bg-neutral-800 dark:border-neutral-700 dark:checked:bg-blue-500 dark:checked:border-blue-500 dark:focus:ring-offset-gray-800">
                </div>
                <div class="ms-3">
                  <label for="remember-me" class="text-sm text-gray-600 dark:text-neutral-400">Mit dem Absenden
                    bestätige ich, dass der Sponsor mit der Übermittlung seiner Daten einverstanden ist und ich dessen
                    Berechtigung habe</label>
                </div>
              </div>
              <!-- End Checkbox -->

              <div class="mt-6 grid">
                <button type="submit"
                  class="w-full py-3 px-4 inline-flex justify-center items-center gap-x-2 text-sm font-medium rounded-lg border border-transparent bg-blue-600 text-white hover:bg-blue-700 focus:outline-hidden focus:bg-blue-700 disabled:opacity-50 disabled:pointer-events-none">Sponsoring
                  hinzufügen</button>
              </div>
            </div>
            <div v-else>
              <div class="py-4 w-full">
                <section class="dark:bg-gray-900 body-font">
                  <div class="container mx-auto">
                    <div class="lg:w-2/3 w-full mx-auto overflow-auto">
                      <table v-if="state.sponsorings.length > 0" class="table-auto w-full text-left whitespace-no-wrap">
                        <thead class="
                      text-black
                      bg-gray-300
                          dark:text-white
                          text-sm
                          dark:bg-gray-800
                        ">
                          <tr>
                            <th class="
                              px-4
                              py-3
                              title-font
                              tracking-wider
                              font-medium
                            ">
                              Name
                            </th>
                            <th class="
                          px-4
                              py-3
                              title-font
                              tracking-wider
                              font-medium
                            ">
                              {{ $t("amount_per_kilometer_in_eur") }}
                            </th>
                            <th class="
                              px-4
                              py-3
                              title-font
                              tracking-wider
                              font-medium
                            ">
                              {{ $t("current_total_amount_in_eur") }}
                            </th>
                          </tr>
                        </thead>
                        <tbody class="text-gray-900 dark:text-gray-50">
                          <tr v-for="s in state.sponsorings" :key="s.id">
                            <td class="px-4 py-3">
                              <span v-text="s.donor.firstname + ' '"></span>
                              <span v-if="s.donor.middlename">
                                <span v-text="s.donor.middlename"></span>
                              </span>
                              <span v-text="s.donor.lastname"></span>
                            </td>
                            <td class="px-4 py-3">
                              <span v-text="(s.amountPerDistance / 100)
                                .toFixed(2)
                                .toLocaleString('de-DE', { valute: 'EUR' })
                                "></span>€
                            </td>
                            <td class="px-4 py-3">
                              <span v-text="(s.amount / 100)
                                .toFixed(2)
                                .toLocaleString('de-DE', { valute: 'EUR' })
                                "></span>€
                            </td>
                          </tr>
                        </tbody>
                        <tfoot class="text-gray-900 dark:text-gray-50">
                          <tr>
                            <td class="px-4 py-3">{{ $t("total") }}</td>
                            <td class="px-4 py-3">
                              <span v-text="(
                                state.sponsorings.reduce(function (
                                  sum,
                                  current
                                ) {
                                  return sum + current.amountPerDistance;
                                },
                                  0) / 100
                              )
                                .toFixed(2)
                                .toLocaleString('de-DE', { valute: 'EUR' })
                                "></span>€
                            </td>
                            <td class="px-4 py-3">
                              <span v-text="(
                                state.sponsorings.reduce(function (
                                  sum,
                                  current
                                ) {
                                  return sum + current.amount;
                                },
                                  0) / 100
                              )
                                .toFixed(2)
                                .toLocaleString('de-DE', { valute: 'EUR' })
                                "></span>€
                            </td>
                          </tr>
                        </tfoot>
                      </table>
                      <div v-else class="
                        text-center
                        font-medium
                        text-black
                        dark:text-white
                        text-xl
                        ">
                        <img src="../assets/empty_laps.svg" class="h-56 mx-auto" :alt="[
                          [$t('no_sponsorings_for_you_were_recorded_yet')],
                        ]" />
                        {{ $t("no_sponsorings_for_you_were_recorded_yet") }}
                      </div>
                      <button @click="mode = 'add_sponsoring'">Sponsoring hinzufügen</button>
                    </div>
                  </div>
                </section>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!--  -->
    <Footer></Footer>
  </div>
</template>

<script setup>
import { reactive, ref } from "vue";
import { TYPE, useToast } from "vue-toastification";
import axios from "redaxios";
import { toCanvas } from "bwip-js";
import Footer from "@/components/Footer.vue";
import { useI18n } from 'vue-i18n'
const { t } = useI18n()
const mode = ref("")

function textToBase64Barcode(text) {
  const canvas = document.createElement("canvas");
  let codeconfig = {
    bcid: config.code_format || "code128",
    text: `${text}`,
    scale: 3,
    includetext: false,
    textxalign: "center",
    backgroundcolor: "ffffff",
  };
  if (
    codeconfig.bcid === "code39" ||
    codeconfig.bcid === "code128" ||
    codeconfig.bcid === "ean13"
  ) {
    codeconfig.height = 10;
  }
  toCanvas(canvas, codeconfig);
  return canvas.toDataURL("image/png");
}

const state = reactive({
  barcode: "",
  phone: "",
  email: "",
  firstname: "",
  middlename: "",
  lastname: "",
  scans: [],
  sponsorings: [],
  group: "",
  activetab: "profile",
  delete_active: false,
  fullobject: {},
});
const toast = useToast();
const props = defineProps({
  token: String,
});
const accesstoken = props.token;

function getReadableDistanceForUI() {
  return state.scans.reduce((accumulator, currentValue) => accumulator + currentValue.distance, 0)
}

function getReadableDistance(distance) {
  const km = Math.floor(distance / 1000)
  const m = Math.floor(distance % 1000)
  console.log({ km, m });
  if (km > 0) {
    return `${km},${m} km`
  }
  return `${m} m`
}

axios
  .get(`${config.baseurl}api/runners/me/${accesstoken}`)
  .then(({ data }) => {
    state.phone = data.phone;
    state.email = data.email;
    state.firstname = data.firstname;
    state.middlename = data.middlename;
    state.lastname = data.lastname;
    state.group = data.group;
    state.sponsorings = data.distanceDonations;
    state.fullobject = data;
    state.barcode = textToBase64Barcode(data.id ?? "???");
  })
  .catch((error) => {
    toast.clear();
    toast.error(t('profil_konnte_nicht_geladen_werden'));
  });
axios
  .get(`${config.baseurl}api/runners/me/${accesstoken}/scans`)
  .then(({ data }) => {
    let counter = 0
    data.map(function (s) {
      if (counter === 0) {
        s.lapTime_readable = t('first_lap')
      } else {
        s.lapTime_readable =
          Math.floor(s.lapTime / 60) +
          "min " +
          (Math.floor(s.lapTime % 60) + "").padStart(2, "0") +
          "s";
      }
      s.distance_readable = getReadableDistance(s.distance);
      counter++;
      return s;
    });
    data.filter((s) => s.valid === true);
    state.scans = data;
  })
  .catch((error) => {
    toast.error(t('profil_konnte_nicht_geladen_werden'));
  });
function delete_me() {
  toast.clear();
  toast(t('profil_wird_geloescht'));
  let url = `${config.baseurl}api/runners/me/${accesstoken}?force=true`;
  axios
    .delete(url)
    .then(() => {
      toast.clear();
      toast(t('alle_daten_geloescht'));
      location.replace(`/`);
    })
    .catch((error) => {
      toast.clear();
      toast.error(t('profil_konnte_nicht_geloescht_werden'));
    });
}
function get_certificate() {
  toast(t('urkunde_wird_generiert'));
  const browserlocale = (
    (navigator.languages && navigator.languages[0]) ||
    ""
  ).substr(0, 2);
  let url = `${config.baseurl_documentserver}/v1/pdfs/certificates?key=${config.documentserver_key}`;
  let postdata = {
    locale: browserlocale,
    runners: [
      {
        first_name: state.firstname,
        middle_name: state.middlename,
        last_name: state.lastname,
        id: state.fullobject.id,
        distance: state.fullobject.distance,
        group: {
          name: state.group,
          id: state.fullobject.group.id || 0,
        },
        distance_donations: state.fullobject.distanceDonations.map((s) => {
          return {
            id: s.id || 0,
            amount: s.amount,
            amount_per_distance: s.amountPerDistance,
            donor: {
              id: s.donor.id || 0,
              first_name: s.donor.firstname,
              middle_name: s.donor.middlename,
              last_name: s.donor.lastname,
            },
          };
        }),
      }
    ]
  };
  axios
    .post(url, postdata, {
      responseType: "blob",
    })
    .then((response) => {
      console.log(response);
      if (response.status !== 200) {
        toast.error(t('urkunde_konnte_nicht_generiert_werden'));
      } else {
        var fileURL = window.URL.createObjectURL(
          new Blob([response.data], { type: "application/pdf" })
        );
        var fileLink = document.createElement("a");

        fileLink.href = fileURL;
        fileLink.setAttribute("download", "Certificate.pdf");
        document.body.appendChild(fileLink);

        fileLink.click();
        fileLink.remove();
        toast.clear();
        toast(t('urkunde_generiert'), { type: TYPE.SUCCESS });
      }
    })
    .catch((err) => {
      console.error(err);
      toast.clear();
      toast.error(t('urkunde_konnte_nicht_generiert_werden'));
    });
}
function get_registration() {
  toast.clear();
  toast(t('registrierungscode_wird_generiert'));
  var a = document.createElement("a");
  a.href = state.barcode;
  a.download = "LfK25_Registrierungscode.png";
  a.click();
  toast.clear();
  toast(t('registrierungscode_generiert'), { type: TYPE.SUCCESS });
}
</script>