<script setup>
/**
 * Fulfillment-Rahmenvertrag modal — opened from the partner edit page and the
 * lead edit page (same prefill contract as the quote modal). Two steps:
 *  - edit:    customer/signer data + contract parameters + assumptions +
 *             custom special clauses (Sondervereinbarungen)
 *  - preview: server-rendered branded contract PDF + email panel + send
 * Legal wording lives in server/utils/offers/contractTexts.ts; this modal only
 * collects the parameters.
 */
import sharedLang from '~/assets/langs/shared.js'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  prefill: {
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['update:modelValue', 'sent'])

const language = useCookie('language')
const lang = computed(() => language.value || 'en-US')
const t = computed(() => sharedLang(lang.value))

const isOpen = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const step = ref('edit')
const form = ref(createContractForm(props.prefill))
const previewLoading = ref(false)
const sending = ref(false)
const sentOk = ref(false)
const errorMessage = ref('')
const attachWarning = ref('')
const pdfFilename = ref('')
const blobUrl = ref('')

const canPreview = computed(() =>
  String(form.value.customer.company).trim() !== '' && String(form.value.customer.contactName).trim() !== ''
)
const canSend = computed(() => /.+@.+\..+/.test(String(form.value.email.to).trim()))

const addClause = () => {
  form.value.contract.customClauses.push({ title: '', text: '' })
}
const removeClause = (idx) => {
  form.value.contract.customClauses.splice(idx, 1)
}

let lastEmailDefaults = { subject: '', message: '' }
const applyEmailDefaults = () => {
  const d = contractEmailDefaults(form.value.language, form.value.customer.contactName, form.value.customer.company)
  if (!form.value.email.subject || form.value.email.subject === lastEmailDefaults.subject) {
    form.value.email.subject = d.subject
  }
  if (!form.value.email.message || form.value.email.message === lastEmailDefaults.message) {
    form.value.email.message = d.message
  }
  lastEmailDefaults = d
}

watch(() => props.modelValue, async (open) => {
  if (open) {
    step.value = 'edit'
    sentOk.value = false
    errorMessage.value = ''
    attachWarning.value = ''
    form.value = createContractForm(props.prefill)
    if (props.prefill?.source === 'partner' && !props.prefill?.email && props.prefill?.recordId) {
      try {
        const res = await $fetch(`/api/partners/partners/${props.prefill.recordId}/users`, {
          headers: useRequestHeaders(['cookie'])
        })
        const users = res?.records || res || []
        const withMail = Array.isArray(users) ? users.find((u) => u?.EMail) : null
        if (withMail && !form.value.email.to) {
          form.value.email.to = withMail.EMail
          form.value.customer.email = withMail.EMail
          if (!form.value.customer.contactName) form.value.customer.contactName = withMail.Name || ''
        }
      } catch { /* prefill only */ }
    }
  } else {
    revokeBlob()
  }
})

const revokeBlob = () => {
  if (blobUrl.value) {
    URL.revokeObjectURL(blobUrl.value)
    blobUrl.value = ''
  }
}

const base64ToBlobUrl = (b64) => {
  const bin = atob(b64)
  const bytes = new Uint8Array(bin.length)
  for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i)
  return URL.createObjectURL(new Blob([bytes], { type: 'application/pdf' }))
}

const fetchPreview = async () => {
  const payload = buildContractPayload(form.value, false)
  const res = await $fetch('/api/offers/contract/preview', {
    method: 'POST',
    headers: useRequestHeaders(['cookie']),
    body: payload
  })
  if (Number(res?.status) === 200 && res?.pdfBase64) {
    pdfFilename.value = res.filename
    revokeBlob()
    blobUrl.value = base64ToBlobUrl(res.pdfBase64)
    return true
  }
  errorMessage.value = res?.message || t.value.quote_send_error || 'PDF generation failed'
  return false
}

const generatePreview = async () => {
  if (!canPreview.value || previewLoading.value) return
  previewLoading.value = true
  errorMessage.value = ''
  try {
    if (await fetchPreview()) {
      applyEmailDefaults()
      step.value = 'preview'
    }
  } catch (err) {
    errorMessage.value = err?.data?.message || err?.message || 'PDF generation failed'
  }
  previewLoading.value = false
}

// Regenerate while previewing when the contract language flips
watch(() => form.value.language, async () => {
  if (step.value === 'preview') {
    applyEmailDefaults()
    previewLoading.value = true
    try { await fetchPreview() } catch { /* keep previous preview */ }
    previewLoading.value = false
  }
})

