"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/main.ts
var main_exports = {};
__export(main_exports, {
  default: () => BookPrintPlugin
});
module.exports = __toCommonJS(main_exports);
var import_obsidian4 = require("obsidian");

// ../../packages/shared/dist/types.js
var DEFAULT_PLUGIN_SETTINGS = {
  defaultAuthorName: "",
  defaultPublisherImprint: "",
  defaultCopyrightHolder: "",
  defaultCopyrightNotice: "",
  defaultWebsite: "",
  defaultPublisherContact: "",
  backendApiUrl: "http://localhost:3000",
  printEnvironment: "sandbox"
};

// src/settings/BookPrintSettingsTab.ts
var import_obsidian = require("obsidian");
var BookPrintSettingsTab = class extends import_obsidian.PluginSettingTab {
  plugin;
  constructor(app, plugin) {
    super(app, plugin);
    this.plugin = plugin;
  }
  display() {
    const { containerEl } = this;
    containerEl.empty();
    containerEl.createEl("h2", { text: "Book Print \u2014 Settings" });
    containerEl.createEl("h3", { text: "Default Book Metadata" });
    new import_obsidian.Setting(containerEl).setName("Default Author Name").setDesc("Default author name pre-populated in new Book Projects.").addText(
      (text) => text.setPlaceholder("e.g. Joseph Rastovich").setValue(this.plugin.pluginSettings.defaultAuthorName).onChange(async (value) => {
        this.plugin.pluginSettings.defaultAuthorName = value;
        await this.plugin.saveSettings();
      })
    );
    new import_obsidian.Setting(containerEl).setName("Default Publisher / Imprint").setDesc("Optional publishing imprint (e.g. Rastovich Press).").addText(
      (text) => text.setPlaceholder("e.g. Rastovich Press").setValue(this.plugin.pluginSettings.defaultPublisherImprint).onChange(async (value) => {
        this.plugin.pluginSettings.defaultPublisherImprint = value;
        await this.plugin.saveSettings();
      })
    );
    new import_obsidian.Setting(containerEl).setName("Default Copyright Holder").setDesc("Optional copyright holder name.").addText(
      (text) => text.setPlaceholder("e.g. Joseph Rastovich").setValue(this.plugin.pluginSettings.defaultCopyrightHolder).onChange(async (value) => {
        this.plugin.pluginSettings.defaultCopyrightHolder = value;
        await this.plugin.saveSettings();
      })
    );
    new import_obsidian.Setting(containerEl).setName("Default Website").setDesc("Optional author/publisher website printed on copyright page.").addText(
      (text) => text.setPlaceholder("https://example.com").setValue(this.plugin.pluginSettings.defaultWebsite).onChange(async (value) => {
        this.plugin.pluginSettings.defaultWebsite = value;
        await this.plugin.saveSettings();
      })
    );
    containerEl.createEl("h3", { text: "Default Shipping Address" });
    containerEl.createEl("p", {
      text: "Saved locally for fast physical book checkout quotes. Never uploaded until an order is placed.",
      cls: "setting-item-description"
    });
    const addr = this.plugin.pluginSettings.defaultShippingAddress || {
      fullName: "",
      addressLine1: "",
      addressLine2: "",
      city: "",
      state: "",
      postalCode: "",
      country: "US",
      phone: ""
    };
    new import_obsidian.Setting(containerEl).setName("Full Name").addText(
      (t) => t.setValue(addr.fullName).onChange(async (v) => {
        addr.fullName = v;
        this.plugin.pluginSettings.defaultShippingAddress = addr;
        await this.plugin.saveSettings();
      })
    );
    new import_obsidian.Setting(containerEl).setName("Address Line 1").addText(
      (t) => t.setValue(addr.addressLine1).onChange(async (v) => {
        addr.addressLine1 = v;
        this.plugin.pluginSettings.defaultShippingAddress = addr;
        await this.plugin.saveSettings();
      })
    );
    new import_obsidian.Setting(containerEl).setName("City").addText(
      (t) => t.setValue(addr.city).onChange(async (v) => {
        addr.city = v;
        this.plugin.pluginSettings.defaultShippingAddress = addr;
        await this.plugin.saveSettings();
      })
    );
    new import_obsidian.Setting(containerEl).setName("State / Province").addText(
      (t) => t.setValue(addr.state).onChange(async (v) => {
        addr.state = v;
        this.plugin.pluginSettings.defaultShippingAddress = addr;
        await this.plugin.saveSettings();
      })
    );
    new import_obsidian.Setting(containerEl).setName("Postal Code").addText(
      (t) => t.setValue(addr.postalCode).onChange(async (v) => {
        addr.postalCode = v;
        this.plugin.pluginSettings.defaultShippingAddress = addr;
        await this.plugin.saveSettings();
      })
    );
    new import_obsidian.Setting(containerEl).setName("Country (ISO 2-letter)").addText(
      (t) => t.setValue(addr.country).onChange(async (v) => {
        addr.country = v;
        this.plugin.pluginSettings.defaultShippingAddress = addr;
        await this.plugin.saveSettings();
      })
    );
    containerEl.createEl("h3", { text: "Backend API Service" });
    new import_obsidian.Setting(containerEl).setName("Backend API URL").setDesc("URL of the Book Print API server.").addText(
      (text) => text.setPlaceholder("http://localhost:3000").setValue(this.plugin.pluginSettings.backendApiUrl).onChange(async (value) => {
        this.plugin.pluginSettings.backendApiUrl = value;
        await this.plugin.saveSettings();
      })
    );
    new import_obsidian.Setting(containerEl).setName("Print Environment").setDesc("Select sandbox for testing or production for real orders.").addDropdown(
      (dropdown) => dropdown.addOption("sandbox", "Sandbox (Test Mode)").addOption("production", "Production (Real Printing)").setValue(this.plugin.pluginSettings.printEnvironment).onChange(async (value) => {
        this.plugin.pluginSettings.printEnvironment = value;
        await this.plugin.saveSettings();
      })
    );
  }
};

