/* =============================================================
   PART 5 — All‑in‑One Export (Cover + Sections + Charts + Brand)
   ============================================================= */

/* =========================
   File: src/services/export/assemblePlan.ts
   ========================= */
import type { BrandKit } from "../../types/brand";

export interface ExportAssembleInput {
  title: string;                 // Plan title
  subtitle?: string;             // Optional subtitle
  coverDataUrl?: string;         // PNG data URL for cover (from CoverDesigner)
  sections: Array<{ id: string; title: string; content: string }>; // current plan sections in order
  appendixImages?: Array<{ title: string; dataUrl: string }>;      // any extra chart/table snapshots
  includeTOC?: boolean;          // defaults true
}

export interface AssembledDocument {
  markdown: string;              // fully assembled MD
  meta: { words: number; images: number };
}

function sanitize(s: string){
  return (s || "").replace(/\u0000/g, "");
}

export function assembleMarkdownDoc(input: ExportAssembleInput, brand?: BrandKit): AssembledDocument {
  const parts: string[] = [];
  const title = sanitize(input.title || "Business Plan");
  const subtitle = sanitize(input.subtitle || "");

  // Cover
  parts.push(`# ${title}`);
  if (subtitle) parts.push(`**${subtitle}**`);
  if (brand?.name) parts.push(`\n*Prepared for **${brand.name}***\n`);
  if (input.coverDataUrl) {
    parts.push(`\n![Cover](${input.coverDataUrl})\n`);
  }

  // TOC
  if (input.includeTOC !== false) {
    parts.push(`\n## Table of Contents`);
    input.sections.forEach((s, idx)=> {
      const anchor = s.title.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/(^-|-$)/g, "");
      parts.push(`${idx+1}. [${sanitize(s.title)}](#${anchor})`);
    });
    if (input.appendixImages?.length) parts.push(`${input.sections.length+1}. [Appendix](#appendix)`);
  }

  // Sections
  input.sections.forEach((s)=>{
    const heading = sanitize(s.title || "Section");
    parts.push(`\n\n## ${heading}`);
    // content may already contain markdown + embedded data URLs from snapshots
    parts.push(sanitize(s.content || "_No content yet._"));
  });

  // Appendix (snapshots)
  if (input.appendixImages?.length){
    parts.push(`\n\n## Appendix`);
    input.appendixImages.forEach(img=>{
      const t = sanitize(img.title || "Figure");
      parts.push(`\n### ${t}`);
      parts.push(`![${t}](${img.dataUrl})`);
    });
  }

  const markdown = parts.join("\n\n");
  const words = markdown.split(/\s+/).filter(Boolean).length;
  const images = (markdown.match(/!\[/g) || []).length;
  return { markdown, meta: { words, images } };
}

/* =========================
   File: src/services/export/index.ts
   ========================= */
import { assembleMarkdownDoc } from "./assemblePlan";
import { useBrandKitStore } from "../../state/useBrandKitStore";
import { exportPlanPdfBrandAware } from "../ai/planExportPdf";
import { exportPlanDocxBrandAware } from "../ai/planExportDocx";

export async function exportFullPlanPDF(opts: Parameters<typeof assembleMarkdownDoc>[0]){
  const brand = useBrandKitStore.getState().getCurrentKit();
  const doc = assembleMarkdownDoc(opts, brand || undefined);
  const filename = slugify(opts.title || "Business Plan") + ".pdf";
  await exportPlanPdfBrandAware(doc, filename);
  return { filename, meta: doc.meta };
}

export async function exportFullPlanDOCX(opts: Parameters<typeof assembleMarkdownDoc>[0]){
  const brand = useBrandKitStore.getState().getCurrentKit();
  const doc = assembleMarkdownDoc(opts, brand || undefined);
  const filename = slugify(opts.title || "Business Plan") + ".docx";
  await exportPlanDocxBrandAware(doc, filename);
  return { filename, meta: doc.meta };
}

function slugify(s: string){
  return (s||"").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/(^-|-$)/g, "").slice(0,80);
}

/* =========================
   File: src/components/ExportBar.tsx
   (Drop-in action bar to call the all‑in‑one export)
   ========================= */
import React from "react";
import { usePlanStoreV2 } from "../state/usePlanStore.v2";
import { useBrandKitStore } from "../state/useBrandKitStore";
import { exportFullPlanPDF, exportFullPlanDOCX } from "../services/export";

export function ExportBar({ coverDataUrl }:{ coverDataUrl?: string }){
  const sections = usePlanStoreV2((s)=> s.sections);
  const brand = useBrandKitStore((s)=> s.getCurrentKit());
  const title = brand?.name ? `${brand.name} – Business Plan` : "Business Plan";

  async function onPdf(){
    const result = await exportFullPlanPDF({
      title,
      subtitle: "Generated by IBrandBiz",
      coverDataUrl,
      sections: sections.map(s=> ({ id: s.id, title: s.title, content: s.content })),
      includeTOC: true,
    });
    console.log("Exported PDF:", result);
  }
  async function onDocx(){
    const result = await exportFullPlanDOCX({
      title,
      subtitle: "Generated by IBrandBiz",
      coverDataUrl,
      sections: sections.map(s=> ({ id: s.id, title: s.title, content: s.content })),
      includeTOC: true,
    });
    console.log("Exported DOCX:", result);
  }

  return (
    <div className="flex gap-2">
      <button className="rounded-2xl border px-3 py-2" onClick={onPdf}>Export PDF</button>
      <button className="rounded-2xl border px-3 py-2" onClick={onDocx}>Export DOCX</button>
    </div>
  );
}

/* =========================
   Patch: src/pages/Builder.v7.tsx – mount ExportBar
   ========================= */
import { ExportBar } from "../components/ExportBar";

// In the right column (e.g., under Cover & Theme):
// <div>
//   <h2 className="text-xl font-semibold mb-2">Export</h2>
//   <ExportBar /* pass latest cover png if you store it in state */ />
// </div>

/* =========================
   Notes
   - `assembleMarkdownDoc` merges the cover, ToC, sections, and appendix into one MD string.
   - The brand-aware exporters you already added consume the MD and inject fonts/colors.
   - If you snapshot charts/tables into sections, they’re already embedded via data URLs.
   - You can pass extra images into `appendixImages` if you keep snapshots outside sections.
   ========================= */
