<template>
  <section class="content-grid">
    <v-card class="span-12 panel-pad">
      <h2 class="section-title mb-1">Section 179 — deduction limitation &amp; carryover</h2>
      <p class="quiet text-body-2 mb-3">
        Return-level §179: the total §179 elected across this company's assets for a tax year, capped by the annual dollar
        limit (reduced by the investment phase-out) and by your business taxable income. Any disallowed amount carries
        forward to next year. The per-asset engine still caps each asset individually; this is the aggregate return view.
      </p>
      <div class="toolbar-row" style="flex-wrap:wrap;gap:12px">
        <v-select v-model="book" :items="bookItems" label="Book" density="compact" hide-details style="max-width:200px" @update:model-value="load" />
        <v-text-field v-model.number="year" type="number" label="Tax year" density="compact" hide-details style="max-width:130px" @update:model-value="load" />
        <v-text-field v-model.number="taxableIncome" type="number" prefix="$" label="Business taxable income" density="compact" hide-details style="max-width:240px" hint="Leave blank to skip the income limit" persistent-hint />
        <v-btn color="primary" prepend-icon="mdi-content-save" :loading="saving" @click="save">Save &amp; carry forward</v-btn>
      </div>
      <v-alert v-if="message" type="success" density="compact" class="mt-3">{{ message }}</v-alert>
      <v-alert v-if="error" type="error" density="compact" class="mt-3">{{ error }}</v-alert>
    </v-card>

    <v-card v-if="s" class="span-7 panel-pad">
      <h3 class="section-title mb-3">Limitation worksheet — {{ s.book_code }} {{ s.tax_year }}</h3>
      <table class="worksheet">
        <tbody>
          <tr><td>§179 elected ({{ s.asset_count }} asset{{ s.asset_count === 1 ? '' : 's' }})</td><td class="r">{{ currency(s.elected) }}</td></tr>
          <tr><td>Carryover from {{ s.tax_year - 1 }}</td><td class="r">{{ currency(s.prior_carryover) }}</td></tr>
          <tr class="sub"><td>Available for deduction</td><td class="r">{{ currency(s.available) }}</td></tr>
          <tr><td>Annual dollar limit{{ s.base_limit ? ` (base ${currency(s.base_limit)})` : '' }}</td><td class="r">{{ s.dollar_limit === null ? 'uncapped' : currency(s.dollar_limit) }}</td></tr>
          <tr v-if="s.phaseout_reduction"><td class="quiet">— investment phase-out reduction (cost {{ currency(s.property_cost) }} over {{ currency(s.phaseout_threshold) }})</td><td class="r quiet">−{{ currency(s.phaseout_reduction) }}</td></tr>
          <tr class="sub"><td>Allowed after dollar limit</td><td class="r">{{ currency(s.dollar_allowed) }}</td></tr>
          <tr v-if="s.taxable_income !== null"><td>Business taxable income limit</td><td class="r">{{ currency(s.taxable_income) }}</td></tr>
          <tr class="total"><td>Allowed §179 deduction</td><td class="r">{{ currency(s.allowed_deduction) }}</td></tr>
          <tr class="carry"><td>Carryover to {{ s.tax_year + 1 }}</td><td class="r">{{ currency(s.carryover_to_next) }}</td></tr>
        </tbody>
      </table>
      <v-alert v-if="s.income_limited" type="info" density="compact" variant="tonal" class="mt-3">
        The deduction is limited by taxable income; {{ currency(s.carryover_to_next) }} carries forward.
      </v-alert>
    </v-card>

    <v-card v-if="s" class="span-5 panel-pad">
      <h3 class="section-title mb-2">How it works</h3>
      <ul class="quiet text-body-2">
        <li>§179 elected = sum of each asset's §179 amount on the selected book, placed in service in the year.</li>
        <li>The <strong>annual dollar limit</strong> ({{ year }}) is reduced dollar-for-dollar once §179 property cost exceeds the phase-out threshold.</li>
        <li>The <strong>taxable-income limit</strong> caps the deduction at your business income; it can't create a loss.</li>
        <li><strong>Carryover</strong> = available − allowed, and is added to next year's available amount when you save.</li>
      </ul>
      <p class="quiet text-caption mt-2">Limit figures are maintained in Admin → Application Configuration → Section 179 limits.</p>
    </v-card>
  </section>
</template>

<script>
import { apiRequest } from '../services/api';
import { currency } from '../utils/format';

// Section 179 return-level limitation & carryover. Aggregates §179 elected for a (book, year), applies the
// annual dollar limit + phase-out and the business taxable-income limit, and persists the carryover so the
// next year picks it up. Backed by /api/section-179/limitation (GET summary, PUT save).
export default {
  props: { token: { type: String, required: true } },
  data() {
    return { books: [], book: 'FEDERAL', year: new Date().getFullYear(), taxableIncome: null, s: null, saving: false, message: '', error: '' };
  },
  computed: {
    bookItems() { return this.books.map((b) => b.code); }
  },
  mounted() { this.loadBooks(); },
  methods: {
    currency,
    async api(path, options = {}) { return apiRequest(path, this.token, options); },
    async loadBooks() {
      try {
        const data = await (await this.api('/api/books')).json();
        this.books = data.books;
        const primary = this.books.find((b) => b.is_primary && b.code !== 'GAAP') || this.books.find((b) => b.code === 'FEDERAL') || this.books[0];
        if (primary) this.book = primary.code;
      } catch (error) { this.error = error.message; }
      this.load();
    },
    async load() {
      this.error = '';
      try {
        const q = new URLSearchParams({ book: this.book, year: String(this.year) });
        const data = await (await this.api(`/api/section-179/limitation?${q.toString()}`)).json();
        this.s = data.summary;
        if (this.taxableIncome === null && this.s.taxable_income !== null) this.taxableIncome = this.s.taxable_income;
      } catch (error) { this.error = error.message; }
    },
    async save() {
      this.saving = true; this.message = ''; this.error = '';
      try {
        const data = await (await this.api('/api/section-179/limitation', { method: 'PUT', body: JSON.stringify({ book: this.book, year: this.year, taxable_income: this.taxableIncome }) })).json();
        this.s = data.summary;
        this.message = `Saved. Carryover to ${this.s.tax_year + 1}: ${currency(this.s.carryover_to_next)}.`;
      } catch (error) { this.error = error.message; } finally { this.saving = false; }
    }
  }
};
</script>

<style scoped>
.worksheet { width: 100%; border-collapse: collapse; }
.worksheet td { padding: 6px 8px; border-bottom: 1px solid rgba(128, 128, 128, 0.14); }
.worksheet td.r { text-align: right; font-variant-numeric: tabular-nums; }
.worksheet tr.sub td { font-weight: 600; border-top: 1px solid rgba(128, 128, 128, 0.3); }
.worksheet tr.total td { font-weight: 700; font-size: 1.05rem; border-top: 2px solid rgba(var(--v-theme-primary), 0.5); }
.worksheet tr.carry td { color: rgb(var(--v-theme-primary)); font-weight: 600; }
</style>
