<subscription>
    
    <!--
    <dialog class="object fill sections" id="subscription_payment">
      <div class="section-headbar gray">
        <div class="ico"><i class="fa-solid fa-credit-card"></i></div>
        <div class="text">
          <strong>Payment</strong>
        </div>
        <div class="actions">
          
        </div>
      </div>
      <section class="col">
        <div class="info_tags">
          <div class="info_tag"><i class="fa-solid fa-people-group"></i><span>0 Seats</span></div>
          <div class="info_tag"><i class="fa-solid fa-dollar"></i><span>0/month</span></div>
          <div class="info_tag">
            <i class="fa-solid fa-gavel"></i>
            <span>A-Tracker $0/month</span>
          </div>
        </div>
        <div class="rowc split fill">
          <div class="items_list cards fill">
            <div class="item card" style="padding: 0px;">
              <div class="ico"><i class="fa-solid fa-credit-card"></i></div>
              <div class="text">
                <strong>VISA - 0000</strong>
                <span>00 / 00</span>
              </div>
              <div class="actions rowc tags info_tags">
                <div class="tag min active"><small>Default</small></div>
                <div class="info_tag dinamic clickable">
                  <span>Set default</span>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="buttons" style="width: auto">
          <button class="button go"><i class="fa-solid fa-check"></i><span>Confirm Subscription</span></button>
          <button class="button plus"><i class="fa-solid fa-credit-card"></i><span>Change Card</span></button>
        </div>
      </section>
    </dialog>
    -->


    <dialog if={this.company && action == 'list_cards'} class="object fill sections" id="subscription_payment">
      <div class="section-headbar gray">
        <div class="ico"><i class="fa-solid fa-credit-card"></i></div>
        <div class="text">
          <strong>Payment</strong>
        </div>
        <div class="actions">
          <!--{get_status()}-->
        </div>
      </div>
      <section class="col">
        <div class="info_tags">
          <div class="info_tag"><i class="fa-solid fa-people-group"></i><span>{company.total_seats} Seats</span></div>
          <div class="info_tag"><i class="fa-solid fa-dollar"></i><span>{company.total_seats * (current_plan ? current_plan.price : 0)}/month</span></div>
          <div class="info_tag" if={a_tracker_billing && !a_tracker_billing.is_free}>
            <i class="fa-solid fa-gavel"></i>
            <span>A-Tracker ${a_tracker_billing.total}/month</span>
          </div>
        </div>
        <div class="rowc split fill">
          <div class="items_list cards fill">
            <div class="item card" style="padding: 0px;" each={payment_method in payment_methods}>
              <div class="ico"><i class="fa-solid fa-credit-card"></i></div>
              <div class="text">
                <strong>{payment_method.brand} - {payment_method.last4}</strong>
                <span>{payment_method.exp_month} / {payment_method.exp_year}</span>
              </div>
              <div class="actions rowc  tags info_tags">
                <div class="tag min active" if={payment_method.id == parent.default_payment_method}><small>Default</small></div>
                <div class="info_tag  dinamic clickable" if={payment_method.id != parent.default_payment_method} onclick={parent.set_default_payment_method.bind(parent, payment_method.id)}>
                  <span>Set default</span>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="buttons" style="width: auto">
          <button class="button go" onclick={confirm_subscription.bind(this, 'standard')} if={!subscription}><i class="fa-solid fa-check"></i><span>Confirm Subscription</span></button>
          <button class="button plus" onclick={change_card}><i class="fa-solid fa-credit-card"></i><span>Change Card</span></button>
        </div>
      </section>
    </dialog>
    
    <dialog if={this.company && action == "add_card"}  class="object fill sections" id="add_card">
      <div class="section-headbar gray">
        <div class="ico"><i class="fa-solid fa-credit-card"></i></div>
        <div class="text">
          <strong>Add A Card</strong>
        </div>
      </div>
      <section>
        <form onsubmit={onsubmit}>
          <div class="form">
            <div class="form_inputs">
              <div class="form_input">
                <div class="input">
                  <div id="card-elements"></div>
                </div>
              </div>
              <div class="help warning" style="margin-bottom: 0px;">
                <div class="ico"><i class="fa-solid fa-circle-exclamation"></i></div>
                <div class="text">
                  <strong>This will replace any existing cards on file</strong>
                  <span>You will be billed at the current rate per user per month that is invited to this
                    company.<br/><br/>E.g. If the current rate is $79/month and you have invited
                    five other users to this company you will be billed $79 * 6 = $474/month.</span>
                </div>
              </div>
              <div class="help info" style="margin-bottom: 0px;">
                <div class="ico"><i class="fa-solid fa-circle-info"></i></div>
                <div class="text">
                  <strong>Note</strong>
                  <span>Each company you setup requires it's own subscription and
                    you are billed for users within that company. Data overages and additional
                    packages will be billed to this card as well.</span>
                </div>
              </div>
            </div>
            <div class="buttons">
              <button class="button send">
                <i class="fa-solid fa-credit-card"></i>
                <span>Add Card</span>
              </button>
              <button class="button cancel" onclick={set.bind(this, 'action', 'list_cards')} if={payment_methods.length}>
                <i class="fa-solid fa-xmark"></i>
                <span>Cancel</span>
              </button>
            </div>
          </div>
        </form>
      </section>
    </dialog>
    
    <overlay if={loading || get_company_loading}></overlay>



  <script>
    this.loading = false;
    this.get_company_loading = false
    this.action = 'add_card';
    this.payment_methods = [];
    this.subscription = null;
    this.company = null;
    this.current_plan = null;
    this.default_payment_method = null;
    this.a_tracker_billing = null;
    this.elements = null
    this.card_element = null;
    this.stripe = null
    this.stripe_loading = 'Loading Dependencies' // load stripe script

    this.get_status = ()=>{
      if(!this.company) return
      if(this.company.trial_end > moment().valueOf()) return `Trial ends on ${moment(Number(this.company.trial_end)).format('MM/DD/YYYY')}`
      else if(this.company.paid_seats) return `Active`
      else return `InActive`
    }

    this.confirm_subscription = async (plan = 'standard')=>{
      try{
        this.loading = true;
        this.update()

        let res = await harmony.post('/subscription', {
          token: this.store.token,
          plan: plan,
        })

        if(res.code != 200) throw res.errors

        this.get_payment_methods()

      }catch(e){
        this.loading = false;
        this.update()
        this.show_errors(e)
      }
    }

    this.change_card = () => {
      // Destroy existing Stripe element so it can remount into the new DOM node
      if (this.card_element) {
        this.card_element.destroy();
        this.card_element = null;
      }
      this.action = 'add_card';
      this.update();
      this.mount_stripe_elements();
    }

    this.onsubmit = async (e)=>{
      try{
        e.preventDefault()
        this.loading = true;
        this.update()

        let stripe_res = await this.stripe.createPaymentMethod({
          type: 'card',
          card: this.card_element,
        });
        if (!stripe_res || stripe_res.error) throw stripe_res.error;

        let res = await harmony.post('/subscription/payment_method', {
          token: this.store.token,
          payment_method_id: stripe_res.paymentMethod.id
        })

        if(res.code != 200) throw res.errors

        let methods = (res.payment_methods || []).map(pm => ({
          id:        pm.id,
          brand:     pm.card.brand,
          last4:     pm.card.last4,
          exp_month: pm.card.exp_month,
          exp_year:  pm.card.exp_year,
        }))

        if(!methods.length){
          this.action = 'add_card'
        }else{
          this.action = 'list_cards'
          this.payment_methods = methods
        }

        this.loading = false;
        this.update()

        // Only confirm subscription if one doesn't already exist
        if(!this.subscription) {
          this.confirm_subscription()
        }

      }catch(e){
        this.loading = false;
        this.update()
        this.show_errors(e)
      }
    }

    this.get_payment_methods = async ()=>{
      try{
        this.loading = true;
        this.update()

        let res = await harmony.get('/subscription/payment_method', {
          token: this.store.token,
        })

        if(res.code != 200) throw res.errors

        let methods = (res.payment_methods || []).map(pm => ({
          id: pm.id,
          brand: pm.card.brand,
          last4: pm.card.last4,
          exp_month: pm.card.exp_month,
          exp_year: pm.card.exp_year,
        }))

        if(!methods.length){
          this.action = 'add_card'
        }else{
          this.action = 'list_cards'
          this.payment_methods = methods
          this.subscription = res.subscription
          this.default_payment_method = res.default_payment_method || null
        }

        this.loading = false;
        this.update()

      }catch(e){
        this.loading = false;
        this.update()
        this.show_errors(e)
      }
    }

    this.set_default_payment_method = async (pm_id) => {
      try {
        this.loading = true;
        this.update();

        let res = await harmony.put('/subscription/payment_method/default', {
          token:             this.store.token,
          payment_method_id: pm_id,
        });

        if(res.code != 200) throw res.errors;

        this.default_payment_method = pm_id;
        this.loading = false;
        this.update();

      } catch(e) {
        this.loading = false;
        this.update();
        this.show_errors(e);
      }
    }

    this.get_company = async ()=>{
      try{
        this.get_company_loading = true;
        this.update()

        let res = await harmony.get('/company/current', {
          token: this.store.token,
        })

        if(res.code != 200) throw res.errors

        this.company = res.companies[0]
        this.get_company_loading = false;
        this.update()

      }catch(e){
        this.get_company_loading = false;
        this.update();
        this.show_errors(e)
      }
    }

    this.get_plans = async ()=>{
      try{
        let res = await harmony.get('/subscription/plans', {
          token: this.store.token,
        })

        if(res.code != 200) throw res.errors

        if(res.current_subscription){
          this.current_plan = res.plans.find(p => p.plan_label === res.current_subscription.plan) || null
        }

        this.update()

      }catch(e){
        this.show_errors(e)
      }
    }

    this.get_a_tracker_billing = async () => {
      try {
        let res = await harmony.get('/a_tracker/settings/billing', {
          token: this.store.token,
        });
        if (res.code != 200) return;
        this.a_tracker_billing = {
          total:    res.total    || 0,
          is_free:  res.is_free  === true,
          frequency: res.frequency,
          tier:     res.tier,
        };
        this.update();
      } catch(e) {
        // Silently skip — A-Tracker add-on is optional
      }
    }

    this.process_notification = (company)=>{
      this.company.paid_seats = company.paid_seats
      this.update()
    }

    this.mount_stripe_elements = async (retry = 0) => {
      if (this.card_element) {
        return false;
      }

      if (retry > 5) {
        console.warn('Stripe mount failed after multiple retries.');
        return;
      }

      try {
        this.loading = true;
        this.update();

        let res = await harmony.get('/subscription/publishable-key', {
          token: this.store.token
        });

        if (res.code != 200) throw res.errors

        let { stripe_connect } = res;

        this.stripe = Stripe(stripe_connect);
        this.elements = this.stripe.elements();

        let style = {
          base: {
            color: '#32325d',
            lineHeight: '18px',
            fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
            fontSmoothing: 'antialiased',
            fontSize: '16px',
            '::placeholder': {
              color: '#aab7c4'
            }
          },
          invalid: {
            color: '#fa755a',
            iconColor: '#fa755a'
          }
        };

        let element = this.root.querySelector('#card-elements')
        if (!element) {
          console.warn('Stripe mount target not found.');
          setTimeout(() => this.mount_stripe_elements(retry + 1), 100);
          return;
        }
        this.card_element = this.elements.create('card', {style: style});
        this.card_element.mount(element);

        this.loading = false;

        this.update();
      } catch (e) {

        this.loading = false;
        this.update();
        this.show_errors(e);
      }
    }


    this.on('mount', ()=>{
      harmony.on('notify /subscription', this.process_notification)

      // Surface why the user landed here (e.g. redirected by a 402 subscription block)
      let gate_message = window.location.search.match(/[?&]message=([^&]+)/)
      if(gate_message){
        this.messenger.emit('notice', {
          type: 'error',
          message: decodeURIComponent(gate_message[1].replace(/\+/g, ' '))
        })
      }

      this.get_payment_methods()
      this.get_company()
      this.get_plans()
      this.get_a_tracker_billing()

      let stripe_script = document.querySelector('#stripe_script');

      if (!stripe_script) {
        stripe_script = document.createElement('script')
        stripe_script.onload = () => {
          this.stripe_loading = false;
          this.mount_stripe_elements();
        }
        stripe_script.src = 'https://js.stripe.com/v3/'
        let head = document.querySelector('head')
        head.appendChild(stripe_script)
      }
    })

    this.on('unmount', ()=>{
      harmony.off('notify /subscription', this.process_notification)
      if (this.card_element) {
        this.card_element.destroy();
      }
    })
  </script>

  <style>

    
    .StripeElement {
      background-color: #F5F5F5;
      padding: 10px 12px;
      border-radius: 10px;
    }
    
    .StripeElement--focus {
      
    }
    
    .StripeElement--invalid {
      border-color: #fa755a;
    }
    
    .StripeElement--webkit-autofill {
      background-color: #fefde5 !important;
    }
    

  </style>
</subscription>