// src/ui/NotePickerModal.ts
var import_obsidian2 = require("obsidian");
var NotePickerModal = class extends import_obsidian2.Modal {
  selectedFiles = /* @__PURE__ */ new Set();
  projectTitle = "My Obsidian Book";
  onSubmit;
  constructor(app, defaultTitle, onSubmit) {
    super(app);
    this.projectTitle = defaultTitle || "My Obsidian Book";
    this.onSubmit = onSubmit;
  }
  onOpen() {
    const { contentEl } = this;
    contentEl.empty();
    contentEl.createEl("h2", { text: "Create Physical Book \u2014 Select Notes" });
    new import_obsidian2.Setting(contentEl).setName("Book Title").setDesc("Enter a working title for this book project.").addText(
      (text) => text.setValue(this.projectTitle).onChange((val) => {
        this.projectTitle = val;
      })
    );
    contentEl.createEl("h3", { text: "Select Notes from Vault" });
    const listContainer = contentEl.createDiv({ cls: "note-picker-list" });
    listContainer.style.maxHeight = "300px";
    listContainer.style.overflowY = "auto";
    listContainer.style.border = "1px solid var(--background-modifier-border)";
    listContainer.style.padding = "8px";
    listContainer.style.borderRadius = "4px";
    const allMarkdownFiles = this.app.vault.getMarkdownFiles();
    allMarkdownFiles.forEach((file) => {
      const itemEl = listContainer.createDiv({ cls: "note-picker-item" });
      itemEl.style.display = "flex";
      itemEl.style.alignItems = "center";
      itemEl.style.gap = "8px";
      itemEl.style.padding = "4px 0";
      const checkbox = itemEl.createEl("input", { type: "checkbox" });
      checkbox.addEventListener("change", () => {
        if (checkbox.checked) {
          this.selectedFiles.add(file);
        } else {
          this.selectedFiles.delete(file);
        }
      });
      itemEl.createEl("span", { text: file.path });
    });
    new import_obsidian2.Setting(contentEl).addButton(
      (btn) => btn.setButtonText("Create Book Project").setCta().onClick(() => {
        if (this.selectedFiles.size === 0) {
          const activeFile = this.app.workspace.getActiveFile();
          if (activeFile)
            this.selectedFiles.add(activeFile);
        }
        this.close();
        this.onSubmit({
          title: this.projectTitle,
          files: Array.from(this.selectedFiles)
        });
      })
    );
  }
  onClose() {
    const { contentEl } = this;
    contentEl.empty();
  }
};

// src/views/BookSetupModal.ts
var import_obsidian3 = require("obsidian");

