<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { api } from '@/api'
import { useAuthStore } from '@/stores/auth'

const authStore = useAuthStore()

const loading = ref(true)
const asContractor = ref<any[]>([])
const asSubcontractor = ref<any[]>([])
const stats = ref<any>({})

// Tabs
const activeTab = ref<'overview' | 'orders' | 'timesheets' | 'invoices'>('overview')

// Modals
const showInviteModal = ref(false)
const showDetailModal = ref(false)
const showRateModal = ref(false)
const showShareOrderModal = ref(false)

// Selected
const selectedPartnership = ref<any>(null)
const partnershipDetail = ref<any>(null)

// Search
const searchQuery = ref('')
const searchResults = ref<any[]>([])
const searching = ref(false)

// Invite form
const inviteForm = ref({
  subcontractor_slug: '',
  notes: '',
  contract_start: '',
  contract_end: ''
})
const inviting = ref(false)

// Rate form
const rateForm = ref({
  name: '',
  description: '',
  rate_type: 'hourly',
  amount: 0,
  is_default: false
})

// Shared orders
const sharedOrders = ref<any>({ asContractor: [], asSubcontractor: [] })
const partnershipTimesheets = ref<any[]>([])
const invoices = ref<any[]>([])

// Orders to share
const availableOrders = ref<any[]>([])
const selectedOrder = ref<any>(null)
const shareForm = ref({
  partnership_id: '',
  order_id: '',
  rate_id: '',
  required_staff: 1,
  notes: ''
})

onMounted(async () => {
  await loadPartnerships()
})

async function loadPartnerships() {
  loading.value = true
  try {
    const res = await api.get<any>('/partnerships')
    asContractor.value = res.data.asContractor || []
    asSubcontractor.value = res.data.asSubcontractor || []
    stats.value = res.data.stats || {}
  } catch (e) {
    console.error('Load partnerships failed:', e)
  }
  loading.value = false
}

async function searchOrgs() {
  if (searchQuery.value.length < 2) {
    searchResults.value = []
    return
  }
  searching.value = true
  try {
    const res = await api.get<any[]>(`/partnerships/search/orgs?q=${encodeURIComponent(searchQuery.value)}`)
    searchResults.value = res.data
  } catch (e) {
    console.error('Search failed:', e)
  }
  searching.value = false
}

function selectOrgToInvite(org: any) {
  inviteForm.value.subcontractor_slug = org.slug
  searchQuery.value = org.name
  searchResults.value = []
}

async function sendInvite() {
  if (!inviteForm.value.subcontractor_slug) return
  inviting.value = true
  try {
    await api.post('/partnerships', {
      subcontractor_slug: inviteForm.value.subcontractor_slug,
      notes: inviteForm.value.notes || undefined,
      contract_start: inviteForm.value.contract_start || undefined,
      contract_end: inviteForm.value.contract_end || undefined
    })
    showInviteModal.value = false
    resetInviteForm()
    await loadPartnerships()
  } catch (e: any) {
    alert('Fehler: ' + (e.response?.data?.error || e.message))
  }
  inviting.value = false
}

function resetInviteForm() {
  inviteForm.value = { subcontractor_slug: '', notes: '', contract_start: '', contract_end: '' }
  searchQuery.value = ''
  searchResults.value = []
}

async function acceptInvite(partnership: any) {
  try {
    await api.post(`/partnerships/${partnership.id}/accept`)
    await loadPartnerships()
  } catch (e: any) {
    alert('Fehler: ' + (e.response?.data?.error || e.message))
  }
}

async function declineInvite(partnership: any) {
  if (!confirm('Einladung wirklich ablehnen?')) return
  try {
    await api.post(`/partnerships/${partnership.id}/decline`)
    await loadPartnerships()
  } catch (e: any) {
    alert('Fehler: ' + (e.response?.data?.error || e.message))
  }
}

async function changeStatus(partnership: any, status: string) {
  if (!confirm(`Status auf "${status}" ändern?`)) return
  try {
    await api.put(`/partnerships/${partnership.id}/status`, { status })
    await loadPartnerships()
    if (partnershipDetail.value?.id === partnership.id) {
      partnershipDetail.value.status = status
    }
  } catch (e: any) {
    alert('Fehler: ' + (e.response?.data?.error || e.message))
  }
}

async function viewPartnership(partnership: any) {
  selectedPartnership.value = partnership
  try {
    const res = await api.get<any>(`/partnerships/${partnership.id}`)
    partnershipDetail.value = res.data
    showDetailModal.value = true
  } catch (e: any) {
    alert('Fehler: ' + (e.response?.data?.error || e.message))
  }
}

// ============================================
// RATES
// ============================================

