<template>
  <section class="py-8 space-y-6">
    <div class="flex items-center justify-between">
      <div>
        <h2 class="text-2xl font-semibold">Compensation</h2>
        <div class="flex items-center gap-2 mt-1">
          <span class="text-xs font-mono">
            Runway: {{ Math.round(metrics.runway) }}mo
          </span>
        </div>
      </div>
      <div class="flex gap-2">
        <button
          @click="onExport"
          class="px-4 py-2 border-2 border-black bg-white font-bold uppercase text-sm hover:shadow-[2px_2px_0px_0px_rgba(0,0,0,1)] transition-shadow">
          Export JSON
        </button>
        <button
          @click="onImport"
          class="px-4 py-2 border-2 border-black bg-white font-bold uppercase text-sm hover:shadow-[2px_2px_0px_0px_rgba(0,0,0,1)] transition-shadow">
          Import JSON
        </button>
      </div>
    </div>

    <!-- Key Metrics Row -->
    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
      <CoverageMeter
        :funded-paid-hours="Math.round(metrics.totalTargetHours * 0.65)"
        :target-hours="metrics.totalTargetHours"
        description="Funded hours vs target capacity across all members." />

      <ReserveMeter
        :current-savings="savingsProgress.current"
        :savings-target-months="savingsProgress.targetMonths"
        :monthly-burn="getMonthlyBurn()"
        :description="`${savingsProgress.progressPct.toFixed(0)}% of savings target reached. ${savingsProgress.gap > 0 ? 'Gap: ' + $format.currency(savingsProgress.gap) : 'Target achieved!'}`" />
    </div>

    <!-- Dashboard Components with Wizard Styling -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
      <!-- Needs Coverage Bars -->
      <div class="border-2 border-black bg-white shadow-[4px_4px_0px_0px_rgba(0,0,0,1)]">
        <div class="border-b-2 border-black p-4">
          <h3 class="text-lg font-bold uppercase">Member Coverage</h3>
        </div>
        <div class="p-4">
          <NeedsCoverageBars />
        </div>
      </div>

      <!-- Milestone-Runway Overlay -->
      <div class="border-2 border-black bg-white shadow-[4px_4px_0px_0px_rgba(0,0,0,1)]">
        <div class="border-b-2 border-black p-4">
          <h3 class="text-lg font-bold uppercase">Runway vs Milestones</h3>
        </div>
        <div class="p-4">
          <MilestoneRunwayOverlay />
        </div>
      </div>
    </div>

    <!-- Alerts Section with Wizard Styling -->
    <div class="border-2 border-black bg-white shadow-[4px_4px_0px_0px_rgba(0,0,0,1)]">
      <div class="border-b-2 border-black p-4">
        <h3 class="text-lg font-bold uppercase">Alerts</h3>
      </div>
      <div class="p-4 space-y-4">
        <!-- Concentration Risk Alert -->
        <div
          v-if="topSourcePct > 50"
          class="border-2 border-red-600 bg-red-50 p-4">
          <div class="flex items-start gap-3">
            <span class="text-red-600 font-bold text-xl">!</span>
            <div class="flex-1">
              <h4 class="font-bold uppercase mb-1">Revenue Concentration Risk</h4>
              <p class="text-sm mb-2">{{ topStreamName }} = {{ topSourcePct }}% of total → consider balancing</p>
              <button 
                @click="handleAlertNavigation('/tools/', 'concentration')"
                class="text-sm underline font-bold">
                VIEW DETAILS
              </button>
            </div>
          </div>
        </div>
          
        <!-- Cushion Breach Alert -->
        <div
          v-if="alerts.cushionBreach"
          class="border-2 border-orange-600 bg-orange-50 p-4">
          <div class="flex items-start gap-3">
            <span class="text-orange-600 font-bold text-xl">!</span>
            <div class="flex-1">
              <h4 class="font-bold uppercase mb-1">Cash Cushion Breach Forecast</h4>
              <p class="text-sm mb-2">Projected to breach minimum cushion in week {{ cushionForecast.firstBreachWeek || 'unknown' }}</p>
              <div class="flex gap-4">
                <button 
                  @click="handleAlertNavigation('/tools/cash', 'breach-forecast')"
                  class="text-sm underline font-bold">
                  VIEW CALENDAR
                </button>
                <button 
                  @click="handleAlertNavigation('/tools/budget', 'expenses')"
                  class="text-sm underline font-bold">
                  ADJUST BUDGET
                </button>
              </div>
            </div>
          </div>
        </div>
          
        <!-- Savings Below Target Alert -->
        <div
          v-if="alerts.savingsBelowTarget"
          class="border-2 border-yellow-600 bg-yellow-50 p-4">
          <div class="flex items-start gap-3">
            <span class="text-yellow-600 font-bold text-xl">!</span>
            <div class="flex-1">
              <h4 class="font-bold uppercase mb-1">Savings Below Target</h4>
              <p class="text-sm mb-2">{{ savingsProgress.progressPct.toFixed(0) }}% of target reached. Build savings before increasing paid hours.</p>
              <div class="flex gap-4">
                <button 
                  @click="handleAlertNavigation('/tools/budget', 'savings')"
                  class="text-sm underline font-bold">
                  VIEW PROGRESS
                </button>
                <button 
                  @click="handleAlertNavigation('/tools/coop-builder', 'policies')"
                  class="text-sm underline font-bold">
                  ADJUST POLICIES
                </button>
              </div>
            </div>
          </div>
        </div>
          
        <!-- Over-Deferred Member Alert -->
        <div
          v-if="deferredAlert.show"
          class="border-2 border-purple-600 bg-purple-50 p-4">
          <div class="flex items-start gap-3">
            <span class="text-purple-600 font-bold text-xl">!</span>
            <div class="flex-1">
              <h4 class="font-bold uppercase mb-1">Member Over-Deferred</h4>
              <p class="text-sm mb-2">{{ deferredAlert.description }}</p>
              <button 
                @click="handleAlertNavigation('/tools/coop-builder', 'members')"
                class="text-sm underline font-bold">
                REVIEW MEMBERS
              </button>
            </div>
          </div>
        </div>
          
        <!-- Success message when no alerts -->
        <div v-if="!alerts.cushionBreach && !alerts.savingsBelowTarget && topSourcePct <= 50 && !deferredAlert.show" 
             class="text-center py-8">
          <span class="text-4xl font-bold">✓</span>
          <p class="font-bold uppercase mt-2">All systems looking good!</p>
          <p class="text-sm mt-1">No critical alerts at this time.</p>
        </div>
      </div>
    </div>




    <!-- Quick Actions with Wizard Styling -->
    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
      <button
        @click="navigateTo('/tools/cash-flow')"
        class="border-2 border-black bg-white p-4 text-left hover:shadow-[4px_4px_0px_0px_rgba(0,0,0,1)] transition-shadow">
        <div class="font-bold uppercase mb-1">Cash Flow Analysis</div>
        <div class="text-sm">Detailed runway & one-time events</div>
      </button>

      <button
        @click="navigateTo('/tools/budget')"
        class="border-2 border-black bg-white p-4 text-left hover:shadow-[4px_4px_0px_0px_rgba(0,0,0,1)] transition-shadow">
        <div class="font-bold uppercase mb-1">Budget Planning</div>
        <div class="text-sm">Manage expenses & savings</div>
      </button>
    </div>
  </section>
