// Gesamtprojekt-Export (Demo-067 C, KAR-982) — XLSX. Same content as
// project-docx.ts (Stammdaten/Agenda/Maßnahmen/Modul-Kurzfassungen), laid
// out as worksheets instead of a narrative document — the Gesamtprojekt-
// Export is the one export the task asks for in both formats. Styling
// mirrors the existing reference exports (lib/qaf-differences/internal/
// export.ts, lib/assessment-export.ts): dynamic ExcelJS import, brand-fill
// header row, frozen header, autoFilter. ARGB literals here are generated-
// document colors, not Tailwind/UI — see docx-shared.ts's module header for
// why scripts/check-hardcoded-colors.mjs does not apply.
//
// Pure function of its inputs — no Supabase/DB access.

import { buildAiInstructionBlock } from './ai-instruction-block'
import { formatDeDate, stammdatenEntries, workshopActionHeaders, workshopActionRow } from './project-content'
import type { ProjectExportInput } from './project-types'

const HEADER_FILL_ARGB = 'FF037493'
const HEADER_TEXT_ARGB = 'FFFFFFFF'
const DISCLAIMER_FILL_ARGB = 'FFFFE082'
const LABEL_FILL_ARGB = 'FFF7F9FB'

function styleHeaderRow(row: import('exceljs').Row) {
  row.font = { bold: true, color: { argb: HEADER_TEXT_ARGB }, size: 11, name: 'Calibri' }
  row.fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: HEADER_FILL_ARGB } }
  row.eachCell((cell) => {
    cell.alignment = { vertical: 'middle', horizontal: 'center', wrapText: true }
  })
}