function openRateModal() {
  rateForm.value = { name: '', description: '', rate_type: 'hourly', amount: 0, is_default: false }
  showRateModal.value = true
}

async function saveRate() {
  if (!rateForm.value.name || !rateForm.value.amount) {
    alert('Name und Betrag erforderlich')
    return
  }
  try {
    await api.post(`/partnerships/${partnershipDetail.value.id}/rates`, {
      ...rateForm.value,
      amount_cents: Math.round(rateForm.value.amount * 100)
    })
    // Reload detail
    const res = await api.get<any>(`/partnerships/${partnershipDetail.value.id}`)
    partnershipDetail.value = res.data
    showRateModal.value = false
  } catch (e: any) {
    alert('Fehler: ' + (e.response?.data?.error || e.message))
  }
}

async function deleteRate(rate: any) {
  if (!confirm(`Satz "${rate.name}" löschen?`)) return
  try {
    await api.delete(`/partnerships/${partnershipDetail.value.id}/rates/${rate.id}`)
    const res = await api.get<any>(`/partnerships/${partnershipDetail.value.id}`)
    partnershipDetail.value = res.data
  } catch (e: any) {
    alert('Fehler: ' + (e.response?.data?.error || e.message))
  }
}

// ============================================
// SHARED ORDERS
// ============================================

async function loadSharedOrders() {
  activeTab.value = 'orders'
  try {
    const res = await api.get<any>('/partnerships/orders/list')
    sharedOrders.value = res.data
  } catch (e) {
    console.error('Load shared orders failed:', e)
  }
}

async function openShareOrderModal(partnership: any) {
  selectedPartnership.value = partnership
  shareForm.value = {
    partnership_id: partnership.id,
    order_id: '',
    rate_id: '',
    required_staff: 1,
    notes: ''
  }
  try {
    // Load our orders
    const ordersRes = await api.get<any>('/orders')
    availableOrders.value = ordersRes.data.orders || ordersRes.data || []
    // Load rates for this partnership
    const ratesRes = await api.get<any>(`/partnerships/${partnership.id}/rates`)
    partnershipDetail.value = { ...partnership, rates: ratesRes.data }
    showShareOrderModal.value = true
  } catch (e) {
    console.error('Load orders failed:', e)
  }
}

async function shareOrder() {
  if (!shareForm.value.order_id) {
    alert('Bitte Auftrag auswählen')
    return
  }
  try {
    await api.post('/partnerships/orders', {
      partnership_id: shareForm.value.partnership_id,
      order_id: shareForm.value.order_id,
      rate_id: shareForm.value.rate_id || undefined,
      required_staff: shareForm.value.required_staff,
      notes: shareForm.value.notes || undefined
    })
    showShareOrderModal.value = false
    await loadSharedOrders()
  } catch (e: any) {
    alert('Fehler: ' + (e.response?.data?.error || e.message))
  }
}

async function respondToOrder(order: any, accept: boolean) {
  try {
    await api.post(`/partnerships/orders/${order.id}/respond`, { 
      accept,
      notes: ''
    })
    await loadSharedOrders()
  } catch (e: any) {
    alert('Fehler: ' + (e.response?.data?.error || e.message))
  }
}

async function completeOrder(order: any) {
  if (!confirm('Auftrag abschließen?')) return
  try {
    await api.post(`/partnerships/orders/${order.id}/complete`)
    await loadSharedOrders()
  } catch (e: any) {
    alert('Fehler: ' + (e.response?.data?.error || e.message))
  }
}

// ============================================
// TIMESHEETS
// ============================================

async function loadPartnershipTimesheets() {
  activeTab.value = 'timesheets'
  try {
    const res = await api.get<any[]>('/partnerships/timesheets/list')
    partnershipTimesheets.value = res.data
  } catch (e) {
    console.error('Load timesheets failed:', e)
  }
}

async function approveTimesheet(ts: any) {
  try {
    await api.post(`/partnerships/timesheets/${ts.id}/approve`)
    await loadPartnershipTimesheets()
  } catch (e: any) {
    alert('Fehler: ' + (e.response?.data?.error || e.message))
  }
}

async function disputeTimesheet(ts: any) {
  const reason = prompt('Grund für Beanstandung:')
  if (!reason) return
  try {
    await api.post(`/partnerships/timesheets/${ts.id}/dispute`, { reason })
    await loadPartnershipTimesheets()
  } catch (e: any) {
    alert('Fehler: ' + (e.response?.data?.error || e.message))
  }
}

// ============================================
// INVOICES
// ============================================

async function loadInvoices() {
  activeTab.value = 'invoices'
  try {
    const res = await api.get<any[]>('/partnerships/invoices/list')
    invoices.value = res.data
  } catch (e) {
    console.error('Load invoices failed:', e)
  }
}

