{% extends "base.html" %}
{% import "macros/ui.html" as ui %}

{% block title %}{{ t(key="checkout-title", lang=lang | default(value='sk')) }}{% endblock title %}

{% block content %}
{% if packeta_api_key %}<script src="https://widget.packeta.com/v6/www/js/library.js"></script>{% endif %}

<h1 class="text-3xl font-bold text-on-surface-strong dark:text-on-surface-dark-strong">{{ t(key="checkout-title", lang=lang | default(value='sk')) }}</h1>

<form method="post" action="/checkout" hx-boost="false"
  x-data="{
    paymentMethod: '',
    accountType: '{{ prefill_account_type | default(value='personal') }}',
    carrier: '',
    carrierPrice: 0,
    requiresPoint: false,
    pointId: '',
    pointName: '',
    subtotal: {{ subtotal_cents }},
    packetaKey: '{{ packeta_api_key }}',
    fmt(c) { return (c / 100).toFixed(2) },
    pickPoint() {
      Packeta.Widget.pick(this.packetaKey, (point) => {
        if (point) { this.pointId = String(point.id); this.pointName = point.formatedValue || point.name }
      })
    },
    get canSubmit() {
      return this.paymentMethod && this.carrier && (!this.requiresPoint || this.pointId)
    }
  }"
  class="mt-6 grid gap-8 lg:grid-cols-3">

  <div class="space-y-6 lg:col-span-2">
    <!-- personal vs company. Fixed (read-only) for a logged-in account; a guest
         picks it and the choice will type any account they create. -->
    <fieldset class="space-y-3 rounded-radius border border-outline bg-surface p-6 dark:border-outline-dark dark:bg-surface-dark-alt">
      <legend class="px-1 text-sm font-semibold text-on-surface-strong dark:text-on-surface-dark-strong">{{ t(key="account-type", lang=lang | default(value='sk')) }}</legend>
      {% if account_fixed %}
      <div class="flex items-center gap-2">
        {% if prefill_account_type == "company" %}
        {{ ui::badge(label=t(key="account-company", lang=lang | default(value='sk')), variant="primary") }}
        {% else %}
        {{ ui::badge(label=t(key="account-personal", lang=lang | default(value='sk')), variant="neutral") }}
        {% endif %}
        <span class="text-xs text-on-surface/60 dark:text-on-surface-dark/60">{{ t(key="account-type-locked", lang=lang | default(value='sk')) }}</span>
      </div>
      {% else %}
      <div class="grid gap-3 sm:grid-cols-2">
        <label class="flex cursor-pointer items-center gap-3 rounded-radius border border-outline px-4 py-3 transition has-[:checked]:border-primary dark:border-outline-dark dark:has-[:checked]:border-primary-dark">
          {{ ui::radio(name="account_type", value="personal", attrs='x-model="accountType"') }}
          <span class="font-medium text-on-surface-strong dark:text-on-surface-dark-strong">{{ t(key="account-personal", lang=lang | default(value='sk')) }}</span>
        </label>
        <label class="flex cursor-pointer items-center gap-3 rounded-radius border border-outline px-4 py-3 transition has-[:checked]:border-primary dark:border-outline-dark dark:has-[:checked]:border-primary-dark">
          {{ ui::radio(name="account_type", value="company", attrs='x-model="accountType"') }}
          <span class="font-medium text-on-surface-strong dark:text-on-surface-dark-strong">{{ t(key="account-company", lang=lang | default(value='sk')) }}</span>
        </label>
      </div>
      {% endif %}
    </fieldset>

    <!-- company billing details (company accounts only) -->
    <fieldset x-show="accountType === 'company'" x-cloak class="space-y-4 rounded-radius border border-outline bg-surface p-6 dark:border-outline-dark dark:bg-surface-dark-alt">
      <legend class="px-1 text-sm font-semibold text-on-surface-strong dark:text-on-surface-dark-strong">{{ t(key="account-company-details", lang=lang | default(value='sk')) }}</legend>
      <div class="space-y-1.5">
        <label for="company_name" class="text-sm font-medium text-on-surface-strong dark:text-on-surface-dark-strong">{{ t(key="company-name", lang=lang | default(value='sk')) }}{{ ui::req() }}</label>
        {{ ui::input(name="company_name", id="company_name", value=prefill_company_name | default(value=''), autocomplete="organization") }}
      </div>
      <div class="grid gap-4 sm:grid-cols-3">
        <div class="space-y-1.5">
          <label for="company_id" class="text-sm font-medium text-on-surface-strong dark:text-on-surface-dark-strong">{{ t(key="company-ico", lang=lang | default(value='sk')) }}{{ ui::req() }}</label>
          {{ ui::input(name="company_id", id="company_id", value=prefill_company_id | default(value='')) }}
        </div>
        <div class="space-y-1.5">
          <label for="tax_id" class="text-sm font-medium text-on-surface-strong dark:text-on-surface-dark-strong">{{ t(key="company-dic", lang=lang | default(value='sk')) }}{{ ui::req() }}</label>
          {{ ui::input(name="tax_id", id="tax_id", value=prefill_tax_id | default(value='')) }}
        </div>
        <div class="space-y-1.5">
          <label for="vat_id" class="text-sm font-medium text-on-surface-strong dark:text-on-surface-dark-strong">{{ t(key="company-icdph", lang=lang | default(value='sk')) }} <span class="text-on-surface/50 dark:text-on-surface-dark/50">({{ t(key="field-optional", lang=lang | default(value='sk')) }})</span></label>
          {{ ui::input(name="vat_id", id="vat_id", value=prefill_vat_id | default(value='')) }}
        </div>
      </div>
    </fieldset>

    <!-- contact -->
    <fieldset class="space-y-4 rounded-radius border border-outline bg-surface p-6 dark:border-outline-dark dark:bg-surface-dark-alt">
      <legend class="px-1 text-sm font-semibold text-on-surface-strong dark:text-on-surface-dark-strong">{{ t(key="checkout-contact", lang=lang | default(value='sk')) }}</legend>
      <div class="space-y-1.5">
        <label for="email" class="text-sm font-medium text-on-surface-strong dark:text-on-surface-dark-strong">{{ t(key="checkout-email", lang=lang | default(value='sk')) }}{{ ui::req() }}</label>
        {{ ui::input(name="email", id="email", type="email", value=prefill_email | default(value=''), required=true, autocomplete="email") }}
      </div>
      <div class="space-y-1.5">
        <label for="customer_name" class="text-sm font-medium text-on-surface-strong dark:text-on-surface-dark-strong">{{ t(key="checkout-name", lang=lang | default(value='sk')) }}{{ ui::req() }}</label>
        {{ ui::input(name="customer_name", id="customer_name", value=prefill_name | default(value=''), required=true, autocomplete="name") }}
      </div>
      <div class="space-y-1.5">
        <label for="phone" class="text-sm font-medium text-on-surface-strong dark:text-on-surface-dark-strong">{{ t(key="checkout-phone", lang=lang | default(value='sk')) }}{{ ui::req() }}</label>
        <div class="flex gap-2">
          <!-- editable combobox: type freely or pick from the dropdown -->
          <div class="relative w-28 shrink-0" @click.outside="prefixOpen = false"
            x-data="{ prefixOpen: false, prefix: '{{ prefill_phone_prefix | default(value='+421') }}', opts: [
              { v: '+421', l: '🇸🇰 +421' }, { v: '+420', l: '🇨🇿 +420' },
              { v: '+43', l: '🇦🇹 +43' }, { v: '+49', l: '🇩🇪 +49' },
              { v: '+48', l: '🇵🇱 +48' }, { v: '+36', l: '🇭🇺 +36' },
              { v: '+44', l: '🇬🇧 +44' }, { v: '+39', l: '🇮🇹 +39' }, { v: '+33', l: '🇫🇷 +33' }
            ], get filtered() { return this.opts.filter(o => !this.prefix || o.v.includes(this.prefix)) } }">
            <input name="phone_prefix" type="text" x-model="prefix" required @focus="prefixOpen = true" @input="prefixOpen = true"
              aria-label="{{ t(key='checkout-phone', lang=lang | default(value='sk')) }}" autocomplete="tel-country-code" inputmode="tel"
              class="w-full rounded-radius border border-outline bg-surface py-2 pl-3 pr-7 text-sm text-on-surface focus:outline-2 focus:outline-primary dark:border-outline-dark dark:bg-surface-dark dark:text-on-surface-dark">
            <button type="button" tabindex="-1" @click="prefixOpen = !prefixOpen"
              class="absolute inset-y-0 right-0 flex w-7 items-center justify-center text-on-surface/60 dark:text-on-surface-dark/60">
              <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor"
                class="size-4 transition-transform" :class="prefixOpen && 'rotate-180'">
                <path stroke-linecap="round" stroke-linejoin="round" d="m19.5 8.25-7.5 7.5-7.5-7.5" />
              </svg>
            </button>
            <ul x-show="prefixOpen" x-cloak x-transition
              class="absolute z-20 mt-1 max-h-56 w-full overflow-auto rounded-radius border border-outline bg-surface p-1 shadow-lg dark:border-outline-dark dark:bg-surface-dark-alt">
              <template x-for="o in filtered" :key="o.v">
                <li><button type="button" @click="prefix = o.v; prefixOpen = false" x-text="o.l"
                  class="block w-full rounded-radius px-3 py-1.5 text-left text-sm text-on-surface transition hover:bg-surface-alt dark:text-on-surface-dark dark:hover:bg-surface-dark"></button></li>
              </template>
            </ul>
          </div>
          {{ ui::input(name="phone", id="phone", type="tel", value=prefill_phone | default(value=''), required=true, autocomplete="tel", placeholder="900 000 000", attrs='inputmode="tel"') }}
        </div>
      </div>
    </fieldset>

    <!-- shipping address -->
    <fieldset class="space-y-4 rounded-radius border border-outline bg-surface p-6 dark:border-outline-dark dark:bg-surface-dark-alt">
      <legend class="px-1 text-sm font-semibold text-on-surface-strong dark:text-on-surface-dark-strong">{{ t(key="checkout-shipping", lang=lang | default(value='sk')) }}</legend>
      <div class="space-y-1.5">
        <label for="address" class="text-sm font-medium text-on-surface-strong dark:text-on-surface-dark-strong">{{ t(key="checkout-address", lang=lang | default(value='sk')) }}{{ ui::req() }}</label>
        {{ ui::input(name="address", id="address", value=prefill_address | default(value=''), required=true, autocomplete="street-address") }}
      </div>
      <div class="grid gap-4 sm:grid-cols-3">
        <div class="space-y-1.5">
          <label for="city" class="text-sm font-medium text-on-surface-strong dark:text-on-surface-dark-strong">{{ t(key="checkout-city", lang=lang | default(value='sk')) }}{{ ui::req() }}</label>
          {{ ui::input(name="city", id="city", value=prefill_city | default(value=''), required=true, autocomplete="address-level2") }}
        </div>
        <div class="space-y-1.5">
          <label for="zip" class="text-sm font-medium text-on-surface-strong dark:text-on-surface-dark-strong">{{ t(key="checkout-zip", lang=lang | default(value='sk')) }}{{ ui::req() }}</label>
          {{ ui::input(name="zip", id="zip", value=prefill_zip | default(value=''), required=true, autocomplete="postal-code") }}
        </div>
        <div class="space-y-1.5">
          <label for="country" class="text-sm font-medium text-on-surface-strong dark:text-on-surface-dark-strong">{{ t(key="checkout-country", lang=lang | default(value='sk')) }}{{ ui::req() }}</label>
          <div class="relative" @click.outside="countryOpen = false"
            x-data="{ countryOpen: false, country: '{{ prefill_country | default(value=t(key='country-sk', lang=lang | default(value='sk'))) }}', opts: [
              { v: '{{ t(key='country-sk', lang=lang | default(value='sk')) }}', l: '🇸🇰 {{ t(key='country-sk', lang=lang | default(value='sk')) }}' },
              { v: '{{ t(key='country-cz', lang=lang | default(value='sk')) }}', l: '🇨🇿 {{ t(key='country-cz', lang=lang | default(value='sk')) }}' },
              { v: '{{ t(key='country-at', lang=lang | default(value='sk')) }}', l: '🇦🇹 {{ t(key='country-at', lang=lang | default(value='sk')) }}' },
              { v: '{{ t(key='country-de', lang=lang | default(value='sk')) }}', l: '🇩🇪 {{ t(key='country-de', lang=lang | default(value='sk')) }}' },
              { v: '{{ t(key='country-pl', lang=lang | default(value='sk')) }}', l: '🇵🇱 {{ t(key='country-pl', lang=lang | default(value='sk')) }}' },
              { v: '{{ t(key='country-hu', lang=lang | default(value='sk')) }}', l: '🇭🇺 {{ t(key='country-hu', lang=lang | default(value='sk')) }}' }
            ], get filtered() { return this.opts.filter(o => !this.country || o.v.toLowerCase().includes(this.country.toLowerCase())) } }">
            <input id="country" name="country" type="text" x-model="country" required @focus="countryOpen = true" @input="countryOpen = true"
              class="w-full rounded-radius border border-outline bg-surface py-2 pl-3 pr-8 text-sm text-on-surface focus:outline-2 focus:outline-primary dark:border-outline-dark dark:bg-surface-dark dark:text-on-surface-dark">
            <button type="button" tabindex="-1" @click="countryOpen = !countryOpen"
              class="absolute inset-y-0 right-0 flex w-8 items-center justify-center text-on-surface/60 dark:text-on-surface-dark/60">
              <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor"
                class="size-4 transition-transform" :class="countryOpen && 'rotate-180'">
                <path stroke-linecap="round" stroke-linejoin="round" d="m19.5 8.25-7.5 7.5-7.5-7.5" />
              </svg>
            </button>
            <ul x-show="countryOpen" x-cloak x-transition
              class="absolute z-20 mt-1 max-h-56 w-full overflow-auto rounded-radius border border-outline bg-surface p-1 shadow-lg dark:border-outline-dark dark:bg-surface-dark-alt">
              <template x-for="o in filtered" :key="o.v">
                <li><button type="button" @click="country = o.v; countryOpen = false" x-text="o.l"
                  class="block w-full rounded-radius px-3 py-1.5 text-left text-sm text-on-surface transition hover:bg-surface-alt dark:text-on-surface-dark dark:hover:bg-surface-dark"></button></li>
              </template>
            </ul>
          </div>
        </div>
      </div>
    </fieldset>

    <!-- carrier -->
    <fieldset class="space-y-3 rounded-radius border border-outline bg-surface p-6 dark:border-outline-dark dark:bg-surface-dark-alt">
      <legend class="px-1 text-sm font-semibold text-on-surface-strong dark:text-on-surface-dark-strong">{{ t(key="checkout-carrier", lang=lang | default(value='sk')) }}{{ ui::req() }}</legend>
      {% for m in shipping_methods %}
      <label class="flex cursor-pointer items-center justify-between gap-3 rounded-radius border border-outline px-4 py-3 transition has-[:checked]:border-primary dark:border-outline-dark dark:has-[:checked]:border-primary-dark">
        <span class="flex items-center gap-3">
          <!-- Penguin radio dot inline (the @change mixes nested single+double quotes, can't pass through a Tera macro arg) -->
          <input type="radio" name="carrier_code" value="{{ m.code }}" required
            @change="carrier='{{ m.code }}'; carrierPrice={{ m.price_cents }}; requiresPoint={{ m.requires_pickup_point }}; pointId=''; pointName=''"
            class="before:content[''] relative h-4 w-4 appearance-none rounded-full border border-outline bg-surface before:invisible before:absolute before:left-1/2 before:top-1/2 before:h-1.5 before:w-1.5 before:-translate-x-1/2 before:-translate-y-1/2 before:rounded-full before:bg-on-primary checked:border-primary checked:bg-primary checked:before:visible focus:outline-2 focus:outline-offset-2 focus:outline-outline-strong checked:focus:outline-primary disabled:cursor-not-allowed dark:border-outline-dark dark:bg-surface-dark dark:before:bg-on-primary-dark dark:checked:border-primary-dark dark:checked:bg-primary-dark dark:focus:outline-outline-dark-strong dark:checked:focus:outline-primary-dark">
          <span class="font-medium text-on-surface-strong dark:text-on-surface-dark-strong">{{ m.name }}</span>
        </span>
        <span class="tabular-nums text-on-surface/80 dark:text-on-surface-dark/80">{{ m.price }} {{ currency }}</span>
      </label>
      {% endfor %}

      <!-- pickup point (carriers that need one, e.g. Packeta) -->
      <div x-show="requiresPoint" x-cloak class="space-y-2 pt-1">
        <input type="hidden" name="pickup_point_id" x-model="pointId">
        <input type="hidden" name="pickup_point_name" x-model="pointName">
        {% if packeta_api_key %}
        <button type="button" @click="pickPoint()"
          class="inline-flex items-center rounded-radius border border-outline px-4 py-2 text-sm font-medium text-on-surface transition hover:bg-surface-alt dark:border-outline-dark dark:text-on-surface-dark dark:hover:bg-surface-dark-alt">
          {{ t(key="checkout-pick-point", lang=lang | default(value='sk')) }}
        </button>
        <p x-show="pointName" x-cloak class="text-sm text-on-surface/80 dark:text-on-surface-dark/80">
          <span class="font-medium">{{ t(key="checkout-chosen-point", lang=lang | default(value='sk')) }}:</span> <span x-text="pointName"></span>
        </p>
        {% else %}
        <label class="text-sm font-medium text-on-surface-strong dark:text-on-surface-dark-strong">{{ t(key="checkout-pickup-point", lang=lang | default(value='sk')) }}</label>
        <input type="text" x-model="pointName" @input="pointId = pointName"
          class="w-full rounded-radius border border-outline bg-surface px-3 py-2 text-sm text-on-surface focus:outline-2 focus:outline-primary dark:border-outline-dark dark:bg-surface-dark dark:text-on-surface-dark">
        {% endif %}
      </div>
    </fieldset>

    <!-- payment -->
    <fieldset class="space-y-3 rounded-radius border border-outline bg-surface p-6 dark:border-outline-dark dark:bg-surface-dark-alt">
      <legend class="px-1 text-sm font-semibold text-on-surface-strong dark:text-on-surface-dark-strong">{{ t(key="checkout-payment", lang=lang | default(value='sk')) }}{{ ui::req() }}</legend>
      <label class="flex cursor-pointer items-center gap-3 rounded-radius border border-outline px-4 py-3 transition has-[:checked]:border-primary dark:border-outline-dark dark:has-[:checked]:border-primary-dark">
        {{ ui::radio(name="payment_method", value="cod", attrs='required x-model="paymentMethod"') }}
        <span class="font-medium text-on-surface-strong dark:text-on-surface-dark-strong">{{ t(key="payment-cod", lang=lang | default(value='sk')) }}</span>
      </label>
      <label class="flex cursor-pointer items-center gap-3 rounded-radius border border-outline px-4 py-3 transition has-[:checked]:border-primary dark:border-outline-dark dark:has-[:checked]:border-primary-dark">
        {{ ui::radio(name="payment_method", value="bank_transfer", attrs='required x-model="paymentMethod"') }}
        <span class="font-medium text-on-surface-strong dark:text-on-surface-dark-strong">{{ t(key="payment-bank", lang=lang | default(value='sk')) }}</span>
      </label>
    </fieldset>

    <div class="space-y-1.5">
      <label for="note" class="text-sm font-medium text-on-surface-strong dark:text-on-surface-dark-strong">{{ t(key="checkout-note", lang=lang | default(value='sk')) }}</label>
      {{ ui::textarea(name="note", id="note", rows="3") }}
    </div>

    {% if logged_in_customer %}
    <!-- logged-in customers can persist this address to their profile for next time -->
    {{ ui::checkbox(name="save_profile", id="save_profile", label=t(key="checkout-save-profile", lang=lang | default(value='sk')), checked=true) }}
    {% endif %}

    {% if can_create_account %}
    <!-- guests may turn this order into an account (typed by their choice above) -->
    <div class="space-y-1.5 rounded-radius border border-outline bg-surface p-4 dark:border-outline-dark dark:bg-surface-dark-alt">
      {{ ui::checkbox(name="create_account", id="create_account", label=t(key="checkout-create-account", lang=lang | default(value='sk'))) }}
      <p class="pl-6 text-xs text-on-surface/60 dark:text-on-surface-dark/60">{{ t(key="checkout-create-account-hint", lang=lang | default(value='sk')) }}</p>
    </div>
    {% endif %}
  </div>

  <!-- summary -->
  <aside class="h-fit space-y-4 rounded-radius border border-outline bg-surface p-6 dark:border-outline-dark dark:bg-surface-dark-alt">
    <h2 class="text-sm font-semibold text-on-surface-strong dark:text-on-surface-dark-strong">{{ t(key="checkout-summary", lang=lang | default(value='sk')) }}</h2>
    <ul class="space-y-2 text-sm">
      {% for item in items %}
      <li class="flex justify-between gap-2">
        <span class="text-on-surface/80 dark:text-on-surface-dark/80">{{ item.name }} × {{ item.quantity }}</span>
        <span class="tabular-nums">{{ item.line_total }} {{ item.currency }}</span>
      </li>
      {% endfor %}
    </ul>
    <div class="space-y-1 border-t border-outline pt-3 text-sm dark:border-outline-dark">
      <div class="flex justify-between">
        <span class="text-on-surface/70 dark:text-on-surface-dark/70">{{ t(key="checkout-subtotal", lang=lang | default(value='sk')) }}</span>
        <span class="tabular-nums">{{ subtotal }} {{ currency }}</span>
      </div>
      <div class="flex justify-between">
        <span class="text-on-surface/70 dark:text-on-surface-dark/70">{{ t(key="checkout-shipping-cost", lang=lang | default(value='sk')) }}</span>
        <span class="tabular-nums" x-text="fmt(carrierPrice) + ' {{ currency }}'"></span>
      </div>
    </div>
    <div class="flex justify-between border-t border-outline pt-3 text-base font-bold dark:border-outline-dark">
      <span>{{ t(key="cart-total", lang=lang | default(value='sk')) }}</span>
      <span class="tabular-nums text-primary dark:text-primary-dark" x-text="fmt(subtotal + carrierPrice) + ' {{ currency }}'"></span>
    </div>
    {{ ui::button(label=t(key="checkout-place-order", lang=lang | default(value='sk')), type="submit", attrs=':disabled="!canSubmit"', extra="w-full", size="px-6 py-2.5 text-sm") }}
  </aside>
</form>
{% endblock content %}