export async function buildProjectCopilotXlsx(input: ProjectExportInput): Promise<ArrayBuffer> {
  const { stammdaten, agendas, workshopActions, moduleSummaries, generatedAtLabel } = input
  const { default: ExcelJS } = await import('exceljs')
  const wb = new ExcelJS.Workbook()
  wb.creator = 'SupplierPulse'
  wb.created = new Date()

  const aiBlock = buildAiInstructionBlock({
    exportTitle: 'Gesamtprojekt-Export',
    aboutText:
      'Dieses Dokument ist der Gesamtprojekt-Export — eine Zusammenfassung eines Lieferantenentwicklungs-' +
      'Projekts über alle Module hinweg: Projekt-Stammdaten, Workshop-Agenda, Maßnahmen sowie ' +
      'Kurzfassungen des Stands in den Fachmodulen (Fabrikanalyse/QAF-Vergleich/Wertstrom/LSC).',
    usageHints: [
      'Erstelle eine Projekt-Statusübersicht: Stammdaten, offene Maßnahmen nach Priorität, Modul-Fortschritt.',
      'Jedes Tabellenblatt ist eigenständig lesbar — es referenziert keine Zellen aus anderen Blättern.',
      'Wenn ein Modul-Blatt "keine Daten" zeigt, das nicht als Ergebnis interpretieren, sondern als "noch nicht erfasst".',
    ],
    isDemo: stammdaten.isDemo,
  })

  // ── Sheet 1: Anleitung (AI-instruction block) ───────────────────────────
  const info = wb.addWorksheet('Anleitung')
  info.columns = [{ width: 28 }, { width: 100 }]
  info.addRow([aiBlock.heading, '']).font = { bold: true, size: 14 }
  info.addRow([])
  info.addRow(['Worum geht es', aiBlock.aboutText])
  info.addRow([])
  info.addRow([aiBlock.usageHeading, '']).font = { bold: true }
  for (const hint of aiBlock.usageHints) info.addRow(['', `• ${hint}`])
  info.addRow([])
  info.addRow([aiBlock.glossaryHeading, '']).font = { bold: true }
  for (const g of aiBlock.glossary) info.addRow([g.term, g.definition])
  if (aiBlock.disclaimer) {
    info.addRow([])
    const r = info.addRow(['Demo-Hinweis', aiBlock.disclaimer])
    r.eachCell((cell) => {
      cell.fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: DISCLAIMER_FILL_ARGB } }
    })
  }
  info.eachRow((row) => {
    row.alignment = { wrapText: true, vertical: 'top' }
  })

  // ── Sheet 2: Stammdaten ──────────────────────────────────────────────────
  const stamm = wb.addWorksheet('Stammdaten')
  stamm.columns = [{ width: 26 }, { width: 60 }]
  for (const [label, value] of [...stammdatenEntries(stammdaten), ['Erzeugt am', generatedAtLabel] as const]) {
    const row = stamm.addRow([label, value])
    row.getCell(1).font = { bold: true }
    row.getCell(1).fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: LABEL_FILL_ARGB } }
  }

  // ── Sheet 3: Agenda ──────────────────────────────────────────────────────
  const agendaWs = wb.addWorksheet('Agenda')
  agendaWs.columns = [
    { header: 'Agenda', key: 'agenda', width: 24 },
    { header: 'Tag', key: 'day', width: 20 },
    { header: 'Datum', key: 'date', width: 12 },
    { header: 'Zeit', key: 'time', width: 14 },
    { header: 'Titel', key: 'title', width: 36 },
    { header: 'Verantwortlich', key: 'resp', width: 20 },
    { header: 'Ort', key: 'loc', width: 20 },
  ]
  styleHeaderRow(agendaWs.getRow(1))
  for (const agenda of agendas) {
    for (const day of agenda.days) {
      const dayLabel = `${day.title ?? 'Tag'}${day.date ? ` (${formatDeDate(day.date)})` : ''}`
      if (day.items.length === 0) {
        agendaWs.addRow({ agenda: agenda.title, day: dayLabel, date: formatDeDate(day.date), time: '', title: '(keine Programmpunkte)', resp: '', loc: '' })
        continue
      }
      for (const item of day.items) {
        agendaWs.addRow({
          agenda: agenda.title,
          day: dayLabel,
          date: formatDeDate(day.date),
          time: [item.startTime, item.endTime].filter(Boolean).join('–'),
          title: item.title,
          resp: item.responsible ?? '',
          loc: item.location ?? '',
        })
      }
    }
  }
  if (agendas.length === 0) agendaWs.addRow({ agenda: '(keine Agenda angelegt)' })
  agendaWs.views = [{ state: 'frozen', ySplit: 1 }]
  agendaWs.autoFilter = { from: { row: 1, column: 1 }, to: { row: 1, column: 7 } }

  // ── Sheet 4: Maßnahmen ───────────────────────────────────────────────────
  const actionsWs = wb.addWorksheet('Maßnahmen')
  const headers = workshopActionHeaders()
  actionsWs.columns = headers.map((h, i) => ({ header: h, key: `c${i}`, width: i === 2 ? 48 : 16 }))
  styleHeaderRow(actionsWs.getRow(1))
  for (const a of workshopActions) actionsWs.addRow(workshopActionRow(a) as string[])
  if (workshopActions.length === 0) actionsWs.addRow(['(keine Maßnahmen erfasst)'])
  actionsWs.views = [{ state: 'frozen', ySplit: 1 }]
  actionsWs.autoFilter = { from: { row: 1, column: 1 }, to: { row: 1, column: headers.length } }

  // ── Sheet 5: Modulübersicht ──────────────────────────────────────────────
  const modWs = wb.addWorksheet('Modulübersicht')
  modWs.columns = [
    { header: 'Modul', key: 'label', width: 22 },
    { header: 'Kurzfassung', key: 'count', width: 20 },
    { header: 'Eintrag', key: 'item', width: 70 },
  ]
  styleHeaderRow(modWs.getRow(1))
  for (const m of moduleSummaries) {
    if (m.items.length === 0) {
      modWs.addRow({ label: m.label, count: m.countLabel, item: '(keine Einträge)' })
      continue
    }
    for (const item of m.items) modWs.addRow({ label: m.label, count: m.countLabel, item })
  }
  if (moduleSummaries.length === 0) modWs.addRow({ label: '(keine Modul-Daten für dieses Projekt)' })
  modWs.views = [{ state: 'frozen', ySplit: 1 }]

  return wb.xlsx.writeBuffer()
}