async function markAsPaid(invoice: any) {
  if (!confirm('Rechnung als bezahlt markieren?')) return
  try {
    await api.put(`/partnerships/invoices/${invoice.id}/pay`)
    await loadInvoices()
  } catch (e: any) {
    alert('Fehler: ' + (e.response?.data?.error || e.message))
  }
}

// Helpers
function formatCents(cents: number): string {
  return (cents / 100).toFixed(2).replace('.', ',') + ' €'
}

function formatDate(date: string): string {
  if (!date) return '-'
  return new Date(date).toLocaleDateString('de-DE')
}

function statusBadge(status: string): { text: string, class: string } {
  const map: Record<string, { text: string, class: string }> = {
    pending: { text: 'Ausstehend', class: 'bg-yellow-100 text-yellow-800' },
    active: { text: 'Aktiv', class: 'bg-green-100 text-green-800' },
    paused: { text: 'Pausiert', class: 'bg-gray-100 text-gray-800' },
    terminated: { text: 'Beendet', class: 'bg-red-100 text-red-800' },
    requested: { text: 'Angefragt', class: 'bg-blue-100 text-blue-800' },
    accepted: { text: 'Angenommen', class: 'bg-green-100 text-green-800' },
    declined: { text: 'Abgelehnt', class: 'bg-red-100 text-red-800' },
    completed: { text: 'Abgeschlossen', class: 'bg-gray-100 text-gray-800' },
    approved: { text: 'Freigegeben', class: 'bg-green-100 text-green-800' },
    disputed: { text: 'Beanstandet', class: 'bg-red-100 text-red-800' },
    draft: { text: 'Entwurf', class: 'bg-gray-100 text-gray-800' },
    sent: { text: 'Gesendet', class: 'bg-blue-100 text-blue-800' },
    paid: { text: 'Bezahlt', class: 'bg-green-100 text-green-800' }
  }
  return map[status] || { text: status, class: 'bg-gray-100 text-gray-800' }
}
</script>

