- saved_credit_cards = spree_current_user&.credit_cards&.with_payment_profile.to_a

%div{"data-controller": "stripe-cards", "data-paymentmethod-id": "#{payment_method.id}" }
  - if saved_credit_cards.any?
    .checkout-input
      %label
        = t('checkout.step2.form.stripe.use_saved_card')
      = select_tag :existing_card_id,
        options_for_select(stripe_card_options(saved_credit_cards) + [[t('checkout.step2.form.stripe.create_new_card'), ""]], nil),
        { "data-action": "change->stripe-cards#onSelectCard", "data-stripe-cards-target": "select" }

  %div{"data-stripe-cards-target": "stripeelements"}
    .checkout-input
      - if saved_credit_cards.none?
        %label
          = t('checkout.step2.form.stripe.use_new_card')

      %div{ "data-controller": "stripe", "data-stripe-key": "#{Stripe.publishable_key}" }
        .stripe-card
          = hidden_field_tag "order[payments_attributes][][source_attributes][first_name]", @order.bill_address.first_name
          = hidden_field_tag "order[payments_attributes][][source_attributes][last_name]", @order.bill_address.last_name
          = hidden_field_tag "order[payments_attributes][][source_attributes][month]", nil, { "data-stripe-target": "expMonth" }
          = hidden_field_tag "order[payments_attributes][][source_attributes][year]", nil, { "data-stripe-target": "expYear" }
          = hidden_field_tag "order[payments_attributes][][source_attributes][cc_type]", nil, { "data-stripe-target": "brand" }
          = hidden_field_tag "order[payments_attributes][][source_attributes][last_digits]", nil, { "data-stripe-target": "last4" }
          = hidden_field_tag "order[payments_attributes][][source_attributes][gateway_payment_profile_id]", nil, { "data-stripe-target": "pmId" }
          %div.card-element{ "data-stripe-target": "cardElement" }

        %div.error.card-errors{ "data-stripe-target": "cardErrors" }

    - if spree_current_user
      .checkout-input
        = check_box_tag "order[payments_attributes][][source_attributes][save_requested_by_customer]", 1, false
        = label_tag :order_payments_attributes__source_attributes_save_requested_by_customer, t('checkout.step2.form.stripe.save_card')

