<%= form_with(model: letter, class: "form-container") do |form| %>
  <% if letter.errors.any? %>
    <div style="color: red">
      <h2><%= pluralize(letter.errors.count, "error") %> prohibited this letter from being saved:</h2>
      <ul>
        <% letter.errors.each do |error| %>
          <li><%= error.full_message %></li>
        <% end %>
      </ul>
    </div>
  <% end %>
  <div class="form-group">
    <%= form.label :user_facing_title, "Title", class: "form-label" %>
    <%= form.text_field :user_facing_title, class: "form-control", placeholder: "e.g. Monthly Newsletter" %>
  </div>
  <fieldset>
    <legend>Letter Specs</legend>
    <%= render partial: "letters/letter_attributes_form", locals: { form: form } %>
  </fieldset>
  <fieldset>
    <legend>Recipient Address</legend>
    <%= render partial: "addresses/nested_form", locals: { form: form } %>
  </fieldset>
  <fieldset>
    <legend>Return Address</legend>
    <div class="grid">
      <div>
        <%= form.label :return_address_id, "Select Return Address" %>
        <%= form.collection_select :return_address_id,
                                 ReturnAddress.shared.or(ReturnAddress.owned_by(current_user)),
                                 :id,
                                 :display_name,
                                 { prompt: "Select a return address...", selected: letter.return_address_id },
                                 { class: "form-control", data: { controller: "return-address" } } %>
        <small>
          <%= link_to "Manage Return Addresses", return_addresses_path(from_letter: true) %>
        </small>
      </div>
      <div class="form-group">
        <%= form.label :return_address_name, "Custom Return Address Name (optional)", class: "form-label" %>
        <%= form.text_field :return_address_name, class: "form-control", placeholder: "Leave blank to use the return address name" %>
      </div>
    </div>
  </fieldset>
  <fieldset>
    <legend>USPS Mailer ID</legend>
    <div class="grid">
      <div>
        <%= form.label :usps_mailer_id_id, "Mailer ID" %>
        <%= form.collection_select :usps_mailer_id_id,
                                 USPS::MailerId.all,
                                 :id,
                                 :name,
                                 { prompt: "Select a mailer ID...", selected: USPS::MailerId.first&.id },
                                 { class: "form-control" } %>
      </div>
    </div>
    <div class="banner banner-warning">
      please leave this at the default if you're mailing from HQ – otherwise talk to nora (it has USPS implications)
    </div>
  </fieldset>
  <fieldset>
    <legend>Additional Data</legend>
    <div class="grid">
      <div>
        <%= form.label :recipient_email, "Recipient Email", class: "form-label" %>
        <%= form.email_field :recipient_email, class: "form-control", placeholder: "recipient@example.com" %>
        <small>Optional email address for the recipient</small>
      </div>
      <div>
        <%= form.label :rubber_stamps, "Rubber Stamps" %>
        <%= form.text_area :rubber_stamps, rows: 5 %>
        <small>Extra text to print on the label!</small>
      </div>
    </div>
    <%= render 'shared/tag_picker', form: form %>
  </fieldset>
  <fieldset id="postage-options" style="display: none;">
    <legend>Postage Options</legend>
    <div class="grid">
      <div>
        <label>
          <%= form.check_box :non_machinable %>
          Non-machinable
        </label>
        <small>Check this if the letter contains rigid items or is otherwise non-machinable.</small>
      </div>
    </div>
    <div class="grid">
      <div>
        <label>
          <%= form.radio_button :postage_type, "stamps", checked: true, class: "postage-type-option" %>
          Stamps
        </label>
        <label>
          <%= form.radio_button :postage_type, "indicia", class: "postage-type-option" %>
          Indicia (Metered)
        </label>
        <small>
          <% if @letter.address&.us? %>
            Indicia costs 69¢ for a standard letter (vs 73¢ for stamps)
          <% else %>
            Indicia costs slightly more than stamps for international mail, but saves time on large batches
          <% end %>
        </small>
      </div>
    </div>
  </fieldset>
  <div class="grid">
    <div>
      <%= form.submit "do it!", class: "success" %>
      <%= link_to "cancel", letters_path, class: "btn btn-tiny danger outlined" %>
    </div>
  </div>
<% end %>
<%= javascript_tag do %>
  document.addEventListener('DOMContentLoaded', function() {
  const returnAddressSelect = document.querySelector('#letter_return_address_id');
  const postageOptions = document.querySelector('#postage-options');
  const stampsRadio = document.querySelector('input[name="letter[postage_type]"][value="stamps"]');
  const indiciaRadio = document.querySelector('input[name="letter[postage_type]"][value="indicia"]');
  // Store country data in a data attribute when rendering the select options
  const returnAddresses = <%= raw ReturnAddress.shared.or(ReturnAddress.owned_by(current_user)).map { |ra| { id: ra.id, country: ra.country } }.to_json %>;
  function updatePostageTypeOptions() {
  const selectedId = returnAddressSelect.value;
  if (!selectedId) return;
  const selectedAddress = returnAddresses.find(ra => ra.id.toString() === selectedId);
  const isUS = selectedAddress?.country === 'US';
  if (isUS) {
  postageOptions.style.display = 'block';
  stampsRadio.checked = true;
  } else {
  postageOptions.style.display = 'none';
  // Set postage type to international_origin for non-US addresses
  const internationalOriginInput = document.createElement('input');
  internationalOriginInput.type = 'hidden';
  internationalOriginInput.name = 'letter[postage_type]';
  internationalOriginInput.value = 'international_origin';
  postageOptions.appendChild(internationalOriginInput);
  }
  }
  returnAddressSelect.addEventListener('change', updatePostageTypeOptions);
  // Initial check
  updatePostageTypeOptions();
  });
<% end %>