<template>
  <div class="p-6">
    <div class="flex justify-between items-center mb-6">
      <div>
        <h1 class="text-2xl font-bold text-gray-900">🤝 Subunternehmer</h1>
        <p class="text-gray-500">Partnerschaften mit anderen Sicherheitsunternehmen</p>
      </div>
      <button 
        @click="showInviteModal = true"
        class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
      >
        + Partner einladen
      </button>
    </div>

    <!-- Tabs -->
    <div class="flex space-x-1 border-b mb-6">
      <button 
        @click="activeTab = 'overview'"
        :class="[
          'px-4 py-2 font-medium border-b-2 -mb-px',
          activeTab === 'overview' 
            ? 'border-blue-600 text-blue-600' 
            : 'border-transparent text-gray-500 hover:text-gray-700'
        ]"
      >
        Übersicht
      </button>
      <button 
        @click="loadSharedOrders()"
        :class="[
          'px-4 py-2 font-medium border-b-2 -mb-px',
          activeTab === 'orders' 
            ? 'border-blue-600 text-blue-600' 
            : 'border-transparent text-gray-500 hover:text-gray-700'
        ]"
      >
        Geteilte Aufträge
      </button>
      <button 
        @click="loadPartnershipTimesheets()"
        :class="[
          'px-4 py-2 font-medium border-b-2 -mb-px',
          activeTab === 'timesheets' 
            ? 'border-blue-600 text-blue-600' 
            : 'border-transparent text-gray-500 hover:text-gray-700'
        ]"
      >
        Stundenzettel
      </button>
      <button 
        @click="loadInvoices()"
        :class="[
          'px-4 py-2 font-medium border-b-2 -mb-px',
          activeTab === 'invoices' 
            ? 'border-blue-600 text-blue-600' 
            : 'border-transparent text-gray-500 hover:text-gray-700'
        ]"
      >
        Rechnungen
      </button>
    </div>

    <!-- Loading -->
    <div v-if="loading" class="text-center py-12">
      <div class="animate-spin w-8 h-8 border-4 border-blue-600 border-t-transparent rounded-full mx-auto"></div>
    </div>

    <!-- ============================================ -->
    <!-- OVERVIEW TAB -->
    <!-- ============================================ -->
    <div v-else-if="activeTab === 'overview'">
      <!-- Stats -->
      <div class="grid grid-cols-4 gap-4 mb-6">
        <div class="bg-white rounded-lg shadow p-4">
          <div class="text-2xl font-bold text-gray-900">{{ stats.totalPartnerships || 0 }}</div>
          <div class="text-sm text-gray-500">Partnerschaften</div>
        </div>
        <div class="bg-white rounded-lg shadow p-4">
          <div class="text-2xl font-bold text-green-600">{{ stats.activeAsContractor || 0 }}</div>
          <div class="text-sm text-gray-500">Als Auftraggeber</div>
        </div>
        <div class="bg-white rounded-lg shadow p-4">
          <div class="text-2xl font-bold text-blue-600">{{ stats.activeAsSubcontractor || 0 }}</div>
          <div class="text-sm text-gray-500">Als Subunternehmer</div>
        </div>
        <div class="bg-white rounded-lg shadow p-4">
          <div class="text-2xl font-bold text-yellow-600">{{ stats.pendingInvitations || 0 }}</div>
          <div class="text-sm text-gray-500">Offene Einladungen</div>
        </div>
      </div>

      <!-- Pending Invitations -->
      <div v-if="asSubcontractor.filter(p => p.status === 'pending').length > 0" class="mb-6">
        <h2 class="text-lg font-semibold mb-3">📩 Offene Einladungen</h2>
        <div class="space-y-2">
          <div 
            v-for="p in asSubcontractor.filter(p => p.status === 'pending')" 
            :key="p.id"
            class="bg-yellow-50 border border-yellow-200 rounded-lg p-4 flex justify-between items-center"
          >
            <div>
              <span class="font-medium">{{ p.partner_name }}</span> möchte mit Ihnen zusammenarbeiten
            </div>
            <div class="flex space-x-2">
              <button 
                @click="acceptInvite(p)"
                class="px-3 py-1 bg-green-600 text-white rounded hover:bg-green-700"
              >
                Annehmen
              </button>
              <button 
                @click="declineInvite(p)"
                class="px-3 py-1 bg-red-100 text-red-700 rounded hover:bg-red-200"
              >
                Ablehnen
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- As Contractor -->
      <div class="mb-6">
        <h2 class="text-lg font-semibold mb-3">🏢 Wir als Auftraggeber</h2>
        <div v-if="asContractor.length === 0" class="bg-gray-50 rounded-lg p-8 text-center text-gray-500">
          Noch keine Subunternehmer eingeladen
        </div>
        <div v-else class="bg-white rounded-lg shadow overflow-hidden">
          <table class="min-w-full divide-y divide-gray-200">
            <thead class="bg-gray-50">
              <tr>
                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Subunternehmer</th>
                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Status</th>
                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Aufträge</th>
                <th class="px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase">Aktionen</th>
              </tr>
            </thead>
            <tbody class="divide-y divide-gray-200">
              <tr v-for="p in asContractor" :key="p.id" class="hover:bg-gray-50">
                <td class="px-4 py-3">
                  <span class="font-medium">{{ p.partner_name }}</span>
                  <span class="text-gray-500 text-sm ml-2">@{{ p.partner_slug }}</span>
                </td>
                <td class="px-4 py-3">
                  <span :class="['px-2 py-1 text-xs rounded-full', statusBadge(p.status).class]">
                    {{ statusBadge(p.status).text }}
                  </span>
                </td>
                <td class="px-4 py-3 text-sm">
                  {{ p.shared_orders_count || 0 }} geteilt
                  <span v-if="p.pending_orders > 0" class="text-yellow-600 ml-1">
                    ({{ p.pending_orders }} offen)
                  </span>
                </td>
                <td class="px-4 py-3 text-right space-x-2">
                  <button 
                    @click="viewPartnership(p)"
                    class="text-blue-600 hover:text-blue-800"
                  >
                    Details
                  </button>
                  <button 
                    v-if="p.status === 'active'"
                    @click="openShareOrderModal(p)"
                    class="text-green-600 hover:text-green-800"
                  >
                    Auftrag teilen
                  </button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>

      <!-- As Subcontractor -->
      <div>
        <h2 class="text-lg font-semibold mb-3">👷 Wir als Subunternehmer</h2>
        <div v-if="asSubcontractor.filter(p => p.status !== 'pending').length === 0" class="bg-gray-50 rounded-lg p-8 text-center text-gray-500">
          Keine aktiven Partnerschaften als Subunternehmer
        </div>
        <div v-else class="bg-white rounded-lg shadow overflow-hidden">
          <table class="min-w-full divide-y divide-gray-200">
            <thead class="bg-gray-50">
              <tr>
                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Auftraggeber</th>
                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Status</th>
                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Aufträge</th>
                <th class="px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase">Aktionen</th>
              </tr>
            </thead>
            <tbody class="divide-y divide-gray-200">
              <tr v-for="p in asSubcontractor.filter(p => p.status !== 'pending')" :key="p.id" class="hover:bg-gray-50">
                <td class="px-4 py-3">
                  <span class="font-medium">{{ p.partner_name }}</span>
                </td>
                <td class="px-4 py-3">
                  <span :class="['px-2 py-1 text-xs rounded-full', statusBadge(p.status).class]">
                    {{ statusBadge(p.status).text }}
                  </span>
                </td>
                <td class="px-4 py-3 text-sm">
                  {{ p.shared_orders_count || 0 }} erhalten
                  <span v-if="p.pending_orders > 0" class="text-yellow-600 ml-1">
                    ({{ p.pending_orders }} offen)
                  </span>
                </td>
                <td class="px-4 py-3 text-right">
                  <button 
                    @click="viewPartnership(p)"
                    class="text-blue-600 hover:text-blue-800"
                  >
                    Details
                  </button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>

    <!-- ============================================ -->
    <!-- ORDERS TAB -->
    <!-- ============================================ -->
    <div v-else-if="activeTab === 'orders'">
      <div class="grid grid-cols-2 gap-6">
        <!-- Orders we shared -->
        <div>
          <h2 class="text-lg font-semibold mb-3">📤 Von uns geteilt</h2>
          <div v-if="sharedOrders.asContractor.length === 0" class="bg-gray-50 rounded-lg p-6 text-center text-gray-500">
            Keine geteilten Aufträge
          </div>
          <div v-else class="space-y-2">
            <div 
              v-for="order in sharedOrders.asContractor" 
              :key="order.id"
              class="bg-white rounded-lg shadow p-4"
            >
              <div class="flex justify-between items-start">
                <div>
                  <div class="font-medium">{{ order.order_title }}</div>
                  <div class="text-sm text-gray-500">{{ order.location }}</div>
                  <div class="text-sm text-gray-500">
                    {{ formatDate(order.start_date) }} - {{ formatDate(order.end_date) }}
                  </div>
                  <div class="text-sm mt-1">
                    → <span class="font-medium">{{ order.subcontractor_name }}</span>
                  </div>
                </div>
                <div class="text-right">
                  <span :class="['px-2 py-1 text-xs rounded-full', statusBadge(order.status).class]">
                    {{ statusBadge(order.status).text }}
                  </span>
                  <div v-if="order.rate_name" class="text-sm text-gray-500 mt-1">
                    {{ order.rate_name }}: {{ formatCents(order.rate_amount) }}/h
                  </div>
                </div>
              </div>
              <div v-if="order.status === 'accepted'" class="mt-2 pt-2 border-t">
                <button 
                  @click="completeOrder(order)"
                  class="text-sm text-green-600 hover:text-green-800"
                >
                  ✓ Abschließen
                </button>
              </div>
            </div>
          </div>
        </div>

        <!-- Orders we received -->
        <div>
          <h2 class="text-lg font-semibold mb-3">📥 An uns übertragen</h2>
          <div v-if="sharedOrders.asSubcontractor.length === 0" class="bg-gray-50 rounded-lg p-6 text-center text-gray-500">
            Keine erhaltenen Aufträge
          </div>
          <div v-else class="space-y-2">
            <div 
              v-for="order in sharedOrders.asSubcontractor" 
              :key="order.id"
              class="bg-white rounded-lg shadow p-4"
            >
              <div class="flex justify-between items-start">
                <div>
                  <div class="font-medium">{{ order.order_title }}</div>
                  <div class="text-sm text-gray-500">{{ order.location }}</div>
                  <div class="text-sm text-gray-500">
                    {{ formatDate(order.start_date) }} - {{ formatDate(order.end_date) }}
                  </div>
                  <div class="text-sm mt-1">
                    ← <span class="font-medium">{{ order.contractor_name }}</span>
                  </div>
                </div>
                <div class="text-right">
                  <span :class="['px-2 py-1 text-xs rounded-full', statusBadge(order.status).class]">
                    {{ statusBadge(order.status).text }}
                  </span>
                </div>
              </div>
              <div v-if="order.status === 'requested'" class="mt-2 pt-2 border-t flex space-x-2">
                <button 
                  @click="respondToOrder(order, true)"
                  class="text-sm px-3 py-1 bg-green-600 text-white rounded hover:bg-green-700"
                >
                  Annehmen
                </button>
                <button 
                  @click="respondToOrder(order, false)"
                  class="text-sm px-3 py-1 bg-red-100 text-red-700 rounded hover:bg-red-200"
                >
                  Ablehnen
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- ============================================ -->
    <!-- TIMESHEETS TAB -->
    <!-- ============================================ -->
    <div v-else-if="activeTab === 'timesheets'">
      <div v-if="partnershipTimesheets.length === 0" class="bg-gray-50 rounded-lg p-12 text-center text-gray-500">
        Keine Partnership-Stundenzettel vorhanden
      </div>
      <div v-else class="bg-white rounded-lg shadow overflow-hidden">
        <table class="min-w-full divide-y divide-gray-200">
          <thead class="bg-gray-50">
            <tr>
              <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Datum</th>
              <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Mitarbeiter</th>
              <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Auftrag</th>
              <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Stunden</th>
              <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Betrag</th>
              <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Status</th>
              <th class="px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase">Aktionen</th>
            </tr>
          </thead>
          <tbody class="divide-y divide-gray-200">
            <tr v-for="ts in partnershipTimesheets" :key="ts.id" class="hover:bg-gray-50">
              <td class="px-4 py-3">{{ formatDate(ts.date) }}</td>
              <td class="px-4 py-3">{{ ts.first_name }} {{ ts.last_name }}</td>
              <td class="px-4 py-3">{{ ts.order_title }}</td>
              <td class="px-4 py-3">{{ ts.hours_worked }}h</td>
              <td class="px-4 py-3">{{ ts.calculated_amount_cents ? formatCents(ts.calculated_amount_cents) : '-' }}</td>
              <td class="px-4 py-3">
                <span :class="['px-2 py-1 text-xs rounded-full', statusBadge(ts.approval_status).class]">
                  {{ statusBadge(ts.approval_status).text }}
                </span>
              </td>
              <td class="px-4 py-3 text-right space-x-2">
                <template v-if="ts.approval_status === 'pending'">
                  <button 
                    @click="approveTimesheet(ts)"
                    class="text-green-600 hover:text-green-800"
                  >
                    ✓ Freigeben
                  </button>
                  <button 
                    @click="disputeTimesheet(ts)"
                    class="text-red-600 hover:text-red-800"
                  >
                    ✗ Beanstanden
                  </button>
                </template>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <!-- ============================================ -->
    <!-- INVOICES TAB -->
    <!-- ============================================ -->
    <div v-else-if="activeTab === 'invoices'">
      <div v-if="invoices.length === 0" class="bg-gray-50 rounded-lg p-12 text-center text-gray-500">
        Keine Rechnungen vorhanden
      </div>
      <div v-else class="bg-white rounded-lg shadow overflow-hidden">
        <table class="min-w-full divide-y divide-gray-200">
          <thead class="bg-gray-50">
            <tr>
              <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Nr.</th>
              <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Partner</th>
              <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Zeitraum</th>
              <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Richtung</th>
              <th class="px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase">Betrag</th>
              <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Status</th>
              <th class="px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase">Aktionen</th>
            </tr>
          </thead>
          <tbody class="divide-y divide-gray-200">
            <tr v-for="inv in invoices" :key="inv.id" class="hover:bg-gray-50">
              <td class="px-4 py-3 font-mono">{{ inv.invoice_number }}</td>
              <td class="px-4 py-3">{{ inv.partner_name }}</td>
              <td class="px-4 py-3">{{ formatDate(inv.period_start) }} - {{ formatDate(inv.period_end) }}</td>
              <td class="px-4 py-3">
                <span v-if="inv.direction === 'outgoing'" class="text-red-600">📤 Ausgehend</span>
                <span v-else class="text-green-600">📥 Eingehend</span>
              </td>
              <td class="px-4 py-3 text-right font-medium">{{ formatCents(inv.total_cents) }}</td>
              <td class="px-4 py-3">
                <span :class="['px-2 py-1 text-xs rounded-full', statusBadge(inv.status).class]">
                  {{ statusBadge(inv.status).text }}
                </span>
              </td>
              <td class="px-4 py-3 text-right">
                <button 
                  v-if="inv.direction === 'incoming' && inv.status === 'sent'"
                  @click="markAsPaid(inv)"
                  class="text-green-600 hover:text-green-800"
                >
                  Als bezahlt markieren
                </button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <!-- ============================================ -->
    <!-- INVITE MODAL -->
    <!-- ============================================ -->
    <div v-if="showInviteModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div class="bg-white rounded-lg shadow-xl w-full max-w-md p-6">
        <h2 class="text-xl font-bold mb-4">Partner einladen</h2>
        
        <div class="space-y-4">
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">Organisation suchen</label>
            <input 
              v-model="searchQuery"
              @input="searchOrgs"
              type="text"
              placeholder="Name oder Slug eingeben..."
              class="w-full border rounded-lg px-3 py-2"
            />
            <div v-if="searchResults.length > 0" class="mt-1 border rounded-lg shadow-sm max-h-40 overflow-y-auto">
              <button 
                v-for="org in searchResults" 
                :key="org.id"
                @click="selectOrgToInvite(org)"
                class="w-full px-3 py-2 text-left hover:bg-gray-100"
              >
                {{ org.name }} <span class="text-gray-500">@{{ org.slug }}</span>
              </button>
            </div>
          </div>

          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">Vertragsbeginn</label>
            <input 
              v-model="inviteForm.contract_start"
              type="date"
              class="w-full border rounded-lg px-3 py-2"
            />
          </div>

          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">Vertragsende (optional)</label>
            <input 
              v-model="inviteForm.contract_end"
              type="date"
              class="w-full border rounded-lg px-3 py-2"
            />
          </div>

          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">Notizen</label>
            <textarea 
              v-model="inviteForm.notes"
              rows="3"
              class="w-full border rounded-lg px-3 py-2"
              placeholder="Optionale Nachricht..."
            ></textarea>
          </div>
        </div>

        <div class="flex justify-end space-x-2 mt-6">
          <button 
            @click="showInviteModal = false; resetInviteForm()"
            class="px-4 py-2 text-gray-700 hover:bg-gray-100 rounded-lg"
          >
            Abbrechen
          </button>
          <button 
            @click="sendInvite"
            :disabled="inviting || !inviteForm.subcontractor_slug"
            class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50"
          >
            {{ inviting ? 'Wird gesendet...' : 'Einladung senden' }}
          </button>
        </div>
      </div>
    </div>

    <!-- ============================================ -->
    <!-- DETAIL MODAL -->
    <!-- ============================================ -->
    <div v-if="showDetailModal && partnershipDetail" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div class="bg-white rounded-lg shadow-xl w-full max-w-2xl p-6 max-h-[90vh] overflow-y-auto">
        <div class="flex justify-between items-start mb-4">
          <div>
            <h2 class="text-xl font-bold">
              Partnerschaft mit {{ partnershipDetail.isContractor ? partnershipDetail.subcontractor_name : partnershipDetail.contractor_name }}
            </h2>
            <span :class="['px-2 py-1 text-xs rounded-full', statusBadge(partnershipDetail.status).class]">
              {{ statusBadge(partnershipDetail.status).text }}
            </span>
          </div>
          <button @click="showDetailModal = false" class="text-gray-500 hover:text-gray-700">✕</button>
        </div>

        <!-- Info -->
        <div class="grid grid-cols-2 gap-4 mb-6 text-sm">
          <div>
            <span class="text-gray-500">Rolle:</span>
            {{ partnershipDetail.isContractor ? 'Wir sind Auftraggeber' : 'Wir sind Subunternehmer' }}
          </div>
          <div>
            <span class="text-gray-500">Seit:</span>
            {{ formatDate(partnershipDetail.contract_start || partnershipDetail.created_at) }}
          </div>
          <div v-if="partnershipDetail.contract_end">
            <span class="text-gray-500">Bis:</span>
            {{ formatDate(partnershipDetail.contract_end) }}
          </div>
        </div>

        <!-- Rates (only for contractor) -->
        <div v-if="partnershipDetail.isContractor" class="mb-6">
          <div class="flex justify-between items-center mb-2">
            <h3 class="font-semibold">Stundensätze</h3>
            <button 
              @click="openRateModal"
              class="text-sm text-blue-600 hover:text-blue-800"
            >
              + Neuer Satz
            </button>
          </div>
          <div v-if="!partnershipDetail.rates?.length" class="text-gray-500 text-sm">
            Noch keine Sätze definiert
          </div>
          <div v-else class="space-y-2">
            <div 
              v-for="rate in partnershipDetail.rates" 
              :key="rate.id"
              class="flex justify-between items-center bg-gray-50 rounded px-3 py-2"
            >
              <div>
                <span class="font-medium">{{ rate.name }}</span>
                <span v-if="rate.is_default" class="text-xs text-blue-600 ml-2">Standard</span>
              </div>
              <div class="flex items-center space-x-4">
                <span class="font-mono">{{ formatCents(rate.amount_cents) }}/h</span>
                <button 
                  @click="deleteRate(rate)"
                  class="text-red-500 hover:text-red-700"
                >
                  🗑
                </button>
              </div>
            </div>
          </div>
        </div>

        <!-- Stats -->
        <div v-if="partnershipDetail.stats" class="grid grid-cols-3 gap-4 mb-6">
          <div class="bg-gray-50 rounded p-3 text-center">
            <div class="text-xl font-bold">{{ partnershipDetail.stats.completed_orders || 0 }}</div>
            <div class="text-xs text-gray-500">Abgeschlossen</div>
          </div>
          <div class="bg-gray-50 rounded p-3 text-center">
            <div class="text-xl font-bold">{{ partnershipDetail.stats.active_orders || 0 }}</div>
            <div class="text-xs text-gray-500">Aktiv</div>
          </div>
          <div class="bg-gray-50 rounded p-3 text-center">
            <div class="text-xl font-bold">{{ partnershipDetail.stats.pending_orders || 0 }}</div>
            <div class="text-xs text-gray-500">Ausstehend</div>
          </div>
        </div>

        <!-- Actions -->
        <div v-if="partnershipDetail.status === 'active'" class="flex space-x-2">
          <button 
            @click="changeStatus(partnershipDetail, 'paused')"
            class="px-4 py-2 bg-yellow-100 text-yellow-700 rounded hover:bg-yellow-200"
          >
            Pausieren
          </button>
          <button 
            @click="changeStatus(partnershipDetail, 'terminated')"
            class="px-4 py-2 bg-red-100 text-red-700 rounded hover:bg-red-200"
          >
            Beenden
          </button>
        </div>
        <div v-else-if="partnershipDetail.status === 'paused'" class="flex space-x-2">
          <button 
            @click="changeStatus(partnershipDetail, 'active')"
            class="px-4 py-2 bg-green-600 text-white rounded hover:bg-green-700"
          >
            Reaktivieren
          </button>
        </div>
      </div>
    </div>

    <!-- ============================================ -->
    <!-- RATE MODAL -->
    <!-- ============================================ -->
    <div v-if="showRateModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div class="bg-white rounded-lg shadow-xl w-full max-w-md p-6">
        <h2 class="text-xl font-bold mb-4">Neuer Stundensatz</h2>
        
        <div class="space-y-4">
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">Bezeichnung *</label>
            <input 
              v-model="rateForm.name"
              type="text"
              placeholder="z.B. Normaldienst, Nachtschicht..."
              class="w-full border rounded-lg px-3 py-2"
            />
          </div>

          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">Beschreibung</label>
            <input 
              v-model="rateForm.description"
              type="text"
              class="w-full border rounded-lg px-3 py-2"
            />
          </div>

          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">Stundensatz (€) *</label>
            <input 
              v-model.number="rateForm.amount"
              type="number"
              step="0.01"
              min="0"
              class="w-full border rounded-lg px-3 py-2"
            />
          </div>

          <label class="flex items-center">
            <input 
              v-model="rateForm.is_default"
              type="checkbox"
              class="mr-2"
            />
            <span class="text-sm">Als Standard-Satz verwenden</span>
          </label>
        </div>

        <div class="flex justify-end space-x-2 mt-6">
          <button 
            @click="showRateModal = false"
            class="px-4 py-2 text-gray-700 hover:bg-gray-100 rounded-lg"
          >
            Abbrechen
          </button>
          <button 
            @click="saveRate"
            class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
          >
            Speichern
          </button>
        </div>
      </div>
    </div>

    <!-- ============================================ -->
    <!-- SHARE ORDER MODAL -->
    <!-- ============================================ -->
    <div v-if="showShareOrderModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div class="bg-white rounded-lg shadow-xl w-full max-w-md p-6">
        <h2 class="text-xl font-bold mb-4">Auftrag teilen mit {{ selectedPartnership?.partner_name }}</h2>
        
        <div class="space-y-4">
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">Auftrag auswählen *</label>
            <select 
              v-model="shareForm.order_id"
              class="w-full border rounded-lg px-3 py-2"
            >
              <option value="">Bitte wählen...</option>
              <option v-for="order in availableOrders" :key="order.id" :value="order.id">
                {{ order.title }} ({{ formatDate(order.start_date) }})
              </option>
            </select>
          </div>

          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">Stundensatz</label>
            <select 
              v-model="shareForm.rate_id"
              class="w-full border rounded-lg px-3 py-2"
            >
              <option value="">Keiner / Später festlegen</option>
              <option v-for="rate in partnershipDetail?.rates" :key="rate.id" :value="rate.id">
                {{ rate.name }} ({{ formatCents(rate.amount_cents) }}/h)
              </option>
            </select>
          </div>

          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">Benötigte Mitarbeiter</label>
            <input 
              v-model.number="shareForm.required_staff"
              type="number"
              min="1"
              class="w-full border rounded-lg px-3 py-2"
            />
          </div>

          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">Notizen</label>
            <textarea 
              v-model="shareForm.notes"
              rows="2"
              class="w-full border rounded-lg px-3 py-2"
            ></textarea>
          </div>
        </div>

        <div class="flex justify-end space-x-2 mt-6">
          <button 
            @click="showShareOrderModal = false"
            class="px-4 py-2 text-gray-700 hover:bg-gray-100 rounded-lg"
          >
            Abbrechen
          </button>
          <button 
            @click="shareOrder"
            :disabled="!shareForm.order_id"
            class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50"
          >
            Auftrag teilen
          </button>
        </div>
      </div>
    </div>
  </div>
</template>
