{% extends "console_page.html" %}

{% block console_content %}
  {% if current_context.type == 'organization' %}
    {% with overview=org_billing_overview %}
    <div class="space-y-6">
      <div class="gobii-card-base p-6">
        <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
          <div>
            <h1 class="text-2xl font-semibold text-slate-900">{{ organization.name }} Billing</h1>
            <p class="text-sm text-slate-500 mt-1">Plan and credit status for the current billing period.</p>
          </div>
          <div class="text-right">
            <p class="text-xs uppercase tracking-wide text-slate-400">Billing Period</p>
            <p class="text-sm font-medium text-slate-700">{{ overview.period.start }} – {{ overview.period.end }}</p>
          </div>
        </div>

        <div class="mt-6 grid gap-4 md:grid-cols-3">
          <div class="border border-slate-100 rounded-lg p-4 bg-slate-50/60">
            <p class="text-xs font-medium uppercase tracking-wide text-slate-500">Plan</p>
            <p class="mt-1 text-base font-semibold text-slate-900">{{ overview.plan.name|default:"Free" }}</p>
            <p class="mt-2 text-sm text-slate-600">
              Seats: {{ overview.seats.purchased }} purchased · {{ overview.seats.reserved }} reserved · {{ overview.seats.available }} available
            </p>
            {% if overview.plan.monthly_price %}
            <p class="mt-2 text-sm text-slate-600">{{ overview.plan.monthly_price }} {{ overview.plan.currency|upper }}/seat</p>
            {% endif %}
          </div>

          <div class="border border-slate-100 rounded-lg p-4 bg-slate-50/60">
            <p class="text-xs font-medium uppercase tracking-wide text-slate-500">Task Credits</p>
            <p class="mt-1 text-sm text-slate-600">Granted: {{ overview.credits.granted|floatformat:0 }}</p>
            <p class="text-sm text-slate-600">Used: {{ overview.credits.used|floatformat:0 }}</p>
            <p class="text-sm text-slate-600">Available: {{ overview.credits.available|floatformat:0 }}</p>
            {% if overview.credits.entitlement %}
            <p class="text-xs text-slate-500 mt-1">Entitlement this period: {{ overview.credits.entitlement }}</p>
            {% endif %}
            <div class="mt-3">
              <div class="h-2 w-full bg-slate-200 rounded-full overflow-hidden">
                <div class="h-2 bg-gradient-to-r from-blue-500 to-blue-600" style="width: {{ org_credit_usage_pct }}%"></div>
              </div>
              <p class="mt-1 text-xs text-slate-500">{{ org_credit_usage_pct|floatformat:0 }}% used</p>
            </div>
          </div>

          <div class="border border-slate-100 rounded-lg p-4 bg-slate-50/60">
            <p class="text-xs font-medium uppercase tracking-wide text-slate-500">Extra Tasks</p>
            <p class="mt-1 text-sm text-slate-600">Configured limit: {% if overview.extra_tasks.configured_limit == -1 %}Unlimited{% else %}{{ overview.extra_tasks.configured_limit }}{% endif %}</p>
            <p class="text-sm text-slate-600">Plan limit: {% if overview.extra_tasks.limit == -1 %}Unlimited{% else %}{{ overview.extra_tasks.limit }}{% endif %}</p>
            <p class="text-sm text-slate-600">Used this period: {{ overview.extra_tasks.used_this_period }}</p>
            <p class="text-xs text-slate-500 mt-1">Auto purchase {% if overview.extra_tasks.enabled %}enabled{% else %}disabled{% endif %} for this subscription.</p>
          </div>
        </div>
      </div>

      {% if not org_can_manage_billing %}
        <div class="bg-amber-50 border border-amber-200 text-amber-900 rounded-lg px-4 py-3">
          You do not have billing permissions for this organization. Contact an owner, admin, or billing manager to make changes.
        </div>
      {% endif %}

      <div class="gobii-card-base p-6">
        <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
          <div>
            <h2 class="text-lg font-semibold text-slate-900">Seat Management</h2>
            <p class="text-sm text-slate-500">Purchased seats control how many members and invites your organization can have.</p>
          </div>
          {% if org_can_manage_billing and org_has_stripe_subscription %}
          <form method="post" action="{% url 'organization_seat_portal' organization.id %}">
            {% csrf_token %}
            <button type="submit" class="inline-flex items-center px-4 py-2 text-sm font-medium text-blue-600 border border-blue-100 rounded-md hover:bg-blue-50">
              Change Payment Method
            </button>
          </form>
          {% endif %}
        </div>

        <p class="mt-4 text-sm text-slate-600">
          Seats purchased: <span class="font-medium text-slate-900">{{ overview.seats.purchased }}</span> ·
          In Use: <span class="font-medium text-slate-900">{{ overview.seats.reserved }}</span> ·
          Available: <span class="font-medium text-slate-900">{{ overview.seats.available }}</span>
        </p>

        {% if seat_purchase_required %}
          <div class="mt-4 rounded-lg border border-amber-200 bg-amber-50 px-4 py-3">
            <h3 class="text-base font-semibold text-amber-900">Purchase seats to unlock organization features</h3>
            <p class="mt-1 text-sm text-amber-800">
              Organization members, shared credits, and org-owned agents become available once you add a paid seat.
            </p>
            {% if org_can_manage_billing %}
              <form method="post" action="{% url 'organization_seat_checkout' organization.id %}" class="mt-3 flex flex-col sm:flex-row sm:items-center sm:gap-3">
                {% csrf_token %}
                <div class="flex items-center gap-3">
                  {{ seat_purchase_form.seats.label_tag }}
                  {{ seat_purchase_form.seats }}
                </div>
                <button type="submit" class="mt-3 sm:mt-0 inline-flex items-center px-4 py-2 text-sm font-semibold text-white bg-blue-600 rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">Buy seats</button>
              </form>
              {% if seat_purchase_form.seats.help_text %}
                <p class="mt-2 text-sm text-amber-800">{{ seat_purchase_form.seats.help_text }}</p>
              {% endif %}
            {% else %}
              <p class="mt-3 text-sm text-amber-800">Contact an organization owner or billing admin to add seats.</p>
            {% endif %}
          </div>
        {% else %}
          <div class="mt-4 rounded-lg border border-blue-100 bg-blue-50 px-4 py-3">
            <h3 class="text-base font-semibold text-blue-900">Need more seats?</h3>
            <p class="mt-1 text-sm text-blue-900/80">Enter the number of additional seats to add to your current subscription. Stripe will prorate charges automatically.</p>
            {% if org_can_manage_billing %}
              <form method="post" action="{% url 'organization_seat_checkout' organization.id %}" class="mt-3 flex flex-col sm:flex-row sm:items-center sm:gap-3">
                {% csrf_token %}
                <div class="flex items-center gap-3">
                  {{ seat_purchase_form.seats.label_tag }}
                  {{ seat_purchase_form.seats }}
                </div>
                <button type="submit" class="mt-3 sm:mt-0 inline-flex items-center px-4 py-2 text-sm font-semibold text-white bg-blue-600 rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">Add seats</button>
              </form>
              {% if seat_purchase_form.seats.help_text %}
                <p class="mt-2 text-sm text-blue-900/80">{{ seat_purchase_form.seats.help_text }}</p>
              {% endif %}
            {% else %}
              <p class="mt-3 text-sm text-blue-900/80">Only organization owners, admins, or billing managers can purchase additional seats.</p>
            {% endif %}
          </div>
        {% endif %}

        {% if seat_purchase_form.seats.errors %}
          <p class="mt-2 text-sm text-red-700">{{ seat_purchase_form.seats.errors|join:", " }}</p>
        {% endif %}

        {% if org_can_manage_billing and org_has_stripe_subscription and overview.seats.purchased > 0 %}
          {% with pending=org_pending_seat_change %}
          <div class="mt-6 rounded-lg border border-slate-200 bg-white shadow-sm"
               x-data="{ open: false }">
            <button type="button"
                    class="w-full flex items-center justify-between gap-3 px-4 py-3 text-left"
                    @click="open = !open">
              <div>
                <h3 class="text-base font-semibold text-slate-900">Manage seat reductions</h3>
                <p class="mt-0.5 text-sm text-slate-600">
                  Schedule a lower seat count for the next billing cycle without affecting the current period.
                </p>
              </div>
              <span class="text-slate-500 transition-transform duration-200" :class="open ? 'rotate-180' : ''">
                ▲
              </span>
            </button>

            {% if pending.quantity is not None %}
              <div class="border-t border-slate-200 bg-blue-50/70 px-4 py-3 text-sm text-blue-900/80">
                <p>
                  Seat count will change to <span class="font-semibold text-blue-900">{{ pending.quantity }}</span>
                  {% if pending.effective_at %}
                    on {{ pending.effective_at|date:"F j, Y" }}.
                  {% else %}
                    at the start of the next billing cycle.
                  {% endif %}
                </p>
                <form method="post" action="{% url 'organization_seat_schedule_cancel' organization.id %}" class="mt-3">
                  {% csrf_token %}
                  <button type="submit" class="inline-flex items-center px-3 py-1.5 text-xs font-medium text-blue-700 bg-white border border-blue-100 rounded-md hover:bg-blue-50">
                    Cancel scheduled change
                  </button>
                </form>
              </div>
            {% endif %}

            <div x-show="open" x-cloak class="border-t border-slate-200 px-4 py-4">
              <form method="post" action="{% url 'organization_seat_schedule' organization.id %}" class="flex flex-col sm:flex-row sm:items-center sm:gap-3">
                {% csrf_token %}
                <div class="flex items-center gap-3">
                  {{ seat_reduction_form.future_seats.label_tag }}
                  {{ seat_reduction_form.future_seats }}
                </div>
                <button type="submit" class="mt-3 sm:mt-0 inline-flex items-center px-4 py-2 text-sm font-semibold text-white bg-slate-800 rounded-md hover:bg-slate-900 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-slate-900">
                  Schedule reduction
                </button>
              </form>
            </div>
          </div>
          {% endwith %}
        {% endif %}
      </div>

      {% include "console/partials/addons_block.html" with addon_context=addon_context addons_disabled=org_addons_disabled heading="Add-ons" subheading="Adjust task, contact, and browser task packs for this billing period." %}

      <div class="gobii-card-base p-6">
        <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-3">
          <div>
            <h2 class="text-lg font-semibold text-slate-900">Dedicated IPs</h2>
            <p class="text-sm text-slate-500 mt-1">Add or release static IPs reserved for this organization.</p>
            <p class="text-xs text-slate-500 mt-1">
              Each dedicated IP costs ${{ dedicated_ip_unit_price|floatformat:2 }} {{ dedicated_ip_currency }}/month.
            </p>
          </div>
        </div>

        {% if dedicated_ip_allowed %}
          {% if org_can_manage_billing %}
            <form method="post" action="{% url 'add_dedicated_ip_quantity' %}" class="mt-4 flex flex-col sm:flex-row sm:items-center sm:gap-3">
              {% csrf_token %}
              <div class="flex items-center gap-3">
                <span class="whitespace-nowrap text-sm font-medium text-slate-700">Add Dedicated IPs</span>
                {{ dedicated_ip_add_form.quantity }}
              </div>
              <button type="submit" class="mt-3 sm:mt-0 inline-flex items-center px-4 py-2 text-sm font-semibold text-white bg-blue-600 rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-600">
                Purchase Dedicated IPs
              </button>
            </form>
          {% else %}
            <div class="mt-4 rounded-md border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-900">
              You do not have permission to modify dedicated IPs for this organization.
            </div>
          {% endif %}
        {% else %}
          <div class="mt-4 rounded-md border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-900">
            {% if settings.GOBII_PROPRIETARY_MODE %}
              Upgrade to a <a href="{% url "proprietary:pricing" %}" title="Gobii Pro Plan" class="underline">Pro</a> or <a href="{% url "proprietary:pricing" %}" title="Gobii Scale Plan" class="underline">Scale</a> plan to enable dedicated IPs.
            {% else %}
              Dedicated IPs are not available in this deployment.
            {% endif %}
          </div>
        {% endif %}

        <p class="mt-4 text-sm text-slate-600">
          Allocated dedicated IPs: <span class="font-semibold text-slate-900">{{ dedicated_ip_total }}</span>
          {% if dedicated_ip_multi_assign %}
            (can be shared across agents).
          {% else %}
            (one IP per agent).
          {% endif %}
        </p>
        <p class="mt-2 text-sm text-slate-600">
          Current dedicated IP charges (monthly): <span class="font-semibold text-slate-900">${{ dedicated_ip_total_cost|floatformat:2 }} {{ dedicated_ip_currency }}</span> in addition to your plan price.
        </p>

        {% if dedicated_ip_proxies %}
          <div class="mt-4 divide-y divide-slate-200 rounded-md border border-slate-200 bg-white">
            {% for proxy in dedicated_ip_proxies %}
              <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2 px-4 py-3">
                <div>
                  <p class="text-sm font-medium text-slate-900">{{ proxy.static_ip|default:proxy.host }}</p>
                  <p class="text-xs text-slate-500">{{ proxy.name }}</p>
                </div>
                {% if org_can_manage_billing %}
                  <form method="post" action="{% url 'remove_dedicated_ip' %}" class="flex items-center gap-2">
                    {% csrf_token %}
                    <input type="hidden" name="proxy_id" value="{{ proxy.id }}">
                    <button type="submit" class="inline-flex items-center px-3 py-1.5 text-xs font-medium text-red-600 border border-red-100 rounded-md hover:bg-red-50">
                      Remove
                    </button>
                  </form>
                {% endif %}
              </div>
            {% endfor %}
          </div>
          {% if dedicated_ip_allowed and dedicated_ip_proxies|length > 1 and org_can_manage_billing %}
            <form method="post" action="{% url 'remove_all_dedicated_ip' %}" class="mt-3">
              {% csrf_token %}
              <button type="submit" class="inline-flex items-center px-4 py-2 text-sm font-medium text-red-600 border border-red-100 rounded-md hover:bg-red-50">
                Remove all dedicated IPs
              </button>
            </form>
          {% endif %}
        {% else %}
          <p class="mt-4 text-xs text-slate-500">No dedicated IPs have been provisioned yet.</p>
        {% endif %}
      </div>

      {% if account.paid == True %}
      <div class="gobii-card-base p-6"
           x-data="billingSettings({ enabled: {{ org_auto_purchase_state.enabled|yesno:'true,false' }}, infinite: {{ org_auto_purchase_state.infinite|yesno:'true,false' }}, maxTasks: {{ org_auto_purchase_state.max_tasks }}, canModify: {{ org_can_manage_billing|yesno:'true,false' }} })"
           x-init="loadSettings()">
        <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-3">
          <div>
            <h2 class="text-lg font-semibold text-slate-900">Auto-Purchase Extra Tasks</h2>
            <p class="text-sm text-slate-500">Automatically top up credits when the organization runs out.</p>
          </div>
          <div class="flex gap-3">
            {% if org_can_open_stripe %}
            <form method="post" action="{% url 'organization_seat_portal' organization.id %}">
              {% csrf_token %}
              <button type="submit" class="inline-flex items-center px-4 py-2 text-sm font-medium text-blue-600 border border-blue-100 rounded-md hover:bg-blue-50">Manage payment methods</button>
            </form>
            {% endif %}
          </div>
        </div>

        <div class="mt-6 space-y-4">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm font-medium text-slate-700">Enable automatic purchases</p>
              <p class="text-xs text-slate-500 mt-1">Keeps critical workflows running by granting additional credits on demand.</p>
            </div>
            <label class="relative inline-flex items-center cursor-pointer">
              <input type="checkbox" class="sr-only peer" x-model="enabled" @change="saveSettings()" :disabled="!canModify">
              <div class="w-11 h-6 bg-slate-200 peer-focus:outline-none peer-focus:ring-2 peer-focus:ring-blue-500 rounded-full peer peer-checked:bg-blue-600 transition"></div>
              <div class="absolute left-1 top-1 w-4 h-4 bg-white rounded-full transition peer-checked:translate-x-5"></div>
            </label>
          </div>

          <div class="pl-4 border-l-2 border-blue-100 space-y-3" x-show="enabled" x-collapse>
            <div class="flex items-center space-x-3">
              <div class="flex items-center h-5">
                <input id="limit-radio" type="radio" name="task_limit_type" class="h-4 w-4 rounded border-slate-300 text-blue-600 focus:ring-blue-500" :checked="!infinite" @click="infinite = false; saveSettings()" :disabled="!canModify">
              </div>
              <div class="flex items-center gap-2">
                <input type="number" min="1" max="100000" class="w-24 rounded-md border-slate-300 text-sm focus:border-blue-500 focus:ring-blue-500" x-model.number="maxTasks" @change="saveSettings()" :disabled="infinite || !canModify">
                <span class="text-sm text-slate-600">extra tasks per period</span>
              </div>
            </div>

            <div class="flex items-center space-x-3">
              <div class="flex items-center h-5">
                <input id="infinite-radio" type="radio" name="task_limit_type" class="h-4 w-4 rounded border-slate-300 text-blue-600 focus:ring-blue-500" :checked="infinite" @click="infinite = true; saveSettings()" :disabled="!canModify">
              </div>
              <label for="infinite-radio" class="text-sm text-slate-600">Allow unlimited extra tasks</label>
            </div>
          </div>
        </div>
      </div>
      {% endif %}
    </div>
    {% endwith %}
  {% else %}
    <div x-data="billingSettings()" x-init="loadSettings()">
      <div class="hs-accordion-group gobii-card-base">
        <div class="px-6 py-3 border-gray-200/70 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
          <div>
            <h1 class="text-2xl font-semibold text-gray-800">Billing</h1>
            <p class="text-sm text-gray-500 mt-1">Manage your subscription.</p>
          </div>
          {% if personal_can_open_stripe %}
          <form method="post" action="{% url 'billing_portal' %}">
            {% csrf_token %}
            <button type="submit" class="inline-flex items-center px-4 py-2 text-sm font-medium text-blue-600 border border-blue-100 rounded-md hover:bg-blue-50">
              Change Payment Method
            </button>
          </form>
          {% endif %}
        </div>
      <div class="px-6 pb-6">
        <div class="flex flex-col space-y-4">
          <!-- Subscription Plan -->
          <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between">
            <div class="flex flex-col">
              <span class="text-sm font-medium text-gray-500">Subscription Plan</span>
              <span class="text-lg font-semibold text-gray-800">{{ subscription_plan.name }}</span>
              {% if settings.GOBII_PROPRIETARY_MODE %}
              {% if not account.paid or account.plan == "startup" %}
              <span class="text-xs text-gray-400 mt-1">
                <a href="{% url 'proprietary:pricing' %}" class="underline" title="Upgrade for additional features, tasks, contacts, and more.">Upgrade</a>
              </span>
              {% endif %}
              {% endif %}
            </div>
            <div class="mt-2 sm:mt-0">
              <span class="inline-flex items-center py-1.5 px-3 rounded-full text-sm font-medium bg-blue-50 text-blue-700">
                ${{ subscription_plan.price|floatformat:2 }} {{ subscription_plan.currency }}/month
              </span>
            </div>
          </div>

            {% include "console/partials/addons_block.html" with addon_context=addon_context addons_disabled=personal_addons_disabled heading="Add-ons" subheading="Tune task, contact, and browser task packs for your subscription." card_class="border border-gray-200 rounded-lg p-4 bg-white shadow-sm space-y-3" %}

          <div class="border border-gray-200 rounded-lg p-4 bg-gray-50/70">
            <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
              <div>
                <p class="text-sm font-semibold text-gray-800">Dedicated IPs</p>
                <p class="text-xs text-gray-500 mt-1">Add new dedicated IPs or release ones you no longer need.</p>
                <p class="text-xs text-gray-500 mt-1">
                  Each dedicated IP costs ${{ dedicated_ip_unit_price|floatformat:2 }} {{ dedicated_ip_currency }}/month.
                </p>
              </div>
            </div>

            {% if dedicated_ip_allowed %}
              <form method="post" action="{% url 'add_dedicated_ip_quantity' %}" class="mt-3 flex flex-col sm:flex-row sm:items-center sm:gap-3">
                {% csrf_token %}
                <div class="flex items-center gap-3">
                  <span class="whitespace-nowrap text-sm font-medium text-gray-700">Add Dedicated IPs</span>
                  {{ dedicated_ip_add_form.quantity }}
                </div>
                <button type="submit" class="mt-3 sm:mt-0 inline-flex items-center px-4 py-2 text-sm font-semibold text-white bg-blue-600 rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-600">
                  Purchase Dedicated IPs
                </button>
              </form>
            {% else %}
              <div class="mt-3 rounded-md border border-yellow-200 bg-yellow-50 px-4 py-3 text-sm text-yellow-800">
                {% if settings.GOBII_PROPRIETARY_MODE %}
                  Upgrade to a <a href="{% url "proprietary:pricing" %}" title="Gobii Pro Plan" class="underline">Pro</a> or <a href="{% url "proprietary:pricing" %}" title="Gobii Scale Plan" class="underline">Scale</a> plan to enable dedicated IPs.
                {% else %}
                  Dedicated IPs are not available in this deployment.
                {% endif %}
              </div>
            {% endif %}

            <p class="mt-4 text-sm text-gray-600">
              Allocated dedicated IPs: <span class="font-semibold text-gray-800">{{ dedicated_ip_total }}</span>
              {% if dedicated_ip_multi_assign %}
                (can be shared across agents).
              {% else %}
                (one IP per agent).
              {% endif %}
            </p>
            <p class="mt-2 text-sm text-gray-600">
              Current dedicated IP charges (monthly): <span class="font-semibold text-gray-800">${{ dedicated_ip_total_cost|floatformat:2 }} {{ dedicated_ip_currency }}</span> in addition to your plan price.
            </p>

            {% if dedicated_ip_proxies %}
              <div class="mt-3 divide-y divide-gray-200 rounded-md border border-gray-200 bg-white">
                {% for proxy in dedicated_ip_proxies %}
                  <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2 px-4 py-3">
                    <div>
                      <p class="text-sm font-medium text-gray-800">{{ proxy.static_ip|default:proxy.host }}</p>
                      <p class="text-xs text-gray-500">{{ proxy.name }}</p>
                    </div>
                    <form method="post" action="{% url 'remove_dedicated_ip' %}" class="flex items-center gap-2">
                      {% csrf_token %}
                      <input type="hidden" name="proxy_id" value="{{ proxy.id }}">
                      <button type="submit" class="inline-flex items-center px-3 py-1.5 text-xs font-medium text-red-600 border border-red-100 rounded-md hover:bg-red-50">
                        Remove
                      </button>
                    </form>
                  </div>
                {% endfor %}
              </div>
              {% if dedicated_ip_allowed and dedicated_ip_proxies|length > 1 %}
                <form method="post" action="{% url 'remove_all_dedicated_ip' %}" class="mt-3">
                  {% csrf_token %}
                  <button type="submit" class="inline-flex items-center px-4 py-2 text-sm font-medium text-red-600 border border-red-100 rounded-md hover:bg-red-50">
                    Remove all dedicated IPs
                  </button>
                </form>
              {% endif %}
            {% else %}
              <p class="mt-3 text-xs text-gray-500">No dedicated IPs have been provisioned yet.</p>
            {% endif %}
          </div>
          {% if paid_subscriber %}
            <div class="border-t border-gray-100"></div>

            {% if cancel_at_period_end %}
            <div class="flex items-start">
              <div class="flex-shrink-0 mt-1">
                <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-red-500" viewBox="0 0 20 20" fill="currentColor">
                  <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clip-rule="evenodd" />
                </svg>
              </div>
              <div class="ml-3">
                <p class="text-sm font-medium text-red-600">Your subscription will be cancelled on</p>
                <p class="text-sm font-bold text-red-700 mt-1">{{ cancel_at }}</p>
              </div>
            </div>
            {% else %}
            <div class="flex items-start">
              <div class="flex-shrink-0 mt-1">
                <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-green-500" viewBox="0 0 20 20" fill="currentColor">
                  <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm1-12a1 1 0 10-2 0v4a1 1 0 00.293.707l2.828 2.829a1 1 0 101.415-1.415L11 9.586V6z" clip-rule="evenodd" />
                </svg>
              </div>
              <div class="ml-3">
                <p class="text-sm font-medium text-gray-500">Next Renewal</p>
                <p class="text-sm font-semibold text-gray-800 mt-1">{{ period_end_date }}</p>
              </div>
            </div>

            <div class="flex justify-end">
              <button type="button"
                      @click="showCancelModal = true"
                      class="py-2 px-4 inline-flex justify-center items-center gap-2 rounded-md border font-medium bg-white text-red-600 shadow-sm align-middle hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500 transition-all text-sm">
                <svg class="w-4 h-4" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
                </svg>
                Cancel Subscription
              </button>
            </div>
            {% endif %}

            {% if account.paid == True  %}
            <div class="border-t border-gray-100"></div>

            <div class="flex flex-col space-y-3">
              <div class="flex items-center justify-between">
                <div>
                  <span class="text-sm font-medium text-gray-700">Auto-purchase Extra Tasks</span>
                  <p class="text-xs text-gray-500 mt-1">Allow automatic purchase of additional tasks when needed</p>
                </div>
                <div class="hs-toggle flex items-center">
                  <input
                    type="checkbox"
                    id="auto-purchase-toggle"
                    class="relative w-[3.25rem] h-7 bg-gray-200 checked:bg-blue-600 rounded-full cursor-pointer transition-colors ease-in-out duration-200 border border-transparent ring-1 ring-transparent focus:border-blue-600 focus:ring-blue-600 ring-offset-white focus:outline-none appearance-none before:inline-block before:w-6 before:h-6 before:bg-white before:translate-x-0 checked:before:translate-x-full before:shadow before:rounded-full before:transform before:ring-0 before:transition before:ease-in-out before:duration-200"
                    x-model="enabled"
                    @change="saveSettings()"
                  >
                  <label for="auto-purchase-toggle" class="sr-only">Enable auto-purchase</label>
                </div>
              </div>
              {% endif %}

              <div x-show="enabled" x-transition class="pl-4 border-l-2 border-blue-100 space-y-3">
                <div class="flex items-center space-x-2">
                  <div class="flex items-center h-5">
                    <input
                      id="limited"
                      name="task_limit_type"
                      type="radio"
                      class="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                      :checked="!infinite"
                      @click="infinite = false; saveSettings()"
                    >
                  </div>
                  <div class="flex items-center space-x-2">
                    <input
                      type="number"
                      min="1"
                      max="10000"
                      x-model="maxTasks"
                      class="py-2 px-3 block w-full border-gray-300 rounded-md text-sm focus:border-blue-500 focus:ring-blue-500"
                      :disabled="infinite"
                      @change="saveSettings()"
                    >
                    <span class="text-sm text-gray-600">extra tasks</span>
                  </div>
                </div>

                <div class="flex items-center space-x-2">
                  <div class="flex items-center h-5">
                    <input
                      id="infinite"
                      name="task_limit_type"
                      type="radio"
                      class="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                      :checked="infinite"
                      @click="infinite = true; saveSettings()"
                    >
                  </div>
                  <label for="infinite" class="text-sm font-medium text-gray-700">Allow unlimited extra tasks</label>
                </div>
              </div>
            </div>
          {% endif %}
        </div>
      </div>
    </div>

    <div x-show="showCancelModal"
         x-cloak
         class="fixed inset-0 z-50 overflow-y-auto"
         aria-labelledby="modal-title"
         role="dialog"
         aria-modal="true">
      <div class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
        <div x-show="showCancelModal"
             x-transition:enter="ease-out duration-300"
             x-transition:enter-start="opacity-0"
             x-transition:enter-end="opacity-100"
             x-transition:leave="ease-in duration-200"
             x-transition:leave-start="opacity-100"
             x-transition:leave-end="opacity-0"
             class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity"
             aria-hidden="true"
             @click="showCancelModal = false"></div>

        <span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>

        <div x-show="showCancelModal"
             x-transition:enter="ease-out duration-300"
             x-transition:enter-start="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
             x-transition:enter-end="opacity-100 translate-y-0 sm:scale-100"
             x-transition:leave="ease-in duration-200"
             x-transition:leave-start="opacity-100 translate-y-0 sm:scale-100"
             x-transition:leave-end="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
             class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
          <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
            <div class="sm:flex sm:items-start">
              <div class="mx-auto flex-shrink-0 flex items-center justify-center h-12 w-12 rounded-full bg-amber-100 sm:mx-0 sm:h-10 sm:w-10">
                <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-amber-600" viewBox="0 0 20 20" fill="currentColor">
                  <path fill-rule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clip-rule="evenodd" />
                </svg>
              </div>
              <div class="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left">
                <h3 class="text-lg leading-6 font-medium text-gray-900" id="modal-title">
                  Cancel subscription
                </h3>
                <div class="mt-2">
                  <p class="text-sm text-gray-500">
                    Are you sure you want to cancel your subscription? You will retain access until the end of your current billing period.
                  </p>
                </div>
              </div>
            </div>
          </div>
          <div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
            <button type="button" id="confirm-cancel-subscription"
                    @click="cancelSubscription()"
                    class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-red-600 text-base font-medium text-white hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500 sm:ml-3 sm:w-auto sm:text-sm">
              Cancel Subscription
            </button>
            <button type="button"
                    @click="showCancelModal = false"
                    class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm">
              Keep My Subscription
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
  {% endif %}
{% endblock %}

  {% block extra_js %}
	  {{ block.super }}
	  <script>
	    const DEFAULT_MAX_TASKS = {{ extra_tasks_default_max_tasks }};
	    function billingSettings(initialState) {
	      const state = {
	        enabled: false,
	        infinite: false,
	        maxTasks: DEFAULT_MAX_TASKS,
	        canModify: true,
	        showCancelModal: false,
	        cancellationInProgress: false,

	        loadSettings() {
	          fetch('/api/v1/user/billing-settings/')
	            .then(response => response.json())
	            .then(data => {
	              this.canModify = data.can_modify !== undefined ? data.can_modify : true;
	              if (data.extra_tasks && typeof data.extra_tasks === 'object') {
	                this.enabled = Boolean(data.extra_tasks.enabled);
	                this.infinite = Boolean(data.extra_tasks.infinite);
	                this.maxTasks = Number.isFinite(data.extra_tasks.maxTasks) ? data.extra_tasks.maxTasks : DEFAULT_MAX_TASKS;
	                return;
	              }

	              if (data.max_extra_tasks === -1) {
	                this.enabled = true;
	                this.infinite = true;
	                this.maxTasks = DEFAULT_MAX_TASKS;
	              } else if (data.max_extra_tasks > 0) {
	                this.enabled = true;
	                this.infinite = false;
	                this.maxTasks = data.max_extra_tasks;
	              } else {
	                this.enabled = false;
	                this.infinite = false;
	                this.maxTasks = DEFAULT_MAX_TASKS;
	              }
	            })
	            .catch(error => {
	              console.error('Error loading billing settings:', error);
	            });
	        },

        saveSettings() {
          if (!this.canModify) {
            return;
          }

          fetch('/billing/settings/update/', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
              'X-CSRFToken': getCsrfTokenValue()
            },
            body: JSON.stringify({
              enabled: this.enabled,
              infinite: this.infinite,
              maxTasks: this.maxTasks
            })
          })
            .then(response => response.json())
            .then(data => {
              if (!data.success) {
                console.error('Error saving settings:', data.error);
              }
            })
            .catch(error => {
              console.error('Error saving settings:', error);
            });
        },

        cancelSubscription() {
          if (this.cancellationInProgress) return;

          this.cancellationInProgress = true;

          const button = document.getElementById('confirm-cancel-subscription');
          const originalContent = button.innerHTML;
          button.innerHTML = '<svg class="animate-spin -ml-1 mr-2 h-4 w-4 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path></svg> Cancelling...';

          fetch('/billing/settings/cancel-subscription/', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
              'X-CSRFToken': getCsrfTokenValue()
            }
          })
          .then(response => response.json())
          .then(data => {
            if (data.success) {
              window.location.reload();
            } else {
              console.error('Error cancelling subscription:', data.error);
              button.innerHTML = originalContent;
            }
          })
          .catch(error => {
            console.error('Failed to cancel subscription:', error);
            button.innerHTML = originalContent;
          })
          .finally(() => {
            this.cancellationInProgress = false;
          });
        },

        getCookie(name) {
          const value = `; ${document.cookie}`;
          const parts = value.split(`; ${name}=`);
          if (parts.length === 2) return parts.pop().split(';').shift();
        }
      };

      if (initialState && typeof initialState === 'object') {
        for (const key in initialState) {
          if (Object.prototype.hasOwnProperty.call(initialState, key)) {
            state[key] = initialState[key];
          }
        }
      }

      return state;
    }
  </script>
{% endblock %}