</template>

<script setup lang="ts">
// Dashboard page
const { $format } = useNuxtApp();

// Use real store data instead of fixtures
const membersStore = useMembersStore();
const policiesStore = usePoliciesStore();
const streamsStore = useStreamsStore();
const budgetStore = useBudgetStore();
const cashStore = useCashStore();

// Runway composable with operating mode integration
const { getDualModeRunway, getMonthlyBurn } = useRunway();

// Cushion forecast and savings progress
const { savingsProgress, cushionForecast, alerts } = useCushionForecast();


// Calculate metrics from real store data
const metrics = computed(() => {
  const totalTargetHours = membersStore.members.reduce(
    (sum, member) => sum + (member.capacity?.targetHours || 0),
    0
  );

  const totalTargetRevenue = streamsStore.streams.reduce(
    (sum, stream) => sum + (stream.targetMonthlyAmount || 0),
    0
  );

  const totalOverheadCosts = budgetStore.overheadCosts.reduce(
    (sum, cost) => sum + (cost.amount || 0),
    0
  );

  // Use integrated runway calculations that respect operating mode
  const currentMode = 'target'; // Always target mode now
  const monthlyBurn = getMonthlyBurn(currentMode);
  
  // Use actual cash store values with fallback
  const cash = cashStore.currentCash || 50000;
  const savings = cashStore.currentSavings || 15000;
  const totalLiquid = cash + savings;
  
  // Get dual-mode runway data
  const runwayData = getDualModeRunway(cash, savings);
  const runway = currentMode === 'target' ? runwayData.target : runwayData.minimum;

  return {
    totalTargetHours,
    totalTargetRevenue,
    monthlyPayroll: runwayData.minBurn, // Use actual calculated payroll
    monthlyBurn,
    runway,
    runwayData, // Include dual-mode data
    finances: {
      currentBalances: {
        cash: cashStore.currentCash,
        savings: cashStore.currentSavings,
        totalLiquid,
      },
      policies: {
        equalHourlyWage: policiesStore.equalHourlyWage,
        payrollOncostPct: policiesStore.payrollOncostPct,
        savingsTargetMonths: policiesStore.savingsTargetMonths,
        minCashCushionAmount: policiesStore.minCashCushionAmount,
      },
      deferredLiabilities: {
        totalDeferred: membersStore.members.reduce(
          (sum, m) =>
            sum + (m.deferredHours || 0) * policiesStore.equalHourlyWage,
          0
        ),
      },
      surplus: Math.max(0, totalTargetRevenue - monthlyBurn),
      savingsGap: Math.max(
        0,
        policiesStore.savingsTargetMonths * monthlyBurn -
          cashStore.currentSavings
      ),
    },
  };
});