const downloadPdf = () => {
  if (!blobUrl.value) return
  const a = document.createElement('a')
  a.href = blobUrl.value
  a.download = pdfFilename.value || 'Vertrag_LogYou.pdf'
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
}

const sendContract = async () => {
  if (!canSend.value || sending.value) return
  sending.value = true
  errorMessage.value = ''
  attachWarning.value = ''
  try {
    const payload = buildContractPayload(form.value, true)
    const res = await $fetch('/api/offers/contract/send', {
      method: 'POST',
      headers: useRequestHeaders(['cookie']),
      body: payload
    })
    if (Number(res?.status) === 200) {
      sentOk.value = true
      if (res?.warning) attachWarning.value = res.warning
      emit('sent', res)
      setTimeout(() => {
        isOpen.value = false
      }, attachWarning.value ? 4000 : 1800)
    } else {
      errorMessage.value = res?.message || t.value.quote_send_error || 'Sending failed'
    }
  } catch (err) {
    errorMessage.value = err?.data?.message || err?.message || 'Sending failed'
  }
  sending.value = false
}

const handleClose = () => {
  if (sending.value || previewLoading.value) return
  isOpen.value = false
}

onBeforeUnmount(() => revokeBlob())
</script>

<template>
  <div class="modal-overlay" v-if="isOpen">
    <div class="modal-wrapper" @click.self="handleClose">
      <div class="modalContent contract-modal">
        <div class="modalHeader contract-header">
          <div class="contract-header-left">
            <img src="/assets/logyou-logo-color.png" alt="LogYou" class="contract-logo" />
            <h3 class="modalTitle">{{ t.create_contract || 'Vertrag erstellen' }}</h3>
          </div>
          <div class="contract-header-right">
            <div class="contract-lang-toggle">
              <button type="button" :class="{ active: form.language === 'de' }" @click="form.language = 'de'">DE</button>
              <button type="button" :class="{ active: form.language === 'en' }" @click="form.language = 'en'">EN</button>
            </div>
            <div class="cursor-pointer" @click="handleClose">
              <span class="tf-icon ti ti-x ti-sm me-1"></span>
            </div>
          </div>
        </div>

        <!-- ==================== STEP: EDIT ==================== -->
        <div v-if="step === 'edit'" class="modalBody contract-body">
          <div class="contract-columns">
            <div class="contract-col">
              <!-- Kunde / Unterzeichner -->
              <div class="contract-section">
                <div class="contract-section-head">
                  <span><i class="ti ti-user"></i> {{ t.quote_customer_section || 'Kunde' }}</span>
                </div>
                <div class="contract-section-body">
                  <div class="columns is-multiline is-variable is-2">
                    <div class="column is-6">
                      <div class="field">
                        <label class="label">{{ t.quote_company || 'Firma' }} <span class="req">*</span></label>
                        <input class="input" v-model="form.customer.company" />
                      </div>
                    </div>
                    <div class="column is-6">
                      <div class="field">
                        <label class="label">{{ t.quote_contact_name || 'Ansprechpartner' }} <span class="req">*</span></label>
                        <input class="input" v-model="form.customer.contactName" />
                      </div>
                    </div>
                    <div class="column is-6">
                      <div class="field">
                        <label class="label">{{ t.contract_signer_position || 'Position (Unterzeichner)' }}</label>
                        <input class="input" v-model="form.customer.signerPosition" />
                      </div>
                    </div>
                    <div class="column is-6">
                      <div class="field">
                        <label class="label">{{ t.contract_ust_id || 'USt-IdNr.' }}</label>
                        <input class="input" v-model="form.customer.ustId" />
                      </div>
                    </div>
                    <div class="column is-6">
                      <div class="field">
                        <label class="label">{{ t.quote_recipient_email || 'E-Mail' }}</label>
                        <input class="input" type="email" v-model="form.email.to" />
                      </div>
                    </div>
                    <div class="column is-6">
                      <div class="field">
                        <label class="label">{{ t.quote_street || 'Straße' }}</label>
                        <input class="input" v-model="form.customer.street" />
                      </div>
                    </div>
                    <div class="column is-3">
                      <div class="field">
                        <label class="label">{{ t.quote_zip || 'PLZ' }}</label>
                        <input class="input" v-model="form.customer.zip" />
                      </div>
                    </div>
                    <div class="column is-5">
                      <div class="field">
                        <label class="label">{{ t.quote_city || 'Stadt' }}</label>
                        <input class="input" v-model="form.customer.city" />
                      </div>
                    </div>
                    <div class="column is-4">
                      <div class="field">
                        <label class="label">{{ t.quote_country || 'Land' }}</label>
                        <input class="input" v-model="form.customer.country" />
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              <!-- Annahmen -->
              <div class="contract-section">
                <div class="contract-section-head">
                  <span><i class="ti ti-list-check"></i> {{ t.quote_assumptions_section || 'Annahmen' }}</span>
                </div>
                <div class="contract-section-body">
                  <div class="columns is-multiline is-variable is-2">
                    <div class="column is-4">
                      <div class="field">
                        <label class="label">{{ t.quote_business_model || 'Geschäftsmodell' }}</label>
                        <div class="select is-fullwidth">
                          <select v-model="form.assumptions.businessModel">
                            <option value="B2C">B2C</option>
                            <option value="B2B">B2B</option>
                            <option value="B2C+B2B">B2C + B2B</option>
                          </select>
                        </div>
                      </div>
                    </div>
                    <div class="column is-4">
                      <div class="field">
                        <label class="label">{{ t.quote_planned_start || 'Geplanter Start' }}</label>
                        <input class="input" type="date" v-model="form.assumptions.plannedStart" />
                      </div>
                    </div>
                    <div class="column is-4">
                      <div class="field">
                        <label class="label">{{ t.quote_shop_system || 'Shopsystem' }}</label>
                        <input class="input" v-model="form.assumptions.shopSystem" placeholder="Shopify / JTL / ..." />
                      </div>
                    </div>
                    <div class="column is-3">
                      <div class="field">
                        <label class="label">{{ t.quote_orders_per_month || 'Aufträge / Monat' }}</label>
                        <input class="input" type="number" min="0" step="1" v-model.number="form.assumptions.ordersPerMonth" />
                      </div>
                    </div>
                    <div class="column is-3">
                      <div class="field">
                        <label class="label">{{ t.quote_avg_picks || 'Ø Picks / Auftrag' }}</label>
                        <input class="input" type="number" min="0" step="0.1" v-model.number="form.assumptions.avgPicksPerOrder" />
                      </div>
                    </div>
                    <div class="column is-3">
                      <div class="field">
                        <label class="label">{{ t.quote_sku_count || 'Artikel (SKUs)' }}</label>
                        <input class="input" type="number" min="0" step="1" v-model.number="form.assumptions.skuCount" />
                      </div>
                    </div>
                    <div class="column is-3">
                      <div class="field">
                        <label class="label">{{ t.quote_volume_m3 || 'Volumen m³' }}</label>
                        <input class="input" type="number" min="0" step="0.5" v-model.number="form.assumptions.storage.volumeM3" />
                      </div>
                    </div>
                    <div class="column is-4">
                      <div class="field">
                        <label class="label">{{ t.quote_shelf_small || 'Fachboden M' }} ({{ t.quantity || 'Anzahl' }})</label>
                        <input class="input" type="number" min="0" step="1" v-model.number="form.assumptions.storage.shelfSmallQty" />
                      </div>
                    </div>
                    <div class="column is-4">
                      <div class="field">
                        <label class="label">{{ t.quote_shelf_large || 'Fachboden L' }} ({{ t.quantity || 'Anzahl' }})</label>
                        <input class="input" type="number" min="0" step="1" v-model.number="form.assumptions.storage.shelfLargeQty" />
                      </div>
                    </div>
                    <div class="column is-4">
                      <div class="field">
                        <label class="label">{{ t.quote_pallet_space || 'Paletten' }} ({{ t.quantity || 'Anzahl' }})</label>
                        <input class="input" type="number" min="0" step="1" v-model.number="form.assumptions.storage.palletQty" />
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <div class="contract-col">
              <!-- Vertragsparameter -->
              <div class="contract-section">
                <div class="contract-section-head">
                  <span><i class="ti ti-adjustments"></i> {{ t.contract_params_section || 'Vertragsparameter' }}</span>
                </div>
                <div class="contract-section-body">
                  <div class="columns is-multiline is-variable is-2">
                    <div class="column is-6">
                      <div class="field">
                        <label class="label">{{ t.contract_offer_date || 'Angebot vom (Anlage 1)' }}</label>
                        <input class="input" type="date" v-model="form.contract.offerDate" />
                      </div>
                    </div>
                    <div class="column is-6">
                      <div class="field">
                        <label class="label">{{ t.contract_cutoff_time || 'Cut-off-Zeit' }}</label>
                        <input class="input" v-model="form.contract.cutoffTime" placeholder="14:00" />
                      </div>
                    </div>
                    <div class="column is-4">
                      <div class="field">
                        <label class="label">{{ t.contract_notice_months || 'Kündigungsfrist (Monate)' }}</label>
                        <input class="input" type="number" min="1" step="1" v-model.number="form.contract.noticeMonths" />
                      </div>
                    </div>
                    <div class="column is-4">
                      <div class="field">
                        <label class="label">{{ t.contract_price_notice_months || 'Preisänderung Vorlauf (Mon.)' }}</label>
                        <input class="input" type="number" min="1" step="1" v-model.number="form.contract.priceNoticeMonths" />
                      </div>
                    </div>
                    <div class="column is-4">
                      <div class="field">
                        <label class="label">{{ t.contract_objection_weeks || 'Widerspruchsfrist (Wochen)' }}</label>
                        <input class="input" type="number" min="1" step="1" v-model.number="form.contract.objectionWeeks" />
                      </div>
                    </div>
                    <div class="column is-4">
                      <div class="field">
                        <label class="label">{{ t.contract_cure_days || 'Nachfrist Zahlungsverzug (Werktage)' }}</label>
                        <input class="input" type="number" min="0" step="1" v-model.number="form.contract.curePeriodDays" />
                      </div>
                    </div>
                    <div class="column is-4">
                      <div class="field">
                        <label class="label">{{ t.contract_shrinkage_pct || 'Inventur-Toleranz (% p.a.)' }}</label>
                        <input class="input" type="number" min="0" step="0.1" v-model.number="form.contract.shrinkagePct" />
                      </div>
                    </div>
                    <div class="column is-4">
                      <div class="field">
                        <label class="label">{{ t.contract_payment_method || 'Zahlungsart' }}</label>
                        <div class="select is-fullwidth">
                          <select v-model="form.contract.paymentMethod">
                            <option value="sepa">{{ t.contract_payment_sepa || 'SEPA-Lastschrift' }}</option>
                            <option value="transfer">{{ t.contract_payment_transfer || 'Überweisung' }}</option>
                          </select>
                        </div>
                      </div>
                    </div>
                    <div class="column is-8">
                      <div class="field">
                        <label class="label">{{ t.contract_marketing_variant || 'Marketingrechte' }}</label>
                        <div class="select is-fullwidth">
                          <select v-model="form.contract.marketingVariant">
                            <option value="consent">{{ t.contract_marketing_consent || 'Generelle Zustimmung (mit Vorab-Info)' }}</option>
                            <option value="approval">{{ t.contract_marketing_approval || 'Freigabe je Einzelfall' }}</option>
                          </select>
                        </div>
                      </div>
                    </div>
                    <div class="column is-4">
                      <label class="checkbox contract-checkbox">
                        <input type="checkbox" v-model="form.contract.includeExpress" />
                        {{ t.contract_include_express || 'Express-Versand-Klausel' }}
                      </label>
                    </div>
                  </div>
                </div>
              </div>

              <!-- Sondervereinbarungen -->
              <div class="contract-section">
                <div class="contract-section-head">
                  <span><i class="ti ti-writing-sign"></i> {{ t.contract_special_clauses || 'Sondervereinbarungen' }}</span>
                  <button type="button" class="button is-small contract-add-btn" @click="addClause">
                    <i class="ti ti-plus"></i>&nbsp;{{ t.contract_add_clause || 'Klausel hinzufügen' }}
                  </button>
                </div>
                <div class="contract-section-body">
                  <p v-if="!form.contract.customClauses.length" class="contract-hint">
                    {{ t.contract_no_clauses_hint || 'Optional: individuelle Vereinbarungen (z. B. Container-Entladung, DHL-Rahmenvertrag des Kunden, Warenübernahme).' }}
                  </p>
                  <div v-for="(clause, idx) in form.contract.customClauses" :key="idx" class="contract-clause">
                    <div class="contract-clause-head">
                      <input class="input is-small" v-model="clause.title" :placeholder="(t.contract_clause_title || 'Titel') + ' ' + (idx + 1)" />
                      <button type="button" class="button is-small is-danger is-light" @click="removeClause(idx)">
                        <i class="ti ti-trash"></i>
                      </button>
                    </div>
                    <textarea class="textarea is-small" rows="3" v-model="clause.text" :placeholder="t.contract_clause_text || 'Klauseltext …'"></textarea>
                  </div>
                  <p class="contract-hint contract-legal-hint">
                    <i class="ti ti-scale"></i>
                    {{ t.contract_legal_hint || 'Vorlage — finale rechtliche Prüfung durch einen Rechtsanwalt wird empfohlen.' }}
                  </p>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- ==================== STEP: PREVIEW ==================== -->
        <div v-else class="modalBody contract-body contract-preview-body">
          <div class="contract-preview-columns">
            <div class="contract-preview-frame">
              <div v-if="previewLoading" class="contract-preview-loading">
                <i class="ti ti-loader-2 contract-spin"></i>
              </div>
              <iframe v-else-if="blobUrl" :src="blobUrl" title="PDF"></iframe>
            </div>
            <div class="contract-email-panel">
              <div class="field">
                <label class="label">{{ t.quote_recipient_email || 'Empfänger' }} <span class="req">*</span></label>
                <input class="input" type="email" v-model="form.email.to" />
                <p v-if="!canSend" class="help is-danger">{{ t.quote_validation_email || 'Empfänger-E-Mail erforderlich' }}</p>
              </div>
              <div class="field">
                <label class="label">{{ t.quote_cc_label || 'CC' }}</label>
                <input class="input" v-model="form.email.cc" />
              </div>
              <div class="field">
                <label class="label">{{ t.quote_email_subject_label || 'Betreff' }}</label>
                <input class="input" v-model="form.email.subject" />
              </div>
              <div class="field">
                <label class="label">{{ t.quote_email_message_label || 'Nachricht' }}</label>
                <textarea class="textarea" rows="9" v-model="form.email.message"></textarea>
              </div>
              <div v-if="sentOk" class="notification is-success is-light contract-sent-note">
                <i class="ti ti-circle-check"></i> {{ t.contract_send_success || 'Vertrag versendet & angehängt' }}
                <div v-if="attachWarning" class="contract-attach-warning">{{ attachWarning }}</div>
              </div>
            </div>
          </div>
        </div>

        <div class="modalFooter contract-footer">
          <div v-if="errorMessage" class="contract-error">
            <i class="ti ti-alert-circle"></i> {{ errorMessage }}
          </div>
          <div class="buttons">
            <template v-if="step === 'edit'">
              <button type="button" class="button" @click="handleClose">{{ t.cancel || 'Abbrechen' }}</button>
              <button
                type="button"
                class="button is-primary"
                :disabled="!canPreview || previewLoading"
                :title="!canPreview ? (t.quote_required_fields_hint || 'Firma und Ansprechpartner sind Pflichtfelder') : ''"
                @click="generatePreview"
              >
                <i class="ti" :class="previewLoading ? 'ti-loader-2 contract-spin' : 'ti-eye'"></i>&nbsp;
                {{ t.quote_preview_button || 'Vorschau ansehen' }}
              </button>
            </template>
            <template v-else>
              <button type="button" class="button" :disabled="sending" @click="step = 'edit'">
                <i class="ti ti-arrow-left"></i>&nbsp;{{ t.quote_back_edit || 'Zurück bearbeiten' }}
              </button>
              <button type="button" class="button" :disabled="!blobUrl" @click="downloadPdf">
                <i class="ti ti-download"></i>&nbsp;{{ t.quote_download_pdf || 'Nur PDF herunterladen' }}
              </button>
              <button
                type="button"
                class="button is-primary"
                :disabled="!canSend || sending || sentOk"
                @click="sendContract"
              >
                <i class="ti" :class="sending ? 'ti-loader-2 contract-spin' : 'ti-send'"></i>&nbsp;
                {{ t.quote_send_button || 'Senden & anhängen' }}
              </button>
            </template>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100vw;
  height: 100vh;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 9999;
  display: flex;
  align-items: center;
  justify-content: center;
}