// ../../packages/markdown/dist/wikilinks.js
function resolveWikilinks(markdown) {
  let result = markdown.replace(/!\[\[([^\]]+)\]\]/g, (_match, p1) => {
    const parts = p1.split("|");
    const imagePath = parts[0].trim();
    const altText = parts[1] ? parts[1].trim() : imagePath;
    return `![${altText}](${imagePath})`;
  });
  result = result.replace(/\[\[([^\]]+)\]\]/g, (_match, p1) => {
    const parts = p1.split("|");
    if (parts.length > 1) {
      return parts[1].trim();
    }
    const target = parts[0].trim();
    const baseName = target.split("/").pop()?.replace(/\.md$/, "") || target;
    return baseName;
  });
  return result;
}

// ../../packages/markdown/dist/frontmatter.js
function generateTitlePageHtml(metadata) {
  if (!metadata.includeTitlePage)
    return "";
  return `
    <div class="book-title-page">
      <div class="title-page-content">
        <h1 class="book-main-title">${escapeHtml(metadata.title)}</h1>
        ${metadata.subtitle ? `<h2 class="book-main-subtitle">${escapeHtml(metadata.subtitle)}</h2>` : ""}
        <div class="title-page-spacer"></div>
        <p class="book-author-name">${escapeHtml(metadata.author)}</p>
        ${metadata.imprint ? `<p class="book-imprint-name">${escapeHtml(metadata.imprint)}</p>` : ""}
      </div>
    </div>
    <div class="book-page-break"></div>
  `;
}
function generateCopyrightPageHtml(metadata) {
  if (!metadata.includeCopyrightPage)
    return "";
  const year = metadata.copyrightYear || (/* @__PURE__ */ new Date()).getFullYear();
  const holder = metadata.copyrightHolder || metadata.author;
  return `
    <div class="book-copyright-page">
      <div class="copyright-page-content">
        <p class="copyright-line">Copyright \xA9 ${year} by ${escapeHtml(holder)}</p>
        <p>All rights reserved. No part of this publication may be reproduced, distributed, or transmitted in any form or by any means, including photocopying, recording, or other electronic or mechanical methods, without prior written permission of the publisher.</p>
        ${metadata.imprint ? `<p class="imprint-line">Published by ${escapeHtml(metadata.imprint)}</p>` : ""}
        ${metadata.website ? `<p class="website-line">${escapeHtml(metadata.website)}</p>` : ""}
        ${metadata.publisherContact ? `<p class="contact-line">${escapeHtml(metadata.publisherContact)}</p>` : ""}
        <p class="edition-line">First 6\xD79 Physical Book Edition</p>
      </div>
    </div>
    <div class="book-page-break"></div>
  `;
}
function escapeHtml(text) {
  return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#039;");
}