// Calculate concentration metrics
const topSourcePct = computed(() => {
  if (streamsStore.streams.length === 0) return 0;
  const amounts = streamsStore.streams.map((s) => s.targetMonthlyAmount || 0);
  const total = amounts.reduce((sum, amt) => sum + amt, 0);
  return total > 0 ? Math.round((Math.max(...amounts) / total) * 100) : 0;
});

const topStreamName = computed(() => {
  if (streamsStore.streams.length === 0) return 'No streams';
  const amounts = streamsStore.streams.map((s) => s.targetMonthlyAmount || 0);
  const maxAmount = Math.max(...amounts);
  const topStream = streamsStore.streams.find(s => (s.targetMonthlyAmount || 0) === maxAmount);
  return topStream?.name || 'Unknown stream';
});

const concentrationStatus = computed(() => {
  if (topSourcePct.value > 50) return "red";
  if (topSourcePct.value > 35) return "yellow";
  return "green";
});

const concentrationColor = computed(() => {
  if (topSourcePct.value > 50) return "text-red-600";
  if (topSourcePct.value > 35) return "text-yellow-600";
  return "text-green-600";
});

function getRunwayColor(months: number): string {
  if (months >= 6) return 'text-green-600'
  if (months >= 3) return 'text-yellow-600' 
  return 'text-red-600'
}


// Cash breach description
const cashBreachDescription = computed(() => {
  // Check cash store for first breach week from projections
  const breachWeek = cashStore.weeklyProjections.find(
    (week) => week.breachesCushion
  );
  if (breachWeek) {
    return `Week ${breachWeek.number} would drop below your minimum cushion.`;
  }
  return "No cushion breach currently projected.";
});

const onExport = () => {
  const data = exportAll();
  const blob = new Blob([JSON.stringify(data, null, 2)], {
    type: "application/json",
  });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = "urgent-tools.json";
  a.click();
  URL.revokeObjectURL(url);
};

const onImport = async () => {
  const input = document.createElement("input");
  input.type = "file";
  input.accept = "application/json";
  input.onchange = async () => {
    const file = input.files?.[0];
    if (!file) return;
    const text = await file.text();
    importAll(JSON.parse(text));
  };
  input.click();
};

const { exportAll, importAll } = useFixtureIO();


// Deferred alert logic
const deferredAlert = computed(() => {
  const maxDeferredRatio = 1.5; // From CLAUDE.md - flag if >1.5× monthly payroll
  const monthlyPayrollCost = getMonthlyBurn() * 0.7; // Estimate payroll as 70% of burn
  const totalDeferred = membersStore.members.reduce(
    (sum, m) => sum + (m.deferredHours || 0) * policiesStore.equalHourlyWage,
    0
  );
  
  const deferredRatio = monthlyPayrollCost > 0 ? totalDeferred / monthlyPayrollCost : 0;
  const show = deferredRatio > maxDeferredRatio;
  
  const overDeferredMembers = membersStore.members.filter(m => {
    const memberDeferred = (m.deferredHours || 0) * policiesStore.equalHourlyWage;
    const memberMonthlyPay = m.monthlyPayPlanned || 0;
    return memberDeferred > memberMonthlyPay * 2; // Member has >2 months of pay deferred
  });
  
  return {
    show,
    description: show 
      ? `${overDeferredMembers.length} member(s) over deferred cap. Total: ${(deferredRatio * 100).toFixed(0)}% of monthly payroll.`
      : ''
  };
});

// Alert navigation with context
function handleAlertNavigation(path: string, section?: string) {
  // Store alert context for target page to highlight relevant section
  if (section) {
    localStorage.setItem('urgent-tools-alert-context', JSON.stringify({ section, timestamp: Date.now() }));
  }
  navigateTo(path);
};
</script>