.modal-wrapper {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.contract-modal {
  max-width: 1150px;
  width: 100%;
  max-height: 92vh;
  display: flex;
  flex-direction: column;
  background: var(--theme-bg-primary, #fff);
  border-radius: 10px;
  overflow: hidden;
}

.contract-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 14px 20px;
  border-bottom: 3px solid #f15924;
  background: var(--theme-bg-primary, #fff);
}

.contract-header-left {
  display: flex;
  align-items: center;
  gap: 14px;
}

.contract-logo {
  height: 26px;
  width: auto;
}

.contract-header-right {
  display: flex;
  align-items: center;
  gap: 16px;
}

.contract-lang-toggle {
  display: flex;
  border: 1px solid #d5dbe1;
  border-radius: 6px;
  overflow: hidden;
}

.contract-lang-toggle button {
  border: none;
  background: transparent;
  padding: 4px 12px;
  cursor: pointer;
  font-size: 0.8rem;
  font-weight: 600;
  color: var(--theme-text-primary, #33414e);
}

.contract-lang-toggle button.active {
  background: #1c324b;
  color: #fff;
}

.contract-body {
  flex: 1;
  overflow: hidden;
  padding: 0;
}

.contract-columns {
  display: flex;
  gap: 0;
  height: 100%;
  max-height: calc(92vh - 128px);
}

.contract-col {
  flex: 1 1 50%;
  overflow-y: auto;
  padding: 16px 20px;
}

.contract-col + .contract-col {
  padding-left: 0;
}

.contract-section {
  border: 1px solid var(--theme-border, #e3e7ec);
  border-radius: 8px;
  margin-bottom: 12px;
  overflow: hidden;
}

.contract-section-head {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 14px;
  font-weight: 600;
  color: #1c324b;
  background: var(--theme-bg-secondary, #f6f8fa);
}

.contract-section-head span i {
  color: #f15924;
  margin-right: 6px;
}

.contract-section-body {
  padding: 14px;
}

.req {
  color: #f15924;
}

.contract-checkbox {
  display: block;
  font-size: 0.85rem;
  margin-top: 30px;
}

.contract-add-btn {
  background: #f15924;
  color: #fff;
  border: none;
}

.contract-add-btn:hover {
  background: #d94b1a;
  color: #fff;
}

.contract-hint {
  font-size: 0.78rem;
  color: var(--theme-text-secondary, #5a6b7c);
}

.contract-legal-hint {
  margin-top: 10px;
}

.contract-legal-hint i {
  color: #f15924;
}

.contract-clause {
  border: 1px dashed var(--theme-border, #e3e7ec);
  border-radius: 6px;
  padding: 10px;
  margin-bottom: 10px;
}

.contract-clause-head {
  display: flex;
  gap: 8px;
  margin-bottom: 8px;
}

.contract-clause-head .input {
  flex: 1;
}

/* Preview step */
.contract-preview-body {
  padding: 0;
}

.contract-preview-columns {
  display: flex;
  height: 100%;
  max-height: calc(92vh - 128px);
}

.contract-preview-frame {
  flex: 1 1 60%;
  background: #4a5568;
  position: relative;
  min-height: 400px;
}

.contract-preview-frame iframe {
  width: 100%;
  height: 100%;
  border: none;
  display: block;
}

.contract-preview-loading {
  position: absolute;
  inset: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  font-size: 2rem;
}

.contract-email-panel {
  flex: 1 1 40%;
  max-width: 420px;
  overflow-y: auto;
  padding: 16px 20px;
}

.contract-sent-note {
  margin-top: 10px;
  font-size: 0.85rem;
}

.contract-attach-warning {
  font-size: 0.75rem;
  margin-top: 4px;
  color: #946c00;
}

/* Footer */
.contract-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  padding: 12px 20px;
  border-top: 1px solid var(--theme-border, #e3e7ec);
}

.contract-footer .buttons {
  margin-left: auto;
  margin-bottom: 0;
}

.contract-error {
  color: #cc0f35;
  font-size: 0.82rem;
}

.contract-spin {
  display: inline-block;
  animation: contract-rotate 1s linear infinite;
}

@keyframes contract-rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

@media (max-width: 900px) {
  /* Fullscreen modal; the body scrolls as ONE column while header/footer stay fixed. */
  .modal-wrapper {
    padding: 0;
    align-items: stretch;
  }

  .contract-modal {
    height: 100vh;
    height: 100dvh;
    max-height: 100vh;
    max-height: 100dvh;
    border-radius: 0;
  }

  .contract-body {
    overflow-y: auto;
    -webkit-overflow-scrolling: touch;
  }

  .contract-columns,
  .contract-preview-columns {
    flex-direction: column;
    height: auto;
    max-height: none;
  }

  .contract-col,
  .contract-email-panel {
    flex: none;
    max-width: none;
    overflow-y: visible;
  }

  .contract-col + .contract-col {
    padding-left: 20px;
  }

  .contract-preview-frame {
    flex: none;
    min-height: 65vh;
  }

  .contract-preview-frame iframe {
    height: 65vh;
  }

  .contract-footer {
    flex-wrap: wrap;
  }
}
</style>