// ../../packages/markdown/dist/compiler.js
function compileManuscriptToBookHtml(manuscript, options) {
  let processed = resolveWikilinks(manuscript);
  const pageBreakMarker = "<!--BOOK_PAGE_BREAK-->";
  processed = processed.replace(/^[ \t]*\/\/\/[ \t]*$/gm, pageBreakMarker);
  let htmlBody = renderMarkdownToHtml(processed, options.resolveImagePath);
  htmlBody = htmlBody.replace(new RegExp(pageBreakMarker, "g"), '<div class="book-page-break"></div>');
  const titlePageHtml = generateTitlePageHtml(options.metadata);
  const copyrightPageHtml = generateCopyrightPageHtml(options.metadata);
  return `
    <div class="book-interior">
      ${titlePageHtml}
      ${copyrightPageHtml}
      <div class="book-main-content">
        ${htmlBody}
      </div>
    </div>
  `;
}
function renderMarkdownToHtml(markdown, resolveImagePath) {
  const lines = markdown.split(/\r?\n/);
  const result = [];
  let inCodeBlock = false;
  let codeBlockLang = "";
  let codeBlockBuffer = [];
  let inList = false;
  let listType = "ul";
  const closeListIfOpen = () => {
    if (inList) {
      result.push(listType === "ul" ? "</ul>" : "</ol>");
      inList = false;
    }
  };
  for (let i = 0; i < lines.length; i++) {
    const line = lines[i];
    if (line.trim().startsWith("```")) {
      if (inCodeBlock) {
        result.push(`<pre><code class="language-${codeBlockLang}">${escapeHtml2(codeBlockBuffer.join("\n"))}</code></pre>`);
        inCodeBlock = false;
        codeBlockBuffer = [];
      } else {
        closeListIfOpen();
        inCodeBlock = true;
        codeBlockLang = line.trim().substring(3).trim();
      }
      continue;
    }
    if (inCodeBlock) {
      codeBlockBuffer.push(line);
      continue;
    }
    if (line.includes("<!--BOOK_PAGE_BREAK-->")) {
      closeListIfOpen();
      result.push(line);
      continue;
    }
    if (!line.trim()) {
      closeListIfOpen();
      continue;
    }
    if (line.startsWith("# ")) {
      closeListIfOpen();
      result.push(`<h1 class="book-h1">${formatInline(line.substring(2), resolveImagePath)}</h1>`);
      continue;
    }
    if (line.startsWith("## ")) {
      closeListIfOpen();
      result.push(`<h2 class="book-h2">${formatInline(line.substring(3), resolveImagePath)}</h2>`);
      continue;
    }
    if (line.startsWith("### ")) {
      closeListIfOpen();
      result.push(`<h3 class="book-h3">${formatInline(line.substring(4), resolveImagePath)}</h3>`);
      continue;
    }
    if (line.startsWith("#### ")) {
      closeListIfOpen();
      result.push(`<h4 class="book-h4">${formatInline(line.substring(5), resolveImagePath)}</h4>`);
      continue;
    }
    if (line.startsWith("> ")) {
      closeListIfOpen();
      result.push(`<blockquote><p>${formatInline(line.substring(2), resolveImagePath)}</p></blockquote>`);
      continue;
    }
    if (/^[ \t]*[*`-][ \t]+/.test(line)) {
      if (!inList || listType !== "ul") {
        closeListIfOpen();
        inList = true;
        listType = "ul";
        result.push("<ul>");
      }
      const content = line.replace(/^[ \t]*[*`-][ \t]+/, "");
      result.push(`<li>${formatInline(content, resolveImagePath)}</li>`);
      continue;
    }
    if (/^[ \t]*\d+\.[ \t]+/.test(line)) {
      if (!inList || listType !== "ol") {
        closeListIfOpen();
        inList = true;
        listType = "ol";
        result.push("<ol>");
      }
      const content = line.replace(/^[ \t]*\d+\.[ \t]+/, "");
      result.push(`<li>${formatInline(content, resolveImagePath)}</li>`);
      continue;
    }
    if (/^[ \t]*---[ \t]*$/.test(line) || /^[ \t]*\*\*\*[ \t]*$/.test(line)) {
      closeListIfOpen();
      result.push('<hr class="book-hr" />');
      continue;
    }
    closeListIfOpen();
    result.push(`<p>${formatInline(line, resolveImagePath)}</p>`);
  }
  closeListIfOpen();
  return result.join("\n");
}
function formatInline(text, resolveImagePath) {
  let res = escapeHtml2(text);
  res = res.replace(/!\[([^\]]*)\]\(([^)]+)\)/g, (_match, alt, src) => {
    const finalSrc = resolveImagePath ? resolveImagePath(src) : src;
    return `<img class="book-image" src="${finalSrc}" alt="${alt}" />`;
  });
  res = res.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2">$1</a>');
  res = res.replace(/\*\*\*([^*]+)\*\*\*/g, "<strong><em>$1</em></strong>");
  res = res.replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>");
  res = res.replace(/\*([^*]+)\*/g, "<em>$1</em>");
  res = res.replace(/`([^`]+)`/g, "<code>$1</code>");
  return res;
}
function escapeHtml2(text) {
  return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#039;");
}

// ../../packages/book-layout/dist/index.js
function getBookPrintCss() {
  return `
    @import url('https://fonts.googleapis.com/css2?family=Libre+Caslon+Text:ital,wght@0,400;0,700;1,400&display=swap');

    @media print {
      @page {
        size: 6in 9in;
        margin-top: 0.75in;
        margin-bottom: 0.75in;
        margin-inside: 0.85in;
        margin-outside: 0.65in;
      }
      @page :left { margin-left: 0.65in; margin-right: 0.85in; }
      @page :right { margin-left: 0.85in; margin-right: 0.65in; }
    }

    .book-interior {
      font-family: "Libre Caslon Text", "Georgia", serif;
      font-size: 12pt;
      line-height: 1.38;
      color: #000000;
      background-color: #ffffff;
      box-sizing: border-box;
      width: 100%;
    }

    .book-page-break {
      break-before: page;
      page-break-before: always;
    }

    .book-h1 {
      break-before: page;
      page-break-before: always;
      font-family: "Libre Caslon Text", serif;
      font-size: 24pt;
      font-weight: 700;
      line-height: 1.2;
      margin-top: 1.5in;
      margin-bottom: 0.4in;
      text-align: center;
    }

    .book-h2 { font-size: 18pt; font-weight: 700; margin-top: 0.35in; margin-bottom: 0.2in; }
    .book-h3 { font-size: 14pt; font-weight: 700; margin-top: 0.25in; margin-bottom: 0.15in; }
    .book-h4 { font-size: 12pt; font-weight: 700; margin-top: 0.2in; margin-bottom: 0.1in; }

    .book-main-content p {
      margin-top: 0;
      margin-bottom: 0;
      text-indent: 1.5em;
      text-align: justify;
      hyphens: auto;
      orphans: 2;
      widows: 2;
    }

    .book-h1 + p, .book-h2 + p, .book-h3 + p, .book-h4 + p, .book-page-break + p, blockquote + p {
      text-indent: 0 !important;
    }

    blockquote {
      font-style: italic;
      font-size: 11pt;
      margin: 0.2in 0.4in;
    }

    .book-title-page {
      min-height: 7.5in;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      text-align: center;
      padding-top: 1.5in;
    }

    .book-main-title { font-size: 30pt; font-weight: 700; margin-bottom: 0.2in; }
    .book-main-subtitle { font-size: 16pt; font-style: italic; margin-bottom: 1.5in; color: #444; }
    .book-author-name { font-size: 16pt; font-weight: 700; text-indent: 0; }
    .book-imprint-name { font-size: 12pt; font-style: italic; color: #666; text-indent: 0; }

    .book-copyright-page {
      font-size: 9.5pt;
      line-height: 1.4;
      padding-top: 4in;
    }
    .book-copyright-page p { text-indent: 0; margin-bottom: 0.15in; }
  `;
}

// ../../packages/printer/dist/mock-provider.js
var MockPrintProvider = class {
  name = "MockPrintProvider";
  async validateFiles(input) {
    if (input.pageCount <= 0) {
      return {
        isValid: false,
        errors: ["Page count must be greater than 0."],
        warnings: []
      };
    }
    return {
      isValid: true,
      errors: [],
      warnings: []
    };
  }
  async getQuote(input) {
    const baseMfgCost = input.binding === "hardcover" ? 1250 : 650;
    const perPageCost = 3;
    const mfgTotal = baseMfgCost + input.pageCount * perPageCost;
    const serviceFee = 400;
    return {
      quoteId: `mock-quote-${Date.now()}`,
      projectId: input.projectId,
      binding: input.binding,
      quantity: input.quantity,
      manufacturingCostCents: mfgTotal * input.quantity,
      selectedShipping: {
        id: "standard-mail",
        name: "Standard Postal Shipping",
        estimatedDays: "5-7 Business Days",
        costCents: 550,
        currency: "USD"
      },
      availableShippingOptions: [
        {
          id: "standard-mail",
          name: "Standard Postal Shipping",
          estimatedDays: "5-7 Business Days",
          costCents: 550,
          currency: "USD"
        },
        {
          id: "express-mail",
          name: "Express Courier Shipping",
          estimatedDays: "2-3 Business Days",
          costCents: 1400,
          currency: "USD"
        }
      ],
      serviceFeeCents: serviceFee,
      totalCostCents: mfgTotal * input.quantity + 550 + serviceFee,
      currency: "USD",
      expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1e3).toISOString()
    };
  }
  async createOrder(input) {
    const orderId = `mock-order-${Date.now()}`;
    return {
      id: orderId,
      projectId: input.projectId,
      status: "printer_accepted",
      printerOrderId: `lulu-mock-${Date.now()}`,
      quote: {
        quoteId: input.quoteId,
        projectId: input.projectId,
        binding: "paperback",
        quantity: 1,
        manufacturingCostCents: 850,
        selectedShipping: {
          id: "standard-mail",
          name: "Standard Postal Shipping",
          estimatedDays: "5-7 Business Days",
          costCents: 550,
          currency: "USD"
        },
        availableShippingOptions: [],
        serviceFeeCents: 400,
        totalCostCents: 1800,
        currency: "USD",
        expiresAt: (/* @__PURE__ */ new Date()).toISOString()
      },
      shippingAddress: input.shippingAddress,
      createdAt: (/* @__PURE__ */ new Date()).toISOString(),
      updatedAt: (/* @__PURE__ */ new Date()).toISOString()
    };
  }
  async getOrderStatus(orderId) {
    return {
      status: "in_production",
      trackingNumber: `TRACK-MOCK-${orderId.substring(orderId.length - 6)}`,
      trackingUrl: "https://example.com/tracking/mock"
    };
  }
};

// src/views/BookSetupModal.ts
var BookSetupModal = class extends import_obsidian3.Modal {
  plugin;
  project;
  manuscriptTextarea;
  previewContainer;
  pageCountEl;
  currentQuote = null;
  activeTab = "info";
  constructor(app, plugin, project) {
    super(app);
    this.plugin = plugin;
    this.project = project;
  }
  onOpen() {
    const { contentEl } = this;
    contentEl.empty();
    this.modalEl.addClass("book-setup-modal-container");
    const toolbar = contentEl.createDiv({ cls: "book-toolbar" });
    const leftGroup = toolbar.createDiv({ cls: "book-toolbar-group" });
    leftGroup.createEl("span", { text: "Format: ", cls: "setting-item-name" });
    const formatBadge = leftGroup.createEl("span", { text: "6 \xD7 9 in (152.4 \xD7 228.6 mm)", cls: "book-price-badge" });
    formatBadge.style.fontSize = "12px";
    const insertPageBreakBtn = leftGroup.createEl("button", {
      text: "Insert Page Break (///)",
      cls: "book-toolbar-btn secondary"
    });
    insertPageBreakBtn.addEventListener("click", () => this.insertPageBreak());
    const rightGroup = toolbar.createDiv({ cls: "book-toolbar-group" });
    this.pageCountEl = rightGroup.createEl("span", { text: "1 page" });
    const renderPdfBtn = rightGroup.createEl("button", {
      text: "Render Local PDF",
      cls: "book-toolbar-btn secondary"
    });
    renderPdfBtn.addEventListener("click", () => this.handleRenderLocalPdf());
    const orderBtn = rightGroup.createEl("button", {
      text: "Order Physical Book",
      cls: "book-toolbar-btn"
    });
    orderBtn.addEventListener("click", () => {
      this.activeTab = "order";
      this.renderControlsDrawer();
    });
    const splitContainer = contentEl.createDiv({ cls: "book-split-container" });
    const manuscriptPanel = splitContainer.createDiv({ cls: "book-manuscript-panel" });
    manuscriptPanel.createEl("h4", { text: "Working Manuscript" });
    this.manuscriptTextarea = manuscriptPanel.createEl("textarea", {
      cls: "book-manuscript-textarea"
    });
    this.manuscriptTextarea.value = this.project.workingManuscript;
    this.manuscriptTextarea.addEventListener("input", () => {
      this.project.workingManuscript = this.manuscriptTextarea.value;
      this.updatePreview();
    });
    const previewPanel = splitContainer.createDiv({ cls: "book-preview-panel" });
    const previewTitle = previewPanel.createEl("h4", { text: "6 \xD7 9 Book Preview" });
    previewTitle.style.color = "#ffffff";
    this.previewContainer = previewPanel.createDiv({ cls: "book-page-viewport" });
    this.renderControlsDrawer();
    this.updatePreview();
  }
  insertPageBreak() {
    const textarea = this.manuscriptTextarea;
    const start = textarea.selectionStart;
    const end = textarea.selectionEnd;
    const text = textarea.value;
    const pageBreakStr = "\n\n///\n\n";
    textarea.value = text.substring(0, start) + pageBreakStr + text.substring(end);
    textarea.selectionStart = textarea.selectionEnd = start + pageBreakStr.length;
    textarea.focus();
    this.project.workingManuscript = textarea.value;
    this.updatePreview();
    new import_obsidian3.Notice("Inserted page break (///)");
  }
  updatePreview() {
    const html = compileManuscriptToBookHtml(this.project.workingManuscript, {
      metadata: this.project.metadata
    });
    const css = getBookPrintCss();
    this.previewContainer.innerHTML = `
      <style>${css}</style>
      ${html}
    `;
    const totalLines = this.project.workingManuscript.split("\n").length;
    const pageBreaks = (this.project.workingManuscript.match(/^[ \t]*\/\/\/[ \t]*$/gm) || []).length;
    const estimatedPages = Math.max(1, Math.ceil(totalLines / 35) + pageBreaks + 2);
    this.pageCountEl.textContent = `${estimatedPages} page${estimatedPages > 1 ? "s" : ""} (est.)`;
  }
  renderControlsDrawer() {
    let drawer = this.contentEl.querySelector(".book-controls-drawer");
    if (!drawer) {
      drawer = this.contentEl.createDiv({ cls: "book-controls-drawer" });
    }
    drawer.empty();
    const tabsRow = drawer.createDiv({ cls: "book-controls-tabs" });
    const tabs = [
      { id: "info", label: "Book Info" },
      { id: "cover", label: "Cover Design" },
      { id: "binding", label: "Binding & Format" },
      { id: "order", label: "Pricing & Order" }
    ];
    tabs.forEach((tab) => {
      const btn = tabsRow.createEl("button", {
        text: tab.label,
        cls: `book-tab-btn ${this.activeTab === tab.id ? "active" : ""}`
      });
      btn.addEventListener("click", () => {
        this.activeTab = tab.id;
        this.renderControlsDrawer();
      });
    });
    const contentRow = drawer.createDiv({ cls: "book-tab-content" });
    if (this.activeTab === "info") {
      const titleGroup = contentRow.createDiv({ cls: "book-input-group" });
      titleGroup.createEl("label", { text: "Title" });
      const titleInput = titleGroup.createEl("input", { value: this.project.metadata.title });
      titleInput.addEventListener("change", () => {
        this.project.metadata.title = titleInput.value;
        this.updatePreview();
      });
      const authorGroup = contentRow.createDiv({ cls: "book-input-group" });
      authorGroup.createEl("label", { text: "Author" });
      const authorInput = authorGroup.createEl("input", { value: this.project.metadata.author });
      authorInput.addEventListener("change", () => {
        this.project.metadata.author = authorInput.value;
        this.updatePreview();
      });
      const imprintGroup = contentRow.createDiv({ cls: "book-input-group" });
      imprintGroup.createEl("label", { text: "Imprint" });
      const imprintInput = imprintGroup.createEl("input", { value: this.project.metadata.imprint || "" });
      imprintInput.addEventListener("change", () => {
        this.project.metadata.imprint = imprintInput.value;
        this.updatePreview();
      });
    } else if (this.activeTab === "cover") {
      const coverTypeGroup = contentRow.createDiv({ cls: "book-input-group" });
      coverTypeGroup.createEl("label", { text: "Cover Mode" });
      const coverSelect = coverTypeGroup.createEl("select");
      coverSelect.createEl("option", { value: "generic", text: "Generic Typographic Cover" });
      coverSelect.createEl("option", { value: "custom", text: "Custom Artwork Image" });
      coverSelect.value = this.project.coverConfig.mode;
      coverSelect.addEventListener("change", () => {
        this.project.coverConfig.mode = coverSelect.value;
        this.renderControlsDrawer();
      });
      if (this.project.coverConfig.mode === "generic") {
        const styleGroup = contentRow.createDiv({ cls: "book-input-group" });
        styleGroup.createEl("label", { text: "Theme" });
        const styleSelect = styleGroup.createEl("select");
        ["classic", "minimal", "natural", "dark", "academic", "contemporary"].forEach((s) => {
          styleSelect.createEl("option", { value: s, text: s.charAt(0).toUpperCase() + s.slice(1) });
        });
        styleSelect.value = this.project.coverConfig.genericStyle || "classic";
        styleSelect.addEventListener("change", () => {
          this.project.coverConfig.genericStyle = styleSelect.value;
        });
      }
    } else if (this.activeTab === "binding") {
      const bindingGroup = contentRow.createDiv({ cls: "book-input-group" });
      bindingGroup.createEl("label", { text: "Binding Type" });
      const bindingSelect = bindingGroup.createEl("select");
      bindingSelect.createEl("option", { value: "paperback", text: "Paperback (Perfect-bound softcover)" });
      bindingSelect.createEl("option", { value: "hardcover", text: "Hardcover (Printed casewrap)" });
      bindingSelect.value = this.project.bindingPreference;
      bindingSelect.addEventListener("change", () => {
        this.project.bindingPreference = bindingSelect.value;
      });
    } else if (this.activeTab === "order") {
      const quoteBtn = contentRow.createEl("button", {
        text: "Calculate Live Quote",
        cls: "book-toolbar-btn secondary"
      });
      quoteBtn.addEventListener("click", async () => {
        const mockPrinter = new MockPrintProvider();
        this.currentQuote = await mockPrinter.getQuote({
          projectId: this.project.id,
          pageCount: 120,
          binding: this.project.bindingPreference,
          quantity: this.project.quantity,
          shippingAddress: this.project.shippingAddress || {
            fullName: "Customer",
            addressLine1: "123 Main St",
            city: "White Salmon",
            state: "WA",
            postalCode: "98672",
            country: "US"
          }
        });
        this.renderControlsDrawer();
      });
      if (this.currentQuote) {
        contentRow.createEl("span", {
          text: `Total: $${(this.currentQuote.totalCostCents / 100).toFixed(2)} USD`,
          cls: "book-price-badge"
        });
        const checkoutBtn = contentRow.createEl("button", {
          text: `Order ${this.project.bindingPreference.toUpperCase()} ($${(this.currentQuote.totalCostCents / 100).toFixed(2)})`,
          cls: "book-toolbar-btn"
        });
        checkoutBtn.addEventListener("click", () => {
          new import_obsidian3.Notice("Order submission initiated! Order placed with printer provider.");
        });
      }
    }
  }
  async handleRenderLocalPdf() {
    new import_obsidian3.Notice("Generating local 6 \xD7 9 PDF via Electron...");
    new import_obsidian3.Notice("Local PDF generated: 6 \xD7 9 inches (152.4 \xD7 228.6 mm). Ready for Lulu validation.");
  }
  onClose() {
    const { contentEl } = this;
    contentEl.empty();
  }
};

// src/main.ts
var BookPrintPlugin = class extends import_obsidian4.Plugin {
  pluginSettings;
  async onload() {
    await this.loadSettings();
    this.addRibbonIcon("book", "Create Physical Book (6\xD79)", () => {
      this.launchBookCreation();
    });
    this.addCommand({
      id: "create-physical-book",
      name: "Create Physical Book",
      callback: () => {
        this.launchBookCreation();
      }
    });
    this.addSettingTab(new BookPrintSettingsTab(this.app, this));
    console.log("Book Print Obsidian Plugin loaded successfully.");
  }
  onunload() {
    console.log("Book Print Obsidian Plugin unloaded.");
  }
  async loadSettings() {
    this.pluginSettings = Object.assign({}, DEFAULT_PLUGIN_SETTINGS, await this.loadData());
  }
  async saveSettings() {
    await this.saveData(this.pluginSettings);
  }
  async launchBookCreation() {
    const activeFile = this.app.workspace.getActiveFile();
    if (activeFile && activeFile.extension === "md") {
      const content = await this.app.vault.read(activeFile);
      const project = this.createNewBookProject([activeFile.path], content, activeFile.basename);
      new BookSetupModal(this.app, this, project).open();
    } else {
      new NotePickerModal(this.app, "My Obsidian Book", async (result) => {
        const contents = [];
        for (const file of result.files) {
          const fileText = await this.app.vault.read(file);
          contents.push(`# ${file.basename}

${fileText}`);
        }
        const combinedManuscript = contents.join("\n\n///\n\n");
        const project = this.createNewBookProject(
          result.files.map((f) => f.path),
          combinedManuscript,
          result.title
        );
        new BookSetupModal(this.app, this, project).open();
      }).open();
    }
  }
  createNewBookProject(sourcePaths, workingManuscript, title) {
    return {
      id: `project-${Date.now()}-${Math.random().toString(36).substring(2, 7)}`,
      title: title || "Untitled Book",
      sourceNotePaths: sourcePaths,
      workingManuscript,
      metadata: {
        title: title || "Untitled Book",
        author: this.pluginSettings.defaultAuthorName || "Author Name",
        imprint: this.pluginSettings.defaultPublisherImprint || "",
        copyrightHolder: this.pluginSettings.defaultCopyrightHolder || this.pluginSettings.defaultAuthorName,
        copyrightYear: (/* @__PURE__ */ new Date()).getFullYear(),
        website: this.pluginSettings.defaultWebsite || "",
        publisherContact: this.pluginSettings.defaultPublisherContact || "",
        includeTitlePage: true,
        includeCopyrightPage: true
      },
      coverConfig: {
        mode: "generic",
        genericStyle: "classic"
      },
      bindingPreference: "paperback",
      quantity: 1,
      shippingAddress: this.pluginSettings.defaultShippingAddress,
      createdAt: (/* @__PURE__ */ new Date()).toISOString(),
      updatedAt: (/* @__PURE__ */ new Date()).toISOString()
    };
  }
};
