// Code Custodian File ID: D266631D-B42F-42EA-A685-494CAD3C678F // // ContentView.swift // The Groovy Panda // // Created by David Higgins on 3/26/26. // import SwiftUI import SwiftData import WarehouseKit import StreamlineFoundation import AppKit import UniformTypeIdentifiers import WebKit struct HTMLPreviewWebView: NSViewRepresentable { let htmlFragment: String func makeNSView(context: Context) -> WKWebView { let webView = WKWebView() webView.setValue(false, forKey: "drawsBackground") webView.wantsLayer = true webView.layer?.backgroundColor = NSColor.clear.cgColor return webView } func updateNSView(_ nsView: WKWebView, context: Context) { let shell = """ \(htmlFragment) """ nsView.loadHTMLString(shell, baseURL: nil) } } enum NavigationSection: String, Hashable { case products case templates case artworks case blanks case taxonomy case globalGroups case personas case contentBlocks } // MARK: - Distributed Notification Coordinator /// A singleton NSObject-based coordinator that bridges distributed notifications into SwiftUI. /// Uses FactoryKit's `NotificationCenter.addDistributedObserver` to register observers exactly once. @MainActor final class DistributedNotificationCoordinator: NSObject { static let shared = DistributedNotificationCoordinator() private var isRegistered = false // MainActor-isolated callback closures for each notification channel var onDataUpdated: (@MainActor () -> Void)? var onGroovyStudioResponse: (@MainActor (String) -> Void)? var onSelectProduct: (@MainActor (String) -> Void)? private override init() { super.init() } /// Registers the distributed notification observers exactly once. func registerIfNeeded() { guard !isRegistered else { return } isRegistered = true // Channel 1: com.factory.data.updated NotificationCenter.addDistributedObserver(forName: Notification.Name("com.factory.data.updated"), object: nil, queue: .main) { [weak self] _ in Task { @MainActor in self?.onDataUpdated?() } } // Channel 2: com.factory.groovystudio.response NotificationCenter.addDistributedObserver(forName: Notification.Name("com.factory.groovystudio.response"), object: nil, queue: .main) { [weak self] notification in guard let requestId = notification.userInfo?["request_id"] as? String else { return } Task { @MainActor in self?.onGroovyStudioResponse?(requestId) } } // Channel 3: com.factory.groovypanda.select_product NotificationCenter.addDistributedObserver(forName: Notification.Name("com.factory.groovypanda.select_product"), object: nil, queue: .main) { [weak self] notification in let userInfo = notification.userInfo ?? [:] let productIdString = (userInfo["product_id"] as? String) ?? (userInfo["request_id"] as? String) guard let productIdString else { return } Task { @MainActor in self?.onSelectProduct?(productIdString) } } } // Nonisolated Objective-C selector handlers that extract Sendable payloads @objc nonisolated func handleDataUpdated(_ notification: Notification) { Task { @MainActor [weak self] in self?.onDataUpdated?() } } @objc nonisolated func handleGroovyStudioResponse(_ notification: Notification) { let requestId = (notification.userInfo?["request_id"] as? String) ?? "" guard !requestId.isEmpty else { return } Task { @MainActor [weak self] in self?.onGroovyStudioResponse?(requestId) } } @objc nonisolated func handleSelectProduct(_ notification: Notification) { let userInfo = notification.userInfo ?? [:] let productIdString = (userInfo["product_id"] as? String) ?? (userInfo["request_id"] as? String) ?? "" guard !productIdString.isEmpty else { return } Task { @MainActor [weak self] in self?.onSelectProduct?(productIdString) } } } struct ContentView: View { private let lastSelectedCategoryPreferenceKey = "last_selected_category" private let lastSelectedSectionPreferenceKey = "last_selected_section" private let lastSelectedProductPreferenceKey = "last_selected_product" private let lastSelectedTemplatePreferenceKey = "last_selected_template" private let lastSelectedArtworkPreferenceKey = "last_selected_artwork" private let lastSelectedBlankPreferenceKey = "last_selected_blank" private let lastSelectedGroupPreferenceKey = "last_selected_group" private let lastSelectedContentBlockPreferenceKey = "last_selected_content_block" @Environment(\.modelContext) private var modelContext @Environment(\.undoManager) private var undoManager @Environment(\.openSettings) private var openSettings @Environment(\.openWindow) private var openWindow @Query private var products: [ApparelProduct] @Query private var artworks: [Artwork] @Query private var blanks: [BlankMedia] @Query private var categories: [Category] @Query private var attributeGroups: [AttributeGroup] @Query private var templates: [ProductTemplate] @Query(sort: \AIPersona.title) private var personas: [AIPersona] @Query private var contentBlocks: [StoreContentBlock] @State private var selectedSection: NavigationSection? = .products @State private var selectedProduct: ApparelProduct? @State private var selectedTemplate: ProductTemplate? @State private var selectedCategory: Category? @State private var selectedGroup: AttributeGroup? @State private var selectedPersona: AIPersona? @State private var selectedContentBlock: StoreContentBlock? @State private var productCategoryFilter: Category? @State private var taxonomyRefreshTrigger = 0 @State private var selectedArtwork: Artwork? @State private var selectedBlank: BlankMedia? @State private var showOrphansOnly = false @State private var productSearchText = "" @State private var showingQuickStart = false @State private var showingNewProductWizard = false @State private var wizardSelectedCategory: Category? @State private var wizardIsOneOfOne = true @State private var shouldOpenTaxonomyWizardAfterQuickStart = false @State private var productHistory: [ApparelProduct] = [] @State private var historyIndex: Int = -1 @State private var isNavigatingHistory: Bool = false // staging sheet state removed var body: some View { NavigationSplitView { List(selection: $selectedSection) { NavigationLink("Products", value: NavigationSection.products) NavigationLink("Templates", value: NavigationSection.templates) NavigationLink("Artworks", value: NavigationSection.artworks) NavigationLink("Blank Media", value: NavigationSection.blanks) NavigationLink("Taxonomy & Rules", value: NavigationSection.taxonomy) NavigationLink("Global Groups", value: NavigationSection.globalGroups) NavigationLink("AI Personas & Prompts", value: NavigationSection.personas) NavigationLink("Content Blocks", value: NavigationSection.contentBlocks) } .navigationTitle("Inventory") } content: { Group { switch selectedSection { case .products: VStack(spacing: 0) { if let productCategoryFilter { HStack { Text("Filtering by: \(productCategoryFilter.name)") .foregroundStyle(.secondary) Spacer() Button("Clear Filter", systemImage: "xmark.circle.fill") { self.productCategoryFilter = nil } .labelStyle(.iconOnly) } .padding() } List(selection: selectedProductBinding) { ForEach(filteredProducts) { product in VStack(alignment: .leading) { Text(product.name) .bold() Text(product.sku) } .tag(product) } .onDelete(perform: deleteProducts) } } .searchable(text: $productSearchText, prompt: "Search Name or SKU") .navigationTitle("Products") case .templates: VStack(spacing: 0) { HStack { Text("Templates") .font(.headline) Spacer() Button("New Template", systemImage: "plus") { createNewTemplate() } .labelStyle(.iconOnly) .help("Create new template") } .padding() List(selection: $selectedTemplate) { ForEach(sortedTemplates) { template in VStack(alignment: .leading, spacing: 4) { Text(template.name) .bold() if let category = template.category { Text(category.fullPath) .font(.caption) .foregroundStyle(.secondary) } else { Text("Uncategorized") .font(.caption) .foregroundStyle(.secondary) } } .tag(template) } .onDelete(perform: deleteTemplates) } } .navigationTitle("Templates") case .artworks: List(selection: $selectedArtwork) { ForEach(artworks) { artwork in VStack(alignment: .leading) { Text(artwork.name) .bold() Text(artwork.sku) } .tag(artwork) } .onDelete(perform: deleteArtworks) } .navigationTitle("Artworks") case .blanks: List(selection: $selectedBlank) { ForEach(blanks) { blank in VStack(alignment: .leading) { Text(blank.name) .bold() Text(blank.sku) } .tag(blank) } .onDelete(perform: deleteBlanks) } .navigationTitle("Blank Media") case .taxonomy: EmptyView() case .personas: VStack(spacing: 0) { HStack { Text("AI Personas") .font(.headline) Spacer() Button("New Persona", systemImage: "plus") { selectedPersona = nil } .labelStyle(.iconOnly) .help("Create new AI persona") } .padding() List(selection: $selectedPersona) { ForEach(personas) { persona in HStack { VStack(alignment: .leading, spacing: 4) { HStack { Text(persona.title) .font(.body) .bold() if persona.isDefault { Text("Default") .font(.caption2) .fontWeight(.bold) .padding(.horizontal, 6) .padding(.vertical, 2) .background(Color.blue) .foregroundStyle(.white) .clipShape(Capsule()) } } Text(persona.promptText) .font(.caption) .lineLimit(2) .foregroundStyle(.secondary) } Spacer() } .padding(.vertical, 4) .tag(persona) } } } .navigationTitle("AI Personas") case .globalGroups: VStack(spacing: 0) { HStack { Text("Global Groups") .font(.headline) Spacer() Button("New Group", systemImage: "plus") { createBlankAttributeGroup() } .labelStyle(.iconOnly) } .padding() List { ForEach(sortedAttributeGroups) { group in Button { selectedGroup = group } label: { Text(group.name) .frame(maxWidth: .infinity, alignment: .leading) .padding(.vertical, 6) .contentShape(Rectangle()) } .buttonStyle(.plain) .background( selectedGroup == group ? Color.accentColor.opacity(0.2) : Color.clear ) } } } .navigationTitle("Global Groups") case .contentBlocks: GroupedContentBlocksListView( contentBlocks: contentBlocks, selectedContentBlock: $selectedContentBlock, onCreateBlock: createNewContentBlock, onDeleteBlock: deleteContentBlock ) case nil: Text("Select a section") .foregroundStyle(.secondary) } } .navigationSplitViewColumnWidth(min: 200, ideal: 250) } detail: { switch selectedSection { case .products: if let selectedProduct { ProductDetailView( product: selectedProduct, onDuplicateProduct: { duplicateCurrentProduct(from: selectedProduct) }, onDeleteProduct: { deleteSelectedProduct(selectedProduct) }, onJumpToCategory: jumpToCategory, onJumpToGroup: jumpToGroup, onCategoryChanged: { taxonomyRefreshTrigger += 1 } ) } else { Text("Select a product") .foregroundStyle(.secondary) } case .templates: if let selectedTemplate { TemplateDetailView( template: selectedTemplate, onCreateProduct: { template, selectedSize in createProduct(from: template, selectedSize: selectedSize) }, onDeleteTemplate: { deleteTemplate(selectedTemplate) self.selectedTemplate = nil }, onJumpToGroup: jumpToGroup ) } else { Text("Select a template") .foregroundStyle(.secondary) } case .artworks: if let selectedArtwork { ArtworkDetailView(artwork: selectedArtwork) } else { Text("Select an artwork") .foregroundStyle(.secondary) } case .blanks: if let selectedBlank { BlankMediaDetailView(blank: selectedBlank) } else { Text("Select blank media") .foregroundStyle(.secondary) } case .taxonomy: TaxonomyDashboardView( selectedCategory: $selectedCategory, refreshTrigger: $taxonomyRefreshTrigger, jumpToGroup: jumpToGroup, jumpToProducts: jumpToProducts ) case .globalGroups: GlobalGroupsDashboardView( selectedGroup: $selectedGroup, jumpToCategory: jumpToCategory ) case .personas: AIPersonasDashboardView(selectedPersona: $selectedPersona) case .contentBlocks: if let selectedContentBlock { ContentBlockStudioDetailView( block: selectedContentBlock, allBlocks: contentBlocks, onDelete: { deleteContentBlock(selectedContentBlock) } ) } else { ContentBlockEmptyStateView() } case nil: Text("Select a section") .foregroundStyle(.secondary) } } .toolbar { ToolbarItemGroup(placement: .navigation) { Menu { ForEach(Array((0..= productHistory.count - 1) .id("forward-\(productHistory.count)-\(historyIndex)") } ToolbarItem { Button(action: addItemForSelectedSection) { Label("Add Item", systemImage: "plus") } .labelStyle(.titleAndIcon) .help("Add a new product or template") .disabled(selectedSection == nil) } if selectedSection == .products { ToolbarItem { Toggle("Show Orphans", isOn: $showOrphansOnly) } ToolbarItem { Button { Task { @MainActor in SchemaExporter.copySchemaToClipboard() } } label: { Label("Copy Schema Graph", systemImage: "doc.on.doc") } .labelStyle(.titleAndIcon) .help("Copy relational schema graph JSON to the clipboard") } ToolbarItem { Button(action: { JSONExporter.publishProducts(context: modelContext) }) { Label("Publish to Web", systemImage: "paperplane.fill") } .labelStyle(.titleAndIcon) .help("Export products.json to Willie") } } ToolbarItem { Button(action: { openSettings() }) { Label("Settings", systemImage: "gearshape.fill") } .labelStyle(.titleAndIcon) .help("App Settings & API Keys") } } .sheet(isPresented: $showingQuickStart, onDismiss: handleQuickStartDismiss) { QuickStartChooserView( templates: templates, onChooseTemplate: { template, selectedSize in createProduct(from: template, selectedSize: selectedSize) }, onDeleteTemplate: deleteTemplate, onChooseCustomProduct: openTaxonomyWizardFromQuickStart ) } .sheet(isPresented: $showingNewProductWizard) { NewProductWizardView( rootCategories: rootCategories, selectedCategory: $wizardSelectedCategory, isOneOfOne: $wizardIsOneOfOne, onCancel: resetNewProductWizard, onCreate: createProductFromWizard ) } .onAppear { // Configure the distributed notification coordinator with current callbacks let coordinator = DistributedNotificationCoordinator.shared coordinator.registerIfNeeded() coordinator.onDataUpdated = { JSONExporter.importStoreInfo(context: modelContext) NotificationCenter.default.post(name: Notification.Name("local.com.factory.data.updated"), object: nil) } coordinator.onGroovyStudioResponse = { requestId in Task { do { let base = GroovyStudioBridge.baseDirectoryURL() let responseURL = base.appending(path: "responses/RESP_\(requestId).json") let data = try Data(contentsOf: responseURL) let response = try JSONDecoder().decode(GroovyStudioResponse.self, from: data) let productId = response.productId guard let productUUID = UUID(uuidString: productId) else { return } openWindow(id: "groovyStudioReview", value: productUUID) } catch { print("❌ [ContentView] Failed to stage Groovy Studio response: \(error)") } } } coordinator.onSelectProduct = { productIdString in guard let productUUID = UUID(uuidString: productIdString) else { return } Task { let descriptor = FetchDescriptor( predicate: #Predicate { product in product.id == productUUID } ) if let product = try? modelContext.fetch(descriptor).first { selectedSection = .products productCategoryFilter = nil productSearchText = "" selectedProduct = product NSApp.activate(ignoringOtherApps: true) } } } JSONExporter.importStoreInfo(context: modelContext) restoreSelectedSectionIfNeeded() restoreSelectedProductIfNeeded() restoreSelectedTemplateIfNeeded() restoreSelectedCategoryIfNeeded() restoreSelectedArtworkIfNeeded() restoreSelectedBlankIfNeeded() restoreSelectedGroupIfNeeded() restoreSelectedContentBlockIfNeeded() } .onReceive(NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification)) { _ in JSONExporter.importStoreInfo(context: modelContext) } .onChange(of: undoManager, initial: true) { _, newManager in modelContext.undoManager = newManager } .onChange(of: selectedProduct, initial: false) { _, newProduct in if isNavigatingHistory { isNavigatingHistory = false return } if let newProduct { PreferencesManager.shared.set(newProduct.id.uuidString, for: lastSelectedProductPreferenceKey) } else { PreferencesManager.shared.remove(for: lastSelectedProductPreferenceKey) } if let newProduct, historyIndex < 0 || productHistory[historyIndex].id != newProduct.id { if historyIndex < productHistory.count - 1 { productHistory.removeSubrange((historyIndex + 1)...) } productHistory.append(newProduct) historyIndex = productHistory.count - 1 } try? modelContext.save() } .onChange(of: selectedTemplate, initial: false) { _, newTemplate in if let newTemplate { PreferencesManager.shared.set(newTemplate.id.uuidString, for: lastSelectedTemplatePreferenceKey) } else { PreferencesManager.shared.remove(for: lastSelectedTemplatePreferenceKey) } try? modelContext.save() } .onChange(of: selectedCategory, initial: false) { _, newCategory in if let newCategory { PreferencesManager.shared.set(newCategory.id.uuidString, for: lastSelectedCategoryPreferenceKey) } else { PreferencesManager.shared.remove(for: lastSelectedCategoryPreferenceKey) } try? modelContext.save() } .onChange(of: selectedArtwork, initial: false) { _, newArtwork in if let newArtwork { PreferencesManager.shared.set(newArtwork.id.uuidString, for: lastSelectedArtworkPreferenceKey) } else { PreferencesManager.shared.remove(for: lastSelectedArtworkPreferenceKey) } try? modelContext.save() } .onChange(of: selectedBlank, initial: false) { _, newBlank in if let newBlank { PreferencesManager.shared.set(newBlank.id.uuidString, for: lastSelectedBlankPreferenceKey) } else { PreferencesManager.shared.remove(for: lastSelectedBlankPreferenceKey) } try? modelContext.save() } .onChange(of: selectedGroup, initial: false) { _, newGroup in if let newGroup { PreferencesManager.shared.set(newGroup.id.uuidString, for: lastSelectedGroupPreferenceKey) } else { PreferencesManager.shared.remove(for: lastSelectedGroupPreferenceKey) } try? modelContext.save() } .onChange(of: selectedContentBlock, initial: false) { _, newBlock in if let newBlock { PreferencesManager.shared.set(newBlock.id.uuidString, for: lastSelectedContentBlockPreferenceKey) } else { PreferencesManager.shared.remove(for: lastSelectedContentBlockPreferenceKey) } try? modelContext.save() } .onChange(of: selectedSection, initial: false) { _, newSection in if let newSection { PreferencesManager.shared.set(newSection.rawValue, for: lastSelectedSectionPreferenceKey) } else { PreferencesManager.shared.remove(for: lastSelectedSectionPreferenceKey) } try? modelContext.save() } } private var filteredProducts: [ApparelProduct] { let orphanFilteredProducts = if showOrphansOnly { products.filter { $0.categories?.isEmpty ?? true } } else { products } let categoryFilteredProducts = if let productCategoryFilter { orphanFilteredProducts.filter { product in (product.categories ?? []).contains { category in category.id == productCategoryFilter.id || category.isDescendant(of: productCategoryFilter) } } } else { orphanFilteredProducts } guard !productSearchText.isEmpty else { return categoryFilteredProducts } return categoryFilteredProducts.filter { product in product.name.localizedStandardContains(productSearchText) || product.sku.localizedStandardContains(productSearchText) } } private var selectedProductBinding: Binding { Binding( get: { selectedProduct }, set: { newSelection in guard let newSelection else { return } selectedProduct = newSelection } ) } private var rootCategories: [Category] { categories .filter { $0.parentCategory == nil } .sorted { $0.name.localizedStandardCompare($1.name) == .orderedAscending } } private var sortedAttributeGroups: [AttributeGroup] { attributeGroups.sorted { $0.name.localizedStandardCompare($1.name) == .orderedAscending } } private func restoreSelectedSectionIfNeeded() { guard let savedSection = PreferencesManager.shared.get(for: lastSelectedSectionPreferenceKey), let section = NavigationSection(rawValue: savedSection) else { return } selectedSection = section } private func restoreSelectedProductIfNeeded() { guard selectedProduct == nil, let productID = storedUUID(for: lastSelectedProductPreferenceKey) else { return } let descriptor = FetchDescriptor( predicate: #Predicate { product in product.id == productID } ) selectedProduct = try? modelContext.fetch(descriptor).first } private var sortedTemplates: [ProductTemplate] { templates.sorted { $0.name.localizedStandardCompare($1.name) == .orderedAscending } } private func createNewTemplate() { let template = ProductTemplate(name: "New Blank Template") modelContext.insert(template) selectedTemplate = template } private func deleteTemplates(offsets: IndexSet) { for index in offsets { let template = sortedTemplates[index] if selectedTemplate == template { selectedTemplate = nil } modelContext.delete(template) } } private func restoreSelectedTemplateIfNeeded() { guard selectedTemplate == nil, let templateID = storedUUID(for: lastSelectedTemplatePreferenceKey) else { return } let descriptor = FetchDescriptor( predicate: #Predicate { template in template.id == templateID } ) selectedTemplate = try? modelContext.fetch(descriptor).first } private func restoreSelectedCategoryIfNeeded() { guard selectedCategory == nil, let categoryID = storedUUID(for: lastSelectedCategoryPreferenceKey) else { return } let descriptor = FetchDescriptor( predicate: #Predicate { category in category.id == categoryID } ) selectedCategory = try? modelContext.fetch(descriptor).first } private func restoreSelectedArtworkIfNeeded() { guard selectedArtwork == nil, let artworkID = storedUUID(for: lastSelectedArtworkPreferenceKey) else { return } let descriptor = FetchDescriptor( predicate: #Predicate { artwork in artwork.id == artworkID } ) selectedArtwork = try? modelContext.fetch(descriptor).first } private func restoreSelectedBlankIfNeeded() { guard selectedBlank == nil, let blankID = storedUUID(for: lastSelectedBlankPreferenceKey) else { return } let descriptor = FetchDescriptor( predicate: #Predicate { blank in blank.id == blankID } ) selectedBlank = try? modelContext.fetch(descriptor).first } private func restoreSelectedGroupIfNeeded() { guard selectedGroup == nil, let groupID = storedUUID(for: lastSelectedGroupPreferenceKey) else { return } let descriptor = FetchDescriptor( predicate: #Predicate { group in group.id == groupID } ) selectedGroup = try? modelContext.fetch(descriptor).first } private func restoreSelectedContentBlockIfNeeded() { guard selectedContentBlock == nil, let blockID = storedUUID(for: lastSelectedContentBlockPreferenceKey) else { return } let descriptor = FetchDescriptor( predicate: #Predicate { block in block.id == blockID } ) selectedContentBlock = try? modelContext.fetch(descriptor).first } private func storedUUID(for preferenceKey: String) -> UUID? { guard let storedValue = PreferencesManager.shared.get(for: preferenceKey) else { return nil } return UUID(uuidString: storedValue) } private func generateSKU(for template: ProductTemplate? = nil, category: Category? = nil) -> String { "TGP-\(String(UUID().uuidString.prefix(8)).uppercased())" } private func createBlankAttributeGroup() { let suffix = String(UUID().uuidString.prefix(4)).lowercased() let group = AttributeGroup(name: "New Group \(suffix)", options: [], categories: []) modelContext.insert(group) selectedGroup = group } private func createNewContentBlock() { let suffix = String(UUID().uuidString.prefix(4)).lowercased() let newBlock = StoreContentBlock( key: "content_block_\(suffix)", title: "New Block", shortText: "", fullText: "", groupName: "General", internalDescription: "" ) modelContext.insert(newBlock) selectedContentBlock = newBlock } private func deleteContentBlock(_ block: StoreContentBlock) { if selectedContentBlock?.id == block.id { selectedContentBlock = nil } modelContext.delete(block) try? modelContext.save() JSONExporter.publishProducts(context: modelContext) } private func jumpToGroup(_ group: AttributeGroup) { selectedSection = .globalGroups selectedGroup = group } private func jumpToCategory(_ category: Category) { selectedSection = .taxonomy selectedCategory = category } private func jumpToProducts(in category: Category) { selectedSection = .products productCategoryFilter = category productSearchText = "" selectedProduct = nil } private func createProductFromWizard() { let uniqueSuffix = String(UUID().uuidString.prefix(8)) let descriptor = FetchDescriptor( predicate: #Predicate { persona in persona.isDefault == true } ) let defaultPersona = try? modelContext.fetch(descriptor).first let product = ApparelProduct( sku: "TGP-\(uniqueSuffix)", name: "New Tie-Dye", shortDesc: "Fresh dye pattern ready for the catalog.", longDesc: "A sample Groovy Panda tie-dye apparel record for inventory testing.", isUniqueOneOff: wizardIsOneOfOne, aiHelperContext: defaultPersona?.promptText, customAccordions: [] ) product.categories = wizardSelectedCategory.map { [$0] } ?? [] modelContext.insert(product) selectedProduct = product selectedSection = .products resetNewProductWizard() taxonomyRefreshTrigger += 1 } private func createProduct(from template: ProductTemplate, selectedSize: String? = nil) { var initialAttributes = template.savedAttributes if let selectedSize, let category = template.category { if let sizeGroup = category.allAttributeGroups.first(where: { $0.name.localizedCaseInsensitiveContains("Size") || ($0.displayName?.localizedCaseInsensitiveContains("Size") ?? false) }) { initialAttributes[sizeGroup.name] = selectedSize } } let product = ApparelProduct( sku: generateSKU(for: template, category: template.category), name: template.name, shortDesc: "", longDesc: "", isUniqueOneOff: template.isUniqueOneOff, aiHelperContext: template.savedAIPrompt, customAccordions: template.savedAccordions, selectedAttributes: initialAttributes, categories: template.category.map { [$0] } ?? nil, tags: template.savedTags ) modelContext.insert(product) selectedProduct = product selectedSection = .products showingQuickStart = false taxonomyRefreshTrigger += 1 } private func resetNewProductWizard() { showingNewProductWizard = false wizardSelectedCategory = nil wizardIsOneOfOne = true } @MainActor private func duplicateCurrentProduct(from original: ApparelProduct) { let uniqueSuffix = String(UUID().uuidString.prefix(8)) let duplicatedAccordions = original.customAccordions.map { accordion in WebAccordion(title: accordion.title, content: accordion.content) } let duplicatedProduct = ApparelProduct( sku: "\(original.sku)-COPY-\(uniqueSuffix)", name: original.name, basePriceCents: original.basePriceCents, weightLbs: original.weightLbs, shortDesc: original.shortDesc, longDesc: original.longDesc, seoTitle: original.seoTitle, seoKeywords: original.seoKeywords, seoMetaDesc: original.seoMetaDesc, isUniqueOneOff: original.isUniqueOneOff, images: [], imageLabels: [:], imageComments: [:], aiHelperContext: original.aiHelperContext, aiSecretContext: original.aiSecretContext, songReference: original.songReference, customAccordions: duplicatedAccordions, categories: original.categories, tags: original.tags, variants: [] ) modelContext.insert(duplicatedProduct) selectedProduct = duplicatedProduct taxonomyRefreshTrigger += 1 } @MainActor private func deleteSelectedProduct(_ product: ApparelProduct) { if selectedProduct == product { selectedProduct = nil } modelContext.delete(product) taxonomyRefreshTrigger += 1 } private func addDummyArtwork() { let uniqueSuffix = String(UUID().uuidString.prefix(8)) let artwork = Artwork( sku: "ART-\(uniqueSuffix)", name: "New Artwork", dimensions: "12x12", mediaCompatibilities: ["DTF", "Screen Print"], heroImage: nil, stockQty: 1 ) modelContext.insert(artwork) selectedArtwork = artwork } private func addDummyBlank() { let uniqueSuffix = String(UUID().uuidString.prefix(8)) let blank = BlankMedia( sku: "BLK-\(uniqueSuffix)", name: "New Blank", mediaType: "T-Shirt", style: "Classic Tee", color: "Natural", size: "L", costCents: 1200, stockQty: 12, heroImage: nil ) modelContext.insert(blank) selectedBlank = blank } private func addItemForSelectedSection() { switch selectedSection { case .products: showingQuickStart = true case .templates: createNewTemplate() case .artworks: addDummyArtwork() case .blanks: addDummyBlank() case .taxonomy: break case .globalGroups: createBlankAttributeGroup() case .personas: selectedPersona = nil case .contentBlocks: createNewContentBlock() case nil: break } } private var addItemHelpText: String { switch selectedSection { case .products: "Add a new product" case .templates: "Add a new template" case .artworks: "Add a new artwork" case .blanks: "Add new blank media" case .taxonomy: "Manage taxonomy and rules" case .globalGroups: "Manage global groups" case .personas: "Manage AI Personas & Prompts" case .contentBlocks: "Add a new content block" case nil: "Select a section first" } } private func deleteTemplate(_ template: ProductTemplate) { modelContext.delete(template) } private func openTaxonomyWizardFromQuickStart() { shouldOpenTaxonomyWizardAfterQuickStart = true showingQuickStart = false } private func handleQuickStartDismiss() { guard shouldOpenTaxonomyWizardAfterQuickStart else { return } shouldOpenTaxonomyWizardAfterQuickStart = false showingNewProductWizard = true } private func deleteProducts(offsets: IndexSet) { for index in offsets { let product = products[index] if selectedProduct == product { selectedProduct = nil } modelContext.delete(product) } taxonomyRefreshTrigger += 1 } private func deleteArtworks(offsets: IndexSet) { for index in offsets { let artwork = artworks[index] if selectedArtwork == artwork { selectedArtwork = nil } modelContext.delete(artwork) } } private func deleteBlanks(offsets: IndexSet) { for index in offsets { let blank = blanks[index] if selectedBlank == blank { selectedBlank = nil } modelContext.delete(blank) } } } struct ProductDetailView: View { @Environment(\.modelContext) private var modelContext @Environment(\.openWindow) private var openWindow @AppStorage("ai_provider") private var aiProvider: String = "ollama" @AppStorage("ollama_model") private var ollamaModel: String = "llama3.1:8b" @Bindable var product: ApparelProduct let onDuplicateProduct: () -> Void let onDeleteProduct: () -> Void let onJumpToCategory: (Category) -> Void let onJumpToGroup: (AttributeGroup) -> Void let onCategoryChanged: () -> Void @Query private var personas: [AIPersona] @Query private var allCategories: [Category] @Query private var allTags: [Tag] @State private var isGenerating = false @State private var isGeneratingSEO = false @State private var isGeneratingPackage = false @State private var isGeneratingNameTagline = false @State private var isSendingToGroovyStudio = false @State private var zoomedImageFilename: String? @State private var draggedImage: String? @State private var activeTagStrings: [String] = [] @State private var showingTagBrowser = false @State private var showingNewCategoryAlert = false @State private var newCategoryName = "" @State private var showingTemplateBuilder = false @State private var showingValidationAlert = false @State private var validationMessage = "" @State private var lockedFieldKeys: Set = [] // Visual diff highlighting state @State private var highlightedFieldKeys: Set = [] @State private var highlightedStyles: Set = [] @State private var promotedStyles: Set = [] private let lockableFieldKeys: [String] = ["name", "tagline", "song_inspiration", "long_description_html", "meta_description"] private var lockableFieldLabels: [String: String] { [ "name": "Name", "tagline": "Tagline", "song_inspiration": "Song", "long_description_html": "Description", "meta_description": "SEO Meta" ] } @ViewBuilder private func inlineLockButton(for fieldKey: String) -> some View { Button(action: { if lockedFieldKeys.contains(fieldKey) { lockedFieldKeys.remove(fieldKey) } else { lockedFieldKeys.insert(fieldKey) } }) { Image(systemName: lockedFieldKeys.contains(fieldKey) ? "lock.fill" : "lock.open") .foregroundStyle(lockedFieldKeys.contains(fieldKey) ? Color.orange : Color.secondary) .font(.system(size: 14, weight: .semibold)) } .buttonStyle(.plain) .help(lockedFieldKeys.contains(fieldKey) ? "Field is locked from AI regeneration" : "Field will be regenerated by AI") .accessibilityLabel(lockedFieldKeys.contains(fieldKey) ? "Unlock \(lockableFieldLabels[fieldKey] ?? fieldKey)" : "Lock \(lockableFieldLabels[fieldKey] ?? fieldKey)") } @ViewBuilder private func LockToggleChip(key: String, label: String, isLocked: Bool, onToggle: @escaping (Bool) -> Void) -> some View { Button(action: { onToggle(!isLocked) }) { HStack(spacing: 4) { Image(systemName: isLocked ? "lock.fill" : "lock.open") .font(.system(size: 11, weight: .bold)) Text(label) .font(.caption) .fontWeight(.medium) } .padding(.horizontal, 10) .padding(.vertical, 5) .background( Capsule() .fill(isLocked ? Color.orange.opacity(0.2) : Color.secondary.opacity(0.1)) ) .overlay( Capsule() .stroke(isLocked ? Color.orange.opacity(0.5) : Color.secondary.opacity(0.3), lineWidth: 1) ) .foregroundStyle(isLocked ? Color.orange : Color.primary) } .buttonStyle(.plain) .help(isLocked ? "\(label) is locked from AI regeneration" : "\(label) will be regenerated by AI") } @ViewBuilder private func updatedBadge(for key: String) -> some View { if highlightedFieldKeys.contains(key) { Text("✨ Updated") .font(.caption2) .fontWeight(.medium) .padding(.horizontal, 6) .padding(.vertical, 2) .background(Color.green.opacity(0.15)) .foregroundStyle(Color.green) .clipShape(Capsule()) .overlay( Capsule() .stroke(Color.green.opacity(0.4), lineWidth: 1) ) .transition(.opacity.combined(with: .scale)) } } var body: some View { ScrollView { HStack(alignment: .top, spacing: 40) { VStack(alignment: .leading, spacing: 24) { GroupBox("Basic Info") { VStack(spacing: 12) { ProductFormRow(label: "SKU") { TextField("", text: $product.sku) } ProductFormRow(label: "Product Name") { HStack { TextField("", text: $product.name) inlineLockButton(for: "name") updatedBadge(for: "name") Button(action: suggestNameAndTagline) { if isGeneratingNameTagline { ProgressView() .controlSize(.small) } else { Label("Suggest Name & Tagline", systemImage: "sparkles") } } .disabled(isGeneratingNameTagline || isGeneratingPackage) } } LabeledContent { CurrencyTextField(title: "Price", cents: $product.basePriceCents) } label: { HStack(spacing: 4) { Text("Price") .foregroundStyle(.secondary) if product.basePriceCents <= 0 { HStack(spacing: 4) { Image(systemName: "exclamationmark.triangle.fill") .foregroundStyle(.orange) Text("Price is $0.00") .font(.caption) .foregroundStyle(.orange) } } } } LabeledContent { TextField("", value: $product.weightLbs, format: .number) .textFieldStyle(.roundedBorder) } label: { HStack(spacing: 4) { Text("Weight (lbs)") .foregroundStyle(.secondary) if product.weightLbs <= 0 { HStack(spacing: 4) { Image(systemName: "exclamationmark.triangle.fill") .foregroundStyle(.orange) Text("Weight is 0.0 lbs") .font(.caption) .foregroundStyle(.orange) } } } } Toggle("Unique / One-Of-A-Kind", isOn: $product.isUniqueOneOff) Toggle("Featured Product", isOn: $product.isFeatured) Toggle("New Arrival", isOn: $product.isNewArrival) Toggle("Best Seller", isOn: $product.isBestSeller) } .textFieldStyle(.roundedBorder) } GroupBox("AI Settings") { VStack(spacing: 12) { HStack { Text("Active Persona") Spacer() Picker("Active Persona", selection: Binding( get: { personas.first(where: { $0.promptText == product.aiHelperContext }) }, set: { newPersona in if let newPersona { product.aiHelperContext = newPersona.promptText } } )) { Text("Custom / Manual").tag(AIPersona?.none) ForEach(personas) { persona in Text(persona.title).tag(Optional(persona)) } } .labelsHidden() } TextField("AI Persona Prompt (Context)", text: Binding( get: { product.aiHelperContext ?? "" }, set: { product.aiHelperContext = $0.isEmpty ? nil : $0 } ), axis: .vertical) .lineLimit(3...15) ProductFormRow(label: "Song Inspiration") { HStack { TextField("e.g. Pink Floyd - Meddle / A Pillow of Winds, or leave empty", text: Binding( get: { product.songReference ?? "" }, set: { product.songReference = $0.isEmpty ? nil : $0 } )) inlineLockButton(for: "song_inspiration") updatedBadge(for: "song_inspiration") } } ProductFormRow(label: "Visual & Crafting Hints (Not Printed)") { TextField("e.g. Back peace sign is reflective silver holographic mirror vinyl", text: Binding( get: { product.aiSecretContext ?? "" }, set: { newValue in let trimmed = newValue.trimmingCharacters(in: .whitespacesAndNewlines) product.aiSecretContext = trimmed.isEmpty ? nil : trimmed } ), axis: .vertical) .lineLimit(2...5) } Button(action: generateCosmicPackage) { HStack { if isGeneratingPackage { ProgressView() .controlSize(.small) } else { Image(systemName: "sparkles") } Text("✨ Cosmic Groovify (Full Package)") .bold() } .frame(maxWidth: .infinity) } .buttonStyle(.borderedProminent) .disabled(isGeneratingPackage || isGenerating || isGeneratingSEO || isGeneratingNameTagline) // Field Locks Quick-Lock Bar VStack(alignment: .leading, spacing: 8) { Text("Field Locks (Preserve from AI)") .font(.caption) .fontWeight(.semibold) .foregroundStyle(.secondary) HStack(spacing: 8) { Button("Lock All") { lockedFieldKeys = Set(lockableFieldKeys) } .buttonStyle(.bordered) .controlSize(.small) Button("Unlock All") { lockedFieldKeys.removeAll() } .buttonStyle(.bordered) .controlSize(.small) } ScrollView(.horizontal, showsIndicators: false) { HStack(spacing: 8) { ForEach(lockableFieldKeys, id: \.self) { key in LockToggleChip( key: key, label: lockableFieldLabels[key] ?? key, isLocked: lockedFieldKeys.contains(key), onToggle: { isLocked in if isLocked { lockedFieldKeys.insert(key) } else { lockedFieldKeys.remove(key) } } ) } } } } .padding(.vertical, 4) if GroovyStudioBridge.pendingResponseURL(for: product.id) != nil { Button(action: { openWindow(id: "groovyStudioReview", value: product.id) }) { HStack { Image(systemName: "doc.text.magnifyingglass") Text("Review Pending Response") .bold() } .frame(maxWidth: .infinity) } .buttonStyle(.bordered) } Button(action: sendToGroovyStudio) { HStack { if isSendingToGroovyStudio { ProgressView() .controlSize(.small) } else { Image(systemName: "arrow.up.forward.app") } Text("Send to Groovy Studio") .bold() } .frame(maxWidth: .infinity) } .buttonStyle(.borderedProminent) .disabled(isSendingToGroovyStudio || isGeneratingPackage || isGenerating || isGeneratingSEO || isGeneratingNameTagline) } .textFieldStyle(.roundedBorder) } GroupBox("Descriptions") { VStack(spacing: 12) { ProductFormRow(label: "Tagline") { HStack { TextField("", text: $product.shortDesc) inlineLockButton(for: "tagline") updatedBadge(for: "tagline") } } HStack { Text("Long Description (HTML)") Text(activeModelName) .font(.caption) .foregroundStyle(.secondary) Spacer() inlineLockButton(for: "long_description_html") updatedBadge(for: "long_description_html") Button(action: generateGroovyDescription) { if isGenerating { ProgressView() .controlSize(.small) } else { Label("Groovify Description", systemImage: "sparkles") } } .disabled(isGenerating || product.name.isEmpty) } TextField("Long Description", text: $product.longDesc, axis: .vertical) .lineLimit(5...25) .textFieldStyle(.roundedBorder) } } GroupBox("Search Optimization") { VStack(alignment: .leading, spacing: 12) { HStack { if isGeneratingSEO { ProgressView() .controlSize(.small) } Button(action: generateSEOFields) { Label("Auto-SEO", systemImage: "sparkles") } .disabled(isGeneratingSEO || product.name.isEmpty || product.longDesc.isEmpty) Spacer() } ProductFormRow(label: "Page Title") { TextField("", text: $product.seoTitle) } ProductFormRow(label: "Keywords") { TextField("", text: $product.seoKeywords) } VStack(alignment: .leading, spacing: 8) { HStack { Text("Meta Description") .foregroundStyle(.secondary) inlineLockButton(for: "meta_description") updatedBadge(for: "meta_description") } TextEditor(text: $product.seoMetaDesc) .frame(height: 100) .overlay( RoundedRectangle(cornerRadius: 6) .stroke(.secondary.opacity(0.2)) ) } } } } .frame(maxWidth: .infinity) VStack(alignment: .leading, spacing: 24) { GroupBox { VStack(spacing: 12) { HStack { Text("Product Images") .font(.headline) Spacer() Button(action: browseFiles) { Label("Browse Files", systemImage: "folder") } } if !product.images.isEmpty { ScrollView(.horizontal) { HStack(spacing: 16) { ForEach(product.images, id: \.self) { filename in VStack(spacing: 8) { if let nsImage = ImageManager.shared.loadImage(filename: filename) { Image(nsImage: nsImage) .resizable() .scaledToFill() .frame(width: 120, height: 120) .clipShape(.rect(cornerRadius: 8)) .onTapGesture(count: 2) { zoomedImageFilename = filename } .onDrag { draggedImage = filename return NSItemProvider(object: filename as NSString) } .onDrop(of: [.text], delegate: ImageReorderDelegate( item: filename, items: $product.images, draggedItem: $draggedImage )) } HStack { if product.images.first == filename { Text("Primary") .font(.caption) .bold() .foregroundStyle(.white) .padding(.horizontal, 8) .padding(.vertical, 4) .background(.blue) .clipShape(.rect(cornerRadius: 4)) } else { Button("Set Primary") { withAnimation { if let idx = product.images.firstIndex(of: filename) { product.images.swapAt(0, idx) } } } .buttonStyle(.bordered) .controlSize(.small) } Spacer() CommentIndicatorView(comment: product.imageComments[filename] ?? "") Button(role: .destructive, action: { ImageManager.shared.deleteImage(filename: filename) product.images.removeAll { $0 == filename } product.imageLabels.removeValue(forKey: filename) product.imageComments.removeValue(forKey: filename) }) { Image(systemName: "trash") .foregroundStyle(.red) } .buttonStyle(.plain) } .frame(width: 120) Picker("", selection: imageLabelBinding(for: filename)) { Text("None").tag("None") Text("Front").tag("Front") Text("Back").tag("Back") Text("Side").tag("Side") Text("Detail").tag("Detail") } .labelsHidden() .controlSize(.mini) .frame(width: 120) } } } .padding(.vertical, 4) } .frame(height: 160) .scrollIndicators(.hidden) } ZStack { RoundedRectangle(cornerRadius: 8) .strokeBorder(.secondary.opacity(0.5), style: StrokeStyle(lineWidth: 2, dash: [6])) .background(.secondary.opacity(0.05)) .frame(height: product.images.isEmpty ? 200 : 80) VStack { Image(systemName: "photo.on.rectangle.angled") .font(.system(size: product.images.isEmpty ? 40 : 24)) .foregroundStyle(.secondary) Text("Drop Images Here or CMD+V") .foregroundStyle(.secondary) } } .onDrop(of: [.image], isTargeted: nil) { providers in handleImageDrop(providers: providers) } .focusable() .onPasteCommand(of: [.image]) { providers in _ = handleImageDrop(providers: providers) } } } .popover(item: Binding( get: { zoomedImageFilename.map { IdentifiableString(value: $0) } }, set: { zoomedImageFilename = $0?.value } )) { identifiableString in if let nsImage = ImageManager.shared.loadImage(filename: identifiableString.value) { ImageZoomPopoverView(product: product, filename: identifiableString.value, nsImage: nsImage) } } // GroupBox { // VStack(alignment: .leading, spacing: 12) { // HStack { // Text("Search Optimization") // .font(.headline) // Spacer() // Button(action: generateSEOFields) { // if isGeneratingSEO { // ProgressView() // .controlSize(.small) // } else { // Text("✨ Auto-SEO") // } // } // .disabled(isGeneratingSEO || product.name.isEmpty || product.longDesc.isEmpty) // } // // ProductFormRow(label: "Page Title") { // TextField("", text: $product.seoTitle) // } // // ProductFormRow(label: "Search Words") { // TextField("", text: $product.seoKeywords) // } // // VStack(alignment: .leading, spacing: 8) { // Text("Meta Description") // .foregroundStyle(.secondary) // TextEditor(text: $product.seoMetaDesc) // .frame(minHeight: 100) // .overlay( // RoundedRectangle(cornerRadius: 6) // .stroke(.secondary.opacity(0.2)) // ) // } // } // } ProductOrganizationSection( rootCategories: rootCategories, allTags: allTags, primaryCategory: product.categories?.first, primaryCategoryName: primaryCategoryName, activeTagStrings: $activeTagStrings, showingTagBrowser: $showingTagBrowser, showingNewCategoryAlert: $showingNewCategoryAlert, newCategoryName: $newCategoryName, onAssignPrimaryCategory: assignPrimaryCategory, onJumpToCategory: onJumpToCategory, onCategoryChanged: onCategoryChanged, onAddCategory: addCategoryFromAlert, onDeleteTag: deleteTag ) if product.isUniqueOneOff, let primaryCategory = product.categories?.first { GroupBox("1-of-1 Properties") { OneOfOnePropertiesSection( product: product, attributeGroups: primaryCategory.allAttributeGroups, onJumpToGroup: onJumpToGroup, highlightedStyles: highlightedStyles, promotedStyles: promotedStyles ) } } GroupBox("Web Accordions / Custom Fields") { VStack(alignment: .leading, spacing: 16) { let categoryDefaults = product.categories?.first?.allDefaultAccordions ?? [] let categoryTitles = Set(categoryDefaults.map(\.title)) if !categoryDefaults.isEmpty { VStack(alignment: .leading, spacing: 12) { Text("Category Default Accordions") .font(.caption) .fontWeight(.bold) .foregroundStyle(.secondary) ForEach(categoryDefaults, id: \.title) { catAccordion in if let overrideIndex = product.customAccordions.firstIndex(where: { $0.title == catAccordion.title }) { VStack(alignment: .leading, spacing: 8) { HStack { TextField("Tab/Accordion Title", text: $product.customAccordions[overrideIndex].title) .textFieldStyle(.roundedBorder) Text("(Overriding Category Default)") .font(.caption) .padding(.horizontal, 6) .padding(.vertical, 2) .background(Color.orange.opacity(0.15)) .foregroundStyle(.orange) .clipShape(Capsule()) Button("Revert to Default") { product.customAccordions.removeAll { $0.title == catAccordion.title } } .buttonStyle(.borderless) .font(.caption) } TextEditor(text: $product.customAccordions[overrideIndex].content) .font(.body) .frame(minHeight: 60) .overlay( RoundedRectangle(cornerRadius: 6) .stroke(Color.secondary.opacity(0.2), lineWidth: 1) ) } .padding(8) .background(Color.secondary.opacity(0.05)) .clipShape(RoundedRectangle(cornerRadius: 8)) } else { VStack(alignment: .leading, spacing: 8) { HStack { Text(catAccordion.title) .font(.headline) Text("(Inherited from Category)") .font(.caption) .padding(.horizontal, 6) .padding(.vertical, 2) .background(Color.blue.opacity(0.15)) .foregroundStyle(.blue) .clipShape(Capsule()) Spacer() Button("Override for this Item") { product.customAccordions.append(WebAccordion(title: catAccordion.title, content: catAccordion.content)) } .buttonStyle(.borderless) .font(.caption) } Text(catAccordion.content.isEmpty ? "No content defined in category" : catAccordion.content) .font(.body) .foregroundStyle(catAccordion.content.isEmpty ? .tertiary : .secondary) .padding(8) .frame(maxWidth: .infinity, alignment: .leading) .background(Color.secondary.opacity(0.05)) .clipShape(RoundedRectangle(cornerRadius: 6)) } .padding(8) .background(Color.secondary.opacity(0.03)) .clipShape(RoundedRectangle(cornerRadius: 8)) } } } Divider() } VStack(alignment: .leading, spacing: 12) { if !categoryDefaults.isEmpty { Text("Custom / One-Off Fields") .font(.caption) .fontWeight(.bold) .foregroundStyle(.secondary) } let oneOffAccordions = product.customAccordions.filter { !categoryTitles.contains($0.title) } ForEach(oneOffAccordions) { accordion in if let index = product.customAccordions.firstIndex(where: { $0.id == accordion.id }) { VStack(alignment: .leading, spacing: 8) { HStack { TextField("Tab/Accordion Title", text: $product.customAccordions[index].title) .textFieldStyle(.roundedBorder) Button(role: .destructive, action: { product.customAccordions.removeAll { $0.id == accordion.id } }) { Image(systemName: "trash") } .buttonStyle(.borderless) } TextEditor(text: $product.customAccordions[index].content) .font(.body) .frame(minHeight: 60) .overlay( RoundedRectangle(cornerRadius: 6) .stroke(Color.secondary.opacity(0.2), lineWidth: 1) ) } .padding(.bottom, 8) Divider() } } Button(action: { product.customAccordions.append(WebAccordion(title: "New Detail", content: "")) }) { Label("Add Accordion Field", systemImage: "plus.circle.fill") } .padding(.top, 4) } } } GroupBox("Variants & Inventory") { VStack(alignment: .leading, spacing: 12) { if product.isUniqueOneOff { Text("1-of-1 Unique Item. No variants.") .foregroundStyle(.secondary) } else { if !product.isUniqueOneOff && (product.variants?.isEmpty ?? true) { Button(action: generateVariantsFromRules) { Label("Generate Variants from Category Rules", systemImage: "wand.and.stars") } .buttonStyle(.borderedProminent) .disabled(product.categories?.isEmpty ?? true) } ForEach(variantBindings) { $variant in HStack(alignment: .center, spacing: 12) { TextField("Label", text: $variant.label) .textFieldStyle(.roundedBorder) TextField("SKU Suffix", text: $variant.variantId) .textFieldStyle(.roundedBorder) TextField("Stock", value: $variant.stockQty, format: .number) .textFieldStyle(.roundedBorder) .frame(maxWidth: 90) CurrencyTextField(title: "Price", cents: $variant.priceCents) .frame(maxWidth: 110) Button(role: .destructive) { deleteVariant(variant) } label: { Image(systemName: "trash") } .buttonStyle(.borderless) } } Button("Add Variant", systemImage: "plus.circle.fill") { addVariant() } } } } } .frame(maxWidth: .infinity) } .padding() .font(.system(size: 14)) } .navigationTitle(product.name.isEmpty ? "New Product" : product.name) .onChange(of: product.isUniqueOneOff, initial: false) { _, newValue in guard newValue, let existingVariants = product.variants, !existingVariants.isEmpty else { return } for variant in existingVariants { modelContext.delete(variant) } product.variants = [] } .onChange(of: product.id, initial: true) { _, _ in syncActiveTags() } .onChange(of: activeTagStrings, initial: true) { _, _ in saveActiveTags() } .onChange(of: product.id) { _, newProduct in // Reset visual diff highlights when product changes highlightedFieldKeys.removeAll() highlightedStyles.removeAll() promotedStyles.removeAll() } .onReceive(NotificationCenter.default.publisher(for: Notification.Name("local.com.factory.groovypanda.staged_changes_applied"))) { notification in guard let userInfo = notification.userInfo, let productId = userInfo["product_id"] as? String, productId == product.id.uuidString else { return } if let changedFields = userInfo["changed_fields"] as? [String] { highlightedFieldKeys = Set(changedFields) } if let appliedStyles = userInfo["applied_styles"] as? [String] { highlightedStyles = Set(appliedStyles) } if let promotedStyleArray = userInfo["promoted_styles"] as? [String] { promotedStyles = Set(promotedStyleArray) } } .toolbar { ToolbarItem { Button(action: onDuplicateProduct) { Label("Duplicate Product", systemImage: "doc.on.doc") } .labelStyle(.titleAndIcon) .help("Create a clone of this product") } ToolbarItem { Button { showingTemplateBuilder = true } label: { Label("Save Template", systemImage: "tray.and.arrow.down") } .labelStyle(.titleAndIcon) .help("Save this product's settings as a reusable template") } ToolbarItem { Button(role: .destructive) { onDeleteProduct() } label: { Label("Delete Product", systemImage: "trash") } .labelStyle(.titleAndIcon) .help("Permanently delete this product") } } .sheet(isPresented: $showingTemplateBuilder) { TemplateBuilderView(sourceProduct: product) } .alert("Missing Information", isPresented: $showingValidationAlert) { Button("OK", role: .cancel) { validationMessage = "" } } message: { Text(validationMessage) } } @MainActor private func generateCosmicPackage() { guard validateRequiredAttributes() else { return } isGeneratingPackage = true Task { do { let descriptor = FetchDescriptor() let existingProducts = (try? modelContext.fetch(descriptor)) ?? [] var existingCatalogItems: [String] = [] for existingProduct in existingProducts { if existingProduct.id != product.id { if !existingProduct.name.isEmpty { existingCatalogItems.append(existingProduct.name) } if let songRef = existingProduct.songReference ?? existingProduct.aiSecretContext, !songRef.isEmpty { existingCatalogItems.append(songRef) } } } let globalBaseRules = PreferencesManager.shared.get(for: "global_ai_base_rules") let primaryCategory = product.categories?.first let categorySizePrefix = primaryCategory?.sizePrefix?.trimmingCharacters(in: .whitespacesAndNewlines) let selectedTraits = product.selectedAttributes.compactMap { (key: String, value: String) -> String? in guard !value.isEmpty else { return nil } let isSizeGroup = key.localizedCaseInsensitiveContains("size") if isSizeGroup, let categorySizePrefix, !categorySizePrefix.isEmpty, !value.localizedCaseInsensitiveContains(categorySizePrefix) { return "Size: \(categorySizePrefix) \(value)" } return "\(key): \(value)" } let package = try await AIAssistManager.shared.generateProductPackage( productName: nil, categoryContext: product.categories?.first?.fullPath, selectedAttributes: selectedTraits, personaPrompt: product.aiHelperContext, globalBaseRules: globalBaseRules, songSeed: product.songReference, visualHints: product.aiSecretContext, existingCatalogItems: existingCatalogItems, imageFilenames: product.images, imageLabels: product.imageLabels ) product.name = package.name product.shortDesc = package.tagline product.longDesc = package.longDescription product.seoTitle = package.seoTitle product.seoKeywords = package.seoKeywords product.seoMetaDesc = package.seoMetaDesc if !package.songReference.isEmpty { product.songReference = package.songReference } try? modelContext.save() JSONExporter.publishProducts(context: modelContext) } catch { print("❌ Cosmic Groovify package generation failed: \(error)") } isGeneratingPackage = false } } @MainActor private func suggestNameAndTagline() { guard validateRequiredAttributes() else { return } isGeneratingNameTagline = true Task { do { let descriptor = FetchDescriptor() let existingProducts = (try? modelContext.fetch(descriptor)) ?? [] var existingCatalogItems: [String] = [] for existingProduct in existingProducts { if existingProduct.id != product.id { if !existingProduct.name.isEmpty { existingCatalogItems.append(existingProduct.name) } if let songRef = existingProduct.songReference ?? existingProduct.aiSecretContext, !songRef.isEmpty { existingCatalogItems.append(songRef) } } } let globalBaseRules = PreferencesManager.shared.get(for: "global_ai_base_rules") let primaryCategory = product.categories?.first let categorySizePrefix = primaryCategory?.sizePrefix?.trimmingCharacters(in: .whitespacesAndNewlines) let selectedTraits = product.selectedAttributes.compactMap { (key: String, value: String) -> String? in guard !value.isEmpty else { return nil } let isSizeGroup = key.localizedCaseInsensitiveContains("size") if isSizeGroup, let categorySizePrefix, !categorySizePrefix.isEmpty, !value.localizedCaseInsensitiveContains(categorySizePrefix) { return "Size: \(categorySizePrefix) \(value)" } return "\(key): \(value)" } let package = try await AIAssistManager.shared.generateProductPackage( productName: nil, categoryContext: product.categories?.first?.fullPath, selectedAttributes: selectedTraits, personaPrompt: product.aiHelperContext, globalBaseRules: globalBaseRules, songSeed: product.songReference, visualHints: product.aiSecretContext, existingCatalogItems: existingCatalogItems, imageFilenames: product.images, imageLabels: product.imageLabels ) product.name = package.name product.shortDesc = package.tagline if !package.songReference.isEmpty { product.songReference = package.songReference } try? modelContext.save() JSONExporter.publishProducts(context: modelContext) } catch { print("❌ Suggest Name & Tagline failed: \(error)") } isGeneratingNameTagline = false } } @MainActor private func generateGroovyDescription() { guard validateRequiredAttributes() else { return } isGenerating = true Task { do { let generatedText = try await AIAssistManager.shared.generateDescription( productName: product.name, shortDesc: product.shortDesc, persona: product.aiHelperContext, secretContext: compiledAIContext, visualHints: product.aiSecretContext, imageFilenames: product.images, imageLabels: product.imageLabels ) product.longDesc = generatedText try? modelContext.save() JSONExporter.publishProducts(context: modelContext) } catch { product.longDesc = error.localizedDescription } isGenerating = false } } @MainActor private func generateSEOFields() { guard validateRequiredAttributes() else { return } isGeneratingSEO = true Task { do { let seo = try await AIAssistManager.shared.generateSEO( name: product.name, description: product.longDesc + "\n\nAdditional Context:\n" + compiledAIContext ) product.seoTitle = seo.title product.seoKeywords = seo.keywords product.seoMetaDesc = seo.meta try? modelContext.save() JSONExporter.publishProducts(context: modelContext) } catch { print("❌ SEO generation failed: \(error)") product.seoMetaDesc = error.localizedDescription } isGeneratingSEO = false } } @MainActor private func sendToGroovyStudio() { // Force any focused text field to commit its current text to the model binding NSApp.keyWindow?.makeFirstResponder(nil) // Persist any pending changes before dispatching try? modelContext.save() isSendingToGroovyStudio = true do { try GroovyStudioBridge.dispatchRequest(for: product, lockedFieldKeys: lockedFieldKeys) print("✅ [ProductDetailView] Dispatched request to Groovy Studio for product: \(product.name)") } catch { print("❌ [ProductDetailView] Failed to dispatch request to Groovy Studio: \(error)") } isSendingToGroovyStudio = false } private var primaryCategoryName: String { product.categories?.first?.name ?? "Select Category" } private var activeModelName: String { switch aiProvider { case "ollama": return ollamaModel case "gemini", "gemini-3.8-flash": return "Gemini 3.8 Flash" case "gemini-3.7-flash": return "Gemini 3.7 Flash" case "gemini-3.5-flash": return "Gemini 3.5 Flash" case "gemini-3.5-flash-lite": return "Gemini 3.5 Flash Lite" default: return aiProvider } } private var compiledAIContext: String { var context = product.aiSecretContext ?? "" if let primaryCategory = product.categories?.first { if !context.isEmpty { context.append("\n") } context.append("Category: \(primaryCategory.fullPath)\n") for group in primaryCategory.allAttributeGroups { guard let value = product.selectedAttributes[group.name], !value.isEmpty else { continue } context.append("\(group.displayName ?? group.name): \(value)\n") } } return context } private func validateRequiredAttributes() -> Bool { guard let primaryCategory = product.categories?.first else { return true } for group in primaryCategory.allAttributeGroups { let groupLabels = [group.name, group.displayName ?? ""] let isSizeGroup = groupLabels.contains { $0.localizedStandardContains("Size") } guard isSizeGroup else { continue } let selectedValue = product.selectedAttributes[group.name]?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" if selectedValue.isEmpty { validationMessage = "Please select a Size before generating AI content." showingValidationAlert = true return false } } return true } private var rootCategories: [Category] { allCategories .filter { $0.parentCategory == nil } .sorted { $0.name.localizedStandardCompare($1.name) == .orderedAscending } } private func imageLabelBinding(for filename: String) -> Binding { Binding( get: { product.imageLabels[filename] ?? "None" }, set: { newValue in if newValue == "None" { product.imageLabels.removeValue(forKey: filename) } else { product.imageLabels[filename] = newValue } } ) } private func assignPrimaryCategory(_ category: Category) { product.categories = [category] } @MainActor private func addCategoryFromAlert() { let trimmedName = newCategoryName.trimmingCharacters(in: .whitespacesAndNewlines) guard !trimmedName.isEmpty else { newCategoryName = "" return } let category = Category( slug: slugify(trimmedName), name: trimmedName ) modelContext.insert(category) product.categories = [category] newCategoryName = "" } @MainActor private func syncActiveTags() { let tagNames = (product.tags ?? []).map(\.name) if activeTagStrings != tagNames { activeTagStrings = tagNames } } @MainActor private func saveActiveTags() { let cleanedNames = activeTagStrings .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } .filter { !$0.isEmpty } if activeTagStrings != cleanedNames { activeTagStrings = cleanedNames return } var resolvedTags: [Tag] = [] for tagName in cleanedNames { let slug = slugify(tagName) let descriptor = FetchDescriptor( predicate: #Predicate { tag in tag.slug == slug } ) if let existingTag = try? modelContext.fetch(descriptor).first { resolvedTags.append(existingTag) } else { let newTag = Tag(slug: slug, name: tagName) modelContext.insert(newTag) resolvedTags.append(newTag) } } let existingTagIDs = Set((product.tags ?? []).map(\.id)) let resolvedTagIDs = Set(resolvedTags.map(\.id)) if existingTagIDs != resolvedTagIDs { product.tags = resolvedTags.isEmpty ? nil : resolvedTags } } private func deleteTag(_ tag: Tag) { activeTagStrings.removeAll { $0 == tag.name } modelContext.delete(tag) } private var variantBindings: Binding<[ApparelVariant]> { Binding( get: { product.variants ?? [] }, set: { product.variants = $0 } ) } private func addVariant() { let newVariant = ApparelVariant( product: product, variantId: "VAR-\((product.variants?.count ?? 0) + 1)", label: "", priceCents: product.basePriceCents, stockQty: 0 ) modelContext.insert(newVariant) if product.variants == nil { product.variants = [] } product.variants?.append(newVariant) } @MainActor private func generateVariantsFromRules() { guard let primaryCategory = product.categories?.first else { return } let validGroups = primaryCategory.allAttributeGroups.filter { group in group.isVariantTrait && !(group.options ?? []).isEmpty } guard !validGroups.isEmpty else { return } let optionSets = validGroups.map { group in sortedAttributeOptions(group.options ?? [], strategy: group.sortStrategy) } let combinations = optionSets.reduce([[]]) { partialResult, options in partialResult.flatMap { partialCombination in options.map { option in partialCombination + [option] } } } var generatedVariants: [ApparelVariant] = product.variants ?? [] let existingVariantIDs = Set(generatedVariants.map(\.variantId)) for combination in combinations { let optionValues = combination.map(\.value) let label = optionValues.joined(separator: " / ") let baseVariantID = "\(product.sku)-\(optionValues.map(slugify).joined(separator: "-"))" let variantID = uniqueVariantID(startingWith: baseVariantID, existingIDs: existingVariantIDs.union(generatedVariants.map(\.variantId))) let variant = ApparelVariant( product: product, variantId: variantID, label: label, priceCents: product.basePriceCents, stockQty: 0 ) modelContext.insert(variant) generatedVariants.append(variant) } product.variants = generatedVariants } private func deleteVariant(_ variant: ApparelVariant) { product.variants?.removeAll { $0.id == variant.id } modelContext.delete(variant) } private func uniqueVariantID(startingWith baseID: String, existingIDs: Set) -> String { guard !existingIDs.contains(baseID) else { var suffix = 1 var candidateID = "\(baseID)-\(suffix)" while existingIDs.contains(candidateID) { suffix += 1 candidateID = "\(baseID)-\(suffix)" } return candidateID } return baseID } private func slugify(_ name: String) -> String { name .lowercased() .replacing("'", with: "") .replacing("&", with: "and") .split(whereSeparator: { !$0.isLetter && !$0.isNumber }) .map(String.init) .joined(separator: "-") } private func handleImageDrop(providers: [NSItemProvider]) -> Bool { guard !product.sku.isEmpty else { print("❌ Cannot attach image: SKU is empty.") return false } guard providers.contains(where: { $0.hasItemConformingToTypeIdentifier(UTType.image.identifier) || $0.hasItemConformingToTypeIdentifier(UTType.fileURL.identifier) }) else { return false } for provider in providers { Task { await importImage(from: provider) } } return true } @MainActor private func appendImageFilename(_ filename: String) { if !product.images.contains(filename) { product.images.append(filename) } } private func importImage(from provider: NSItemProvider) async { if let filename = await importImageData(from: provider) { appendImageFilename(filename) return } if let filename = await importImageFile(from: provider) { appendImageFilename(filename) return } if let filename = await importImageObject(from: provider) { appendImageFilename(filename) } } private func importImageFile(from provider: NSItemProvider) async -> String? { if provider.hasItemConformingToTypeIdentifier(UTType.image.identifier) { do { if let fileURL = try await loadFileRepresentation(for: UTType.image.identifier, provider: provider) { return ImageManager.shared.importImageFile(from: fileURL, for: product.sku) } } catch { return nil } } if provider.hasItemConformingToTypeIdentifier(UTType.fileURL.identifier) { do { if let fileURL = try await loadItemURL(for: UTType.fileURL.identifier, provider: provider) { return ImageManager.shared.importImageFile(from: fileURL, for: product.sku) } } catch { return nil } } return nil } private func importImageData(from provider: NSItemProvider) async -> String? { guard provider.hasItemConformingToTypeIdentifier(UTType.image.identifier) else { return nil } do { let data = try await loadDataRepresentation(for: UTType.image.identifier, provider: provider) return ImageManager.shared.saveImageData(data, suggestedType: .image, for: product.sku) } catch { print("❌ Image import data representation failed: \(error)") return nil } } private func importImageObject(from provider: NSItemProvider) async -> String? { guard provider.canLoadObject(ofClass: NSImage.self) else { return nil } do { let image = try await loadImageObject(from: provider) return ImageManager.shared.saveImage(image, for: product.sku) } catch { print("❌ Image import NSImage failed: \(error)") return nil } } private func loadFileRepresentation(for typeIdentifier: String, provider: NSItemProvider) async throws -> URL? { try await withCheckedThrowingContinuation { continuation in provider.loadFileRepresentation(forTypeIdentifier: typeIdentifier) { url, error in if let error { continuation.resume(throwing: error) } else { continuation.resume(returning: url) } } } } private func loadItemURL(for typeIdentifier: String, provider: NSItemProvider) async throws -> URL? { try await withCheckedThrowingContinuation { continuation in provider.loadItem(forTypeIdentifier: typeIdentifier, options: nil) { item, error in if let error { continuation.resume(throwing: error) return } if let data = item as? Data, let url = URL(dataRepresentation: data, relativeTo: nil) { continuation.resume(returning: url) } else if let url = item as? URL { continuation.resume(returning: url) } else { continuation.resume(returning: nil) } } } } private func loadDataRepresentation(for typeIdentifier: String, provider: NSItemProvider) async throws -> Data { try await withCheckedThrowingContinuation { continuation in provider.loadDataRepresentation(forTypeIdentifier: typeIdentifier) { data, error in if let error { continuation.resume(throwing: error) } else if let data { continuation.resume(returning: data) } else { continuation.resume(throwing: CocoaError(.fileReadUnknown)) } } } } private func loadImageObject(from provider: NSItemProvider) async throws -> NSImage { try await withCheckedThrowingContinuation { continuation in provider.loadObject(ofClass: NSImage.self) { object, error in if let error { continuation.resume(throwing: error) } else if let image = object as? NSImage { continuation.resume(returning: image) } else { continuation.resume(throwing: CocoaError(.coderReadCorrupt)) } } } } private func browseFiles() { let panel = NSOpenPanel() panel.allowedContentTypes = [.image] panel.allowsMultipleSelection = true panel.canChooseDirectories = false if panel.runModal() == .OK { for url in panel.urls { if let image = NSImage(contentsOf: url) { Task { @MainActor in if let filename = ImageManager.shared.saveImage(image, for: product.sku) { product.images.append(filename) } } } } } } } // MARK: - Helpers struct CommentIndicatorView: View { let comment: String var body: some View { let trimmed = comment.trimmingCharacters(in: .whitespacesAndNewlines) if !trimmed.isEmpty { Image(systemName: "text.bubble.fill") .foregroundStyle(Color.accentColor) .help("Comment: \(trimmed)") } } } struct ImageZoomPopoverView: View { let product: ApparelProduct let filename: String let nsImage: NSImage var body: some View { VStack(spacing: 16) { // Image Preview Image(nsImage: nsImage) .resizable() .scaledToFit() .frame(minWidth: 420, maxWidth: 450, minHeight: 300, maxHeight: 450) .clipShape(.rect(cornerRadius: 8)) // Photo Perspective & Crafting Comment Section VStack(alignment: .leading, spacing: 8) { Text("Photo Perspective & Crafting Comment") .font(.headline) TextEditor(text: Binding( get: { product.imageComments[filename] ?? "" }, set: { newValue in if newValue.isEmpty { product.imageComments.removeValue(forKey: filename) } else { product.imageComments[filename] = newValue } } )) .font(.body) .frame(minHeight: 80, maxHeight: 120) .overlay( RoundedRectangle(cornerRadius: 6) .stroke(Color.secondary.opacity(0.2), lineWidth: 1) ) Text("e.g. Close-up of front pocket print, macro tie-dye spiral, or back hem detail...") .font(.caption) .foregroundStyle(.tertiary) Text("This note guides AI visual perspective during Groovy Studio analysis.") .font(.caption) .foregroundStyle(.secondary) } .frame(width: 420) .padding(.horizontal, 12) .padding(.bottom, 12) } .padding(.top, 12) } } struct IdentifiableString: Identifiable { let id = UUID() let value: String } struct ProductOrganizationSection: View { let rootCategories: [Category] let allTags: [Tag] let primaryCategory: Category? let primaryCategoryName: String @Binding var activeTagStrings: [String] @Binding var showingTagBrowser: Bool @Binding var showingNewCategoryAlert: Bool @Binding var newCategoryName: String let onAssignPrimaryCategory: (Category) -> Void let onJumpToCategory: (Category) -> Void let onCategoryChanged: () -> Void let onAddCategory: () -> Void let onDeleteTag: (Tag) -> Void @State private var tagSearchText: String = "" private var filteredTags: [Tag] { let sorted = allTags.sorted { $0.name.localizedStandardCompare($1.name) == .orderedAscending } let query = tagSearchText.trimmingCharacters(in: .whitespacesAndNewlines) if query.isEmpty { return sorted } return sorted.filter { $0.name.localizedCaseInsensitiveContains(query) } } var body: some View { GroupBox("Organization") { VStack(alignment: .leading, spacing: 12) { LabeledContent("Category") { HStack { Menu(primaryCategoryName) { CategoryMenu(categories: rootCategories) { category in onAssignPrimaryCategory(category) onCategoryChanged() } } if let primaryCategory { Button("Jump to Category", systemImage: "arrow.right.circle") { onJumpToCategory(primaryCategory) } .labelStyle(.iconOnly) .buttonStyle(.borderless) } Button("Add Category", systemImage: "plus") { showingNewCategoryAlert = true } .buttonStyle(.bordered) .controlSize(.small) } } HStack { Text("Tags") .foregroundStyle(.secondary) Spacer() Button("Browse Tags", systemImage: "tag") { showingTagBrowser.toggle() } .buttonStyle(.bordered) .popover(isPresented: $showingTagBrowser) { VStack(alignment: .leading, spacing: 12) { Text("Existing Tags") .font(.headline) TextField("Search tags...", text: $tagSearchText) .textFieldStyle(.roundedBorder) List(filteredTags) { tag in HStack { Text(tag.name) Spacer() if activeTagStrings.contains(tag.name) { Image(systemName: "checkmark") .foregroundStyle(.secondary) } else { Button("Add", systemImage: "plus") { activeTagStrings.append(tag.name) } .labelStyle(.iconOnly) .buttonStyle(.borderless) } Button(role: .destructive) { onDeleteTag(tag) } label: { Label("Delete Tag", systemImage: "trash") } .labelStyle(.iconOnly) .buttonStyle(.borderless) } } .scrollIndicators(.hidden) } .padding() .frame(minWidth: 250, minHeight: 300) } } WrappingTokenField(tokens: $activeTagStrings, placeholder: "Add tag", suggestions: allTags.map(\.name)) } .textFieldStyle(.roundedBorder) } .alert("New Category", isPresented: $showingNewCategoryAlert) { TextField("Category Name", text: $newCategoryName) Button("Cancel", role: .cancel) { newCategoryName = "" } Button("Add", action: onAddCategory) } message: { Text("Create a category and assign it to this product.") } } } struct CategoryMenu: View { let categories: [Category] let action: (Category) -> Void var body: some View { ForEach(sortedCategories) { category in if let subCategories = sortedSubcategories(for: category), !subCategories.isEmpty { Menu(category.name) { CategoryMenu(categories: subCategories, action: action) } } else { Button(category.name) { action(category) } } } } private var sortedCategories: [Category] { categories.sorted { $0.name.localizedStandardCompare($1.name) == .orderedAscending } } private func sortedSubcategories(for category: Category) -> [Category]? { category.subCategories? .sorted { $0.name.localizedStandardCompare($1.name) == .orderedAscending } } } struct NewProductWizardView: View { let rootCategories: [Category] @Binding var selectedCategory: Category? @Binding var isOneOfOne: Bool let onCancel: () -> Void let onCreate: () -> Void @State private var selectedPath: [Category] = [] var body: some View { VStack(alignment: .leading, spacing: 16) { Text("Create New Product") .font(.title2) .bold() Text("Category") .bold() ScrollView(.horizontal) { HStack(alignment: .top) { WizardCategoryColumn( title: "Root Categories", categories: rootCategories, selectedCategory: selectedPath.first, onSelect: { category in selectedPath = [category] } ) ForEach(0.. [Category]? { category.subCategories? .sorted { $0.name.localizedStandardCompare($1.name) == .orderedAscending } } } struct QuickStartChooserView: View { let templates: [ProductTemplate] let onChooseTemplate: (ProductTemplate, String?) -> Void let onDeleteTemplate: (ProductTemplate) -> Void let onChooseCustomProduct: () -> Void var body: some View { NavigationStack { List { Section("Templates") { if sortedTemplates.isEmpty { Text("No saved templates yet.") .foregroundStyle(.secondary) } else { ForEach(sortedTemplates) { template in QuickStartTemplateRow( template: template, onChooseTemplate: onChooseTemplate ) .swipeActions { Button("Delete", role: .destructive) { onDeleteTemplate(template) } } } } } Section("Custom") { Button { onChooseCustomProduct() } label: { Label("Custom Product (Browse Taxonomy)", systemImage: "square.grid.3x3.topleft.filled") } .buttonStyle(.borderedProminent) } } .navigationTitle("Quick Start") } .frame(minWidth: 420, minHeight: 360) } private var sortedTemplates: [ProductTemplate] { templates.sorted { $0.name.localizedStandardCompare($1.name) == .orderedAscending } } } struct QuickStartTemplateRow: View { let template: ProductTemplate let onChooseTemplate: (ProductTemplate, String?) -> Void var body: some View { VStack(alignment: .leading, spacing: 6) { Text(template.name) .bold() if let categoryPath = template.category?.fullPath { Text(categoryPath) .font(.caption) .foregroundStyle(.secondary) } else if let categoryName = template.category?.name { Text(categoryName) .font(.caption) .foregroundStyle(.secondary) } if sizeGroup != nil, !sortedSizeOptions.isEmpty { ScrollView(.horizontal, showsIndicators: false) { HStack(spacing: 6) { ForEach(sortedSizeOptions, id: \.id) { option in Button { onChooseTemplate(template, option.value) } label: { Text(option.value) .font(.caption) .fontWeight(.medium) .padding(.horizontal, 8) .padding(.vertical, 4) .background(Color.accentColor.opacity(0.15)) .foregroundStyle(Color.accentColor) .clipShape(.rect(cornerRadius: 6)) } .buttonStyle(.plain) } } .padding(.vertical, 2) } } else { Button { onChooseTemplate(template, nil) } label: { HStack { Text("Create Product") .font(.caption) .fontWeight(.medium) Spacer() } .contentShape(Rectangle()) } .buttonStyle(.plain) } } .padding(.vertical, 4) } private var sizeGroup: AttributeGroup? { guard let category = template.category else { return nil } return category.allAttributeGroups.first { group in group.name.localizedCaseInsensitiveContains("Size") || (group.displayName?.localizedCaseInsensitiveContains("Size") ?? false) } } private var sortedSizeOptions: [AttributeOption] { guard let sizeGroup = sizeGroup else { return [] } return sortedAttributeOptions(sizeGroup.options ?? [], strategy: sizeGroup.sortStrategy) } } struct WizardCategoryColumn: View { let title: String let categories: [Category] let selectedCategory: Category? let onSelect: (Category) -> Void var body: some View { ScrollView(.vertical) { VStack(alignment: .leading) { Text(title) .bold() ForEach(sortedCategories) { category in Button { onSelect(category) } label: { HStack { Text(category.name) Spacer() if !(category.subCategories ?? []).isEmpty { Image(systemName: "chevron.right") .foregroundStyle(.secondary) } } .padding(.vertical, 6) .padding(.horizontal, 8) .frame(maxWidth: .infinity, alignment: .leading) .background(isSelected(category) ? Color.accentColor.opacity(0.2) : Color.clear) .clipShape(.rect(cornerRadius: 8)) } .buttonStyle(.plain) .focusable(false) } } .frame(width: 220, alignment: .topLeading) } .frame(width: 220) .frame(minHeight: 220) } private var sortedCategories: [Category] { categories.sorted { $0.name.localizedStandardCompare($1.name) == .orderedAscending } } private func isSelected(_ category: Category) -> Bool { selectedCategory?.id == category.id } } struct OneOfOnePropertiesSection: View { @Bindable var product: ApparelProduct let attributeGroups: [AttributeGroup] let onJumpToGroup: (AttributeGroup) -> Void let highlightedStyles: Set let promotedStyles: Set var body: some View { VStack(alignment: .leading, spacing: 12) { if attributeGroups.isEmpty { Text("No category properties available.") .foregroundStyle(.secondary) } else { ForEach(attributeGroups) { group in OneOfOnePropertyRow( product: product, group: group, onJumpToGroup: onJumpToGroup, highlightedStyles: highlightedStyles, promotedStyles: promotedStyles ) } } } } } struct OneOfOnePropertyRow: View { @Environment(\.modelContext) private var modelContext @Bindable var product: ApparelProduct let group: AttributeGroup let onJumpToGroup: (AttributeGroup) -> Void let highlightedStyles: Set let promotedStyles: Set @State private var newPopupOption = "" var body: some View { VStack(alignment: .leading, spacing: 8) { HStack { Text(group.displayName ?? group.name) .bold() if isPropertyUnset { HStack(spacing: 4) { Image(systemName: "exclamationmark.triangle.fill") .foregroundStyle(.orange) Text("Required / Unset") .font(.caption) .foregroundStyle(.orange) } } Button("Jump to Group", systemImage: "arrow.right.circle") { onJumpToGroup(group) } .labelStyle(.iconOnly) .buttonStyle(.borderless) } switch group.displayStyle { case .tags: WrappingTokenField(tokens: tagTokensBinding, placeholder: "Add \(group.displayName ?? group.name)", suggestions: group.options?.map(\.value) ?? []) case .radio: OneOfOneRadioOptionsView( options: sortedOptions, selectedValue: selectedValueBinding ) case .checkbox: OneOfOneCheckboxOptionsView( options: sortedOptions, selectedValues: checkboxValuesBinding, highlightedStyles: highlightedStyles, promotedStyles: promotedStyles ) case .popup: HStack { OneOfOnePopupOptionsView( mainOptions: mainPopupOptions, otherOptions: otherPopupOptions, selectedValue: selectedValueBinding ) TextField("Add option", text: $newPopupOption) .textFieldStyle(.roundedBorder) .frame(maxWidth: 180) Button("Add") { addPopupOption() } .buttonStyle(.bordered) .controlSize(.small) .disabled(newPopupOption.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) Button("Clear") { selectedValueBinding.wrappedValue = "" } .buttonStyle(.bordered) .controlSize(.small) .disabled(selectedValueBinding.wrappedValue.isEmpty) } } } } private var isPropertyUnset: Bool { let selectedValue = product.selectedAttributes[group.name]?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" return selectedValue.isEmpty } private var sortedOptions: [AttributeOption] { sortedAttributeOptions(group.options ?? [], strategy: group.sortStrategy) } private var mainPopupOptions: [String] { sortedOptions .map(\.value) .filter { !$0.hasPrefix(".") } } private var otherPopupOptions: [String] { sortedOptions.compactMap { option in guard option.value.hasPrefix(".") else { return nil } return String(option.value.dropFirst()) } } private var selectedValueBinding: Binding { Binding( get: { product.selectedAttributes[group.name] ?? "" }, set: { newValue in if newValue.isEmpty { product.selectedAttributes.removeValue(forKey: group.name) } else { product.selectedAttributes[group.name] = newValue } } ) } private var tagTokensBinding: Binding<[String]> { Binding( get: { let storedValue = product.selectedAttributes[group.name] ?? "" return storedValue .split(separator: ",") .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } .filter { !$0.isEmpty } }, set: { newTokens in let normalizedTokens = newTokens .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } .filter { !$0.isEmpty } if normalizedTokens.isEmpty { product.selectedAttributes.removeValue(forKey: group.name) } else { product.selectedAttributes[group.name] = normalizedTokens.joined(separator: ", ") } } ) } private var checkboxValuesBinding: Binding<[String]> { Binding( get: { let storedValue = product.selectedAttributes[group.name] ?? "" return storedValue .split(separator: ",") .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } .filter { !$0.isEmpty } }, set: { newValues in let normalizedValues = newValues .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } .filter { !$0.isEmpty } if normalizedValues.isEmpty { product.selectedAttributes.removeValue(forKey: group.name) } else { product.selectedAttributes[group.name] = normalizedValues.joined(separator: ", ") } } ) } private func addPopupOption() { let trimmedValue = newPopupOption.trimmingCharacters(in: .whitespacesAndNewlines) guard !trimmedValue.isEmpty else { return } let existingOptions = group.options ?? [] guard !existingOptions.contains(where: { $0.value == trimmedValue }) else { product.selectedAttributes[group.name] = trimmedValue newPopupOption = "" return } let option = AttributeOption( value: trimmedValue, orderIndex: existingOptions.count, group: group ) modelContext.insert(option) group.options = existingOptions + [option] product.selectedAttributes[group.name] = trimmedValue newPopupOption = "" guard let rootPath = PreferencesManager.shared.get(for: "taxonomy_root_path"), !rootPath.isEmpty else { return } TaxonomySyncManager().pushToFinder(rootURL: URL(filePath: rootPath), context: modelContext) } } struct OneOfOneRadioOptionsView: View { let options: [AttributeOption] @Binding var selectedValue: String var body: some View { VStack(alignment: .leading, spacing: 12) { ForEach(groupedSubgroupKeys, id: \.self) { subgroup in VStack(alignment: .leading, spacing: 8) { if let subgroup { Text(subgroup) .font(.caption) .bold() .foregroundStyle(.secondary) } FlowLayout { ForEach(optionsBySubgroup[subgroup] ?? []) { option in Button { if selectedValue == option.value { selectedValue = "" } else { selectedValue = option.value } } label: { HStack(spacing: 6) { Image(systemName: selectedValue == option.value ? "largecircle.fill.circle" : "circle") Text(option.value) } } .buttonStyle(.bordered) } } } .padding(.vertical, subgroup == groupedSubgroupKeys.first ? 0 : 4) } } } private var optionsBySubgroup: [String?: [AttributeOption]] { Dictionary(grouping: options) { normalizedSubgroup($0.subgroup) } } private var groupedSubgroupKeys: [String?] { Set(options.map { normalizedSubgroup($0.subgroup) }).sorted(by: subgroupSort) } } fileprivate func sortedAttributeOptions(_ options: [AttributeOption], strategy: SortStrategy) -> [AttributeOption] { switch strategy { case .strict: options.sorted { $0.orderIndex < $1.orderIndex } case .alphabetical: options.sorted { $0.value.localizedStandardCompare($1.value) == .orderedAscending } case .numeric: options.sorted { lhs, rhs in if let lhsValue = Double(lhs.value), let rhsValue = Double(rhs.value) { return lhsValue < rhsValue } return lhs.value.localizedStandardCompare(rhs.value) == .orderedAscending } } } struct OneOfOneCheckboxOptionsView: View { let options: [AttributeOption] @Binding var selectedValues: [String] let highlightedStyles: Set let promotedStyles: Set var body: some View { VStack(alignment: .leading, spacing: 12) { ForEach(groupedSubgroupKeys, id: \.self) { subgroup in VStack(alignment: .leading, spacing: 8) { if let subgroup { Text(subgroup) .font(.caption) .bold() .foregroundStyle(.secondary) } FlowLayout { ForEach(optionsBySubgroup[subgroup] ?? []) { option in let isPromoted = promotedStyles.contains(option.value) let isHighlighted = highlightedStyles.contains(option.value) && !isPromoted Button { toggleSelection(for: option.value) } label: { HStack(spacing: 6) { Image(systemName: selectedValues.contains(option.value) ? "checkmark.square.fill" : "square") Text(option.value) if isPromoted { Text("🌟 New to Taxonomy") .font(.caption2) .fontWeight(.medium) .padding(.horizontal, 6) .padding(.vertical, 2) .background(Color.orange.opacity(0.15)) .foregroundStyle(Color.orange) .clipShape(Capsule()) .overlay( Capsule() .stroke(Color.orange.opacity(0.4), lineWidth: 1) ) } else if isHighlighted { Text("✨ Applied") .font(.caption2) .fontWeight(.medium) .padding(.horizontal, 6) .padding(.vertical, 2) .background(Color.green.opacity(0.15)) .foregroundStyle(Color.green) .clipShape(Capsule()) .overlay( Capsule() .stroke(Color.green.opacity(0.4), lineWidth: 1) ) } } } .buttonStyle(.bordered) .overlay( RoundedRectangle(cornerRadius: 6) .stroke( isPromoted ? Color.orange.opacity(0.6) : (isHighlighted ? Color.green.opacity(0.4) : Color.clear), lineWidth: isPromoted ? 2 : (isHighlighted ? 1 : 0) ) ) } } } .padding(.vertical, subgroup == groupedSubgroupKeys.first ? 0 : 4) } } } private var optionsBySubgroup: [String?: [AttributeOption]] { Dictionary(grouping: options) { normalizedSubgroup($0.subgroup) } } private var groupedSubgroupKeys: [String?] { Set(options.map { normalizedSubgroup($0.subgroup) }).sorted(by: subgroupSort) } private func toggleSelection(for value: String) { var nextValues = selectedValues if nextValues.contains(value) { nextValues.removeAll { $0 == value } } else { nextValues.append(value) } selectedValues = nextValues } } private func normalizedSubgroup(_ subgroup: String?) -> String? { guard let subgroup else { return nil } let trimmedSubgroup = subgroup.trimmingCharacters(in: .whitespacesAndNewlines) return trimmedSubgroup.isEmpty ? nil : trimmedSubgroup } private func subgroupSort(_ lhs: String?, _ rhs: String?) -> Bool { switch (lhs, rhs) { case (nil, nil): return false case (nil, _): return true case (_, nil): return false case let (left?, right?): return left.localizedStandardCompare(right) == .orderedAscending } } struct OneOfOnePopupOptionsView: View { let mainOptions: [String] let otherOptions: [String] @Binding var selectedValue: String var body: some View { Menu { ForEach(mainOptions, id: \.self) { option in Button(option) { selectedValue = option } } if !otherOptions.isEmpty { Menu("Other") { ForEach(otherOptions, id: \.self) { option in Button(option) { selectedValue = option } } } } } label: { HStack { Text(selectedValue.isEmpty ? "Select..." : selectedValue) Spacer() Image(systemName: "chevron.up.chevron.down") .imageScale(.small) } .padding(.horizontal, 12) .padding(.vertical, 8) .background(.quaternary.opacity(0.5)) .clipShape(.rect(cornerRadius: 8)) } } } struct ProductFormRow: View { let label: String @ViewBuilder let content: Content var body: some View { LabeledContent { content } label: { Text(label) .foregroundStyle(.secondary) } } } struct CurrencyTextField: View { let title: String @Binding var cents: Int @State private var textValue = "" @FocusState private var isFocused: Bool var body: some View { TextField(title, text: $textValue) .focused($isFocused) .multilineTextAlignment(.leading) .onAppear { syncTextValue() } .onChange(of: cents, initial: false) { _, _ in guard !isFocused else { return } syncTextValue() } .onChange(of: isFocused, initial: false) { _, focused in if focused { return } commitValue() } .onSubmit { commitValue() } } private func syncTextValue() { textValue = format(cents: cents) } private func commitValue() { let sanitizedValue = textValue.replacing(",", with: ".").trimmingCharacters(in: .whitespacesAndNewlines) guard !sanitizedValue.isEmpty else { cents = 0 syncTextValue() return } guard let amount = Double(sanitizedValue) else { syncTextValue() return } cents = Int((amount * 100).rounded()) syncTextValue() } private func format(cents: Int) -> String { let amount = Decimal(cents) / 100 return amount.formatted(.number.precision(.fractionLength(2))) } } private extension Category { func isDescendant(of ancestor: Category) -> Bool { var current = parentCategory while let parent = current { if parent.id == ancestor.id { return true } current = parent.parentCategory } return false } } struct ImageReorderDelegate: DropDelegate { let item: String @Binding var items: [String] @Binding var draggedItem: String? func dropEntered(info: DropInfo) { guard let draggedItem, draggedItem != item, let from = items.firstIndex(of: draggedItem), let to = items.firstIndex(of: item) else { return } withAnimation { items.move(fromOffsets: IndexSet(integer: from), toOffset: to > from ? to + 1 : to) } } func performDrop(info: DropInfo) -> Bool { draggedItem = nil return true } } struct StorefrontKeyValuePair: Identifiable { let id = UUID() var key: String var value: String } struct SettingsView: View { @Environment(\.modelContext) private var modelContext @Query private var personas: [AIPersona] @Query private var contentBlocks: [StoreContentBlock] @AppStorage("ai_provider") private var aiProvider: String = "ollama" @AppStorage("storefront_domain") private var storefrontDomain: String = "" @State private var geminiKey: String = "" @State private var ollamaModel: String = "" @State private var availableModels: [String] = [] @State private var isLoadingModels = false @State private var taxonomyRootPath: String = "" @State private var selectedPersona: AIPersona? @State private var personaTitle: String = "" @State private var personaPromptText: String = "" @State private var personaIsDefault = false @State private var selectedContentBlock: StoreContentBlock? @State private var storefrontStoreName: String = "" @State private var storefrontAddress: String = "" @State private var storefrontHours: String = "" @State private var storefrontFacebook: String = "" @State private var storefrontInstagram: String = "" @State private var storefrontTiktok: String = "" @State private var storefrontCopyrightYear: String = "" @State private var storefrontTermsURL: String = "" @State private var storefrontPrivacyURL: String = "" @State private var storefrontEmails: [StorefrontKeyValuePair] = [] @State private var storefrontPhones: [StorefrontKeyValuePair] = [] var body: some View { TabView { APIKeySettingsTab( aiProvider: $aiProvider, storefrontDomain: $storefrontDomain, geminiKey: $geminiKey, ollamaModel: $ollamaModel, availableModels: availableModels, isLoadingModels: isLoadingModels, onAppear: fetchAvailableModels, onSave: saveAPIKey ) .tabItem { Label("API Key", systemImage: "key.fill") } StorefrontSettingsTab( storeName: $storefrontStoreName, address: $storefrontAddress, hours: $storefrontHours, emails: $storefrontEmails, phones: $storefrontPhones, facebook: $storefrontFacebook, instagram: $storefrontInstagram, tiktok: $storefrontTiktok, copyrightYear: $storefrontCopyrightYear, termsURL: $storefrontTermsURL, privacyURL: $storefrontPrivacyURL, onSave: saveStorefrontSettings ) .tabItem { Label("Storefront", systemImage: "storefront.fill") } AIPersonasSettingsTab( personas: personas, selectedPersona: $selectedPersona, personaTitle: $personaTitle, personaPromptText: $personaPromptText, personaIsDefault: $personaIsDefault, onDelete: deletePersona, onMakeDefault: makeDefaultPersona, onSubmit: submitPersona, onCancel: clearPersonaForm ) .tabItem { Label("AI Personas", systemImage: "sparkles.rectangle.stack") } TaxonomySyncSettingsTab( taxonomyRootPath: $taxonomyRootPath, onChooseDirectory: chooseTaxonomyDirectory ) .tabItem { Label("Taxonomy Sync", systemImage: "folder.badge.gearshape") } } .frame(width: 560, height: 480) .onAppear { JSONExporter.importStoreInfo(context: modelContext) geminiKey = PreferencesManager.shared.get(for: "gemini_api_key") ?? "" ollamaModel = PreferencesManager.shared.get(for: "ollama_model") ?? "llama3.1:8b" taxonomyRootPath = PreferencesManager.shared.get(for: "taxonomy_root_path") ?? "" loadStorefrontSettingsFromPreferences() } .onReceive(NotificationCenter.default.publisher(for: Notification.Name("local.com.factory.data.updated"))) { _ in JSONExporter.importStoreInfo(context: modelContext) loadStorefrontSettingsFromPreferences() } .onReceive(NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification)) { _ in JSONExporter.importStoreInfo(context: modelContext) loadStorefrontSettingsFromPreferences() } .onChange(of: selectedPersona, initial: false) { _, newPersona in if let newPersona { personaTitle = newPersona.title personaPromptText = newPersona.promptText personaIsDefault = newPersona.isDefault } else { clearPersonaForm() } } } private func loadStorefrontSettingsFromPreferences() { storefrontStoreName = PreferencesManager.shared.get(for: "store_name") ?? PreferencesManager.shared.get(for: "storefront_store_name") ?? "" storefrontAddress = PreferencesManager.shared.get(for: "storefront_address") ?? PreferencesManager.shared.get(for: "address") ?? "" storefrontHours = PreferencesManager.shared.get(for: "storefront_hours") ?? PreferencesManager.shared.get(for: "hours") ?? "" storefrontFacebook = PreferencesManager.shared.get(for: "storefront_facebook") ?? PreferencesManager.shared.get(for: "facebook") ?? "" storefrontInstagram = PreferencesManager.shared.get(for: "storefront_instagram") ?? PreferencesManager.shared.get(for: "instagram") ?? "" storefrontTiktok = PreferencesManager.shared.get(for: "storefront_tiktok") ?? PreferencesManager.shared.get(for: "tiktok") ?? "" storefrontCopyrightYear = PreferencesManager.shared.get(for: "storefront_copyright_year") ?? PreferencesManager.shared.get(for: "copyright_year") ?? PreferencesManager.shared.get(for: "storefront_copyrightYear") ?? PreferencesManager.shared.get(for: "copyrightYear") ?? "" storefrontTermsURL = PreferencesManager.shared.get(for: "storefront_terms_url") ?? PreferencesManager.shared.get(for: "terms_url") ?? PreferencesManager.shared.get(for: "storefront_termsURL") ?? PreferencesManager.shared.get(for: "termsURL") ?? "" storefrontPrivacyURL = PreferencesManager.shared.get(for: "storefront_privacy_url") ?? PreferencesManager.shared.get(for: "privacy_url") ?? PreferencesManager.shared.get(for: "storefront_privacyURL") ?? PreferencesManager.shared.get(for: "privacyURL") ?? "" let emailsRaw = PreferencesManager.shared.get(for: "storefront_emails") ?? PreferencesManager.shared.get(for: "emails") let phonesRaw = PreferencesManager.shared.get(for: "storefront_phones") ?? PreferencesManager.shared.get(for: "phones") storefrontEmails = decodeDictionary(from: emailsRaw) .map { StorefrontKeyValuePair(key: $0.key, value: $0.value) } .sorted { $0.key.localizedStandardCompare($1.key) == .orderedAscending } storefrontPhones = decodeDictionary(from: phonesRaw) .map { StorefrontKeyValuePair(key: $0.key, value: $0.value) } .sorted { $0.key.localizedStandardCompare($1.key) == .orderedAscending } } private func saveAPIKey() { PreferencesManager.shared.set(geminiKey, for: "gemini_api_key") PreferencesManager.shared.set(ollamaModel, for: "ollama_model") } @MainActor private func fetchAvailableModels() { Task { isLoadingModels = true defer { isLoadingModels = false } do { struct OllamaTagsResponse: Decodable { struct OllamaModel: Decodable { let name: String } let models: [OllamaModel] } let url = URL(string: "http://localhost:11434/api/tags")! let (data, _) = try await URLSession.shared.data(from: url) let response = try JSONDecoder().decode(OllamaTagsResponse.self, from: data) var modelNames = response.models.map(\.name) if !ollamaModel.isEmpty, !modelNames.contains(ollamaModel) { modelNames.append(ollamaModel) } availableModels = modelNames.sorted { $0.localizedStandardCompare($1) == .orderedAscending } } catch { availableModels = [] } } } private func chooseTaxonomyDirectory() { let panel = NSOpenPanel() panel.canChooseFiles = false panel.canChooseDirectories = true panel.allowsMultipleSelection = false guard panel.runModal() == .OK, let url = panel.urls.first else { return } taxonomyRootPath = url.path PreferencesManager.shared.set(url.path, for: "taxonomy_root_path") } private func deletePersona(_ persona: AIPersona) { modelContext.delete(persona) if selectedPersona?.id == persona.id { clearPersonaForm() } } private func makeDefaultPersona(_ persona: AIPersona) { for existingPersona in personas { existingPersona.isDefault = existingPersona.id == persona.id } if selectedPersona?.id == persona.id { personaIsDefault = true } } private func submitPersona() { guard !personaTitle.isEmpty, !personaPromptText.isEmpty else { return } if personaIsDefault { for existingPersona in personas { existingPersona.isDefault = false } } if let selectedPersona { selectedPersona.title = personaTitle selectedPersona.promptText = personaPromptText selectedPersona.isDefault = personaIsDefault } else { let persona = AIPersona( title: personaTitle, promptText: personaPromptText, isDefault: personaIsDefault ) modelContext.insert(persona) } clearPersonaForm() } private func clearPersonaForm() { selectedPersona = nil personaTitle = "" personaPromptText = "" personaIsDefault = false } private func saveStorefrontSettings() { PreferencesManager.shared.set(storefrontStoreName, for: "store_name") PreferencesManager.shared.set(storefrontAddress, for: "storefront_address") PreferencesManager.shared.set(storefrontHours, for: "storefront_hours") PreferencesManager.shared.set(storefrontFacebook, for: "storefront_facebook") PreferencesManager.shared.set(storefrontInstagram, for: "storefront_instagram") PreferencesManager.shared.set(storefrontTiktok, for: "storefront_tiktok") PreferencesManager.shared.set(storefrontCopyrightYear, for: "storefront_copyright_year") PreferencesManager.shared.set(storefrontTermsURL, for: "storefront_terms_url") PreferencesManager.shared.set(storefrontPrivacyURL, for: "storefront_privacy_url") var emailDict: [String: String] = [:] for pair in storefrontEmails { let key = pair.key.trimmingCharacters(in: .whitespacesAndNewlines) if !key.isEmpty { emailDict[key] = pair.value } } if let data = try? JSONEncoder().encode(emailDict), let jsonString = String(data: data, encoding: .utf8) { PreferencesManager.shared.set(jsonString, for: "storefront_emails") } var phoneDict: [String: String] = [:] for pair in storefrontPhones { let key = pair.key.trimmingCharacters(in: .whitespacesAndNewlines) if !key.isEmpty { phoneDict[key] = pair.value } } if let data = try? JSONEncoder().encode(phoneDict), let jsonString = String(data: data, encoding: .utf8) { PreferencesManager.shared.set(jsonString, for: "storefront_phones") } JSONExporter.publishProducts(context: modelContext) } private func decodeDictionary(from jsonString: String?) -> [String: String] { guard let jsonString = jsonString, let data = jsonString.data(using: .utf8) else { return [:] } return (try? JSONDecoder().decode([String: String].self, from: data)) ?? [:] } } struct StorefrontSettingsTab: View { @Binding var storeName: String @Binding var address: String @Binding var hours: String @Binding var emails: [StorefrontKeyValuePair] @Binding var phones: [StorefrontKeyValuePair] @Binding var facebook: String @Binding var instagram: String @Binding var tiktok: String @Binding var copyrightYear: String @Binding var termsURL: String @Binding var privacyURL: String let onSave: () -> Void var body: some View { ScrollView { Form { Section("Contact Info") { TextField("Store Name", text: $storeName) TextField("Address", text: $address, axis: .vertical) .lineLimit(2...4) TextField("Hours", text: $hours, axis: .vertical) .lineLimit(2...4) } Section("Emails") { ForEach($emails) { $pair in HStack { TextField("Label (e.g., Support)", text: $pair.key) .textFieldStyle(.roundedBorder) TextField("Email Address", text: $pair.value) .textFieldStyle(.roundedBorder) Button(role: .destructive) { emails.removeAll { $0.id == pair.id } } label: { Image(systemName: "trash") } .buttonStyle(.borderless) } } Button("Add Email Pair", systemImage: "plus.circle.fill") { emails.append(StorefrontKeyValuePair(key: "", value: "")) } } Section("Phone Numbers") { ForEach($phones) { $pair in HStack { TextField("Label (e.g., Sales)", text: $pair.key) .textFieldStyle(.roundedBorder) TextField("Phone Number", text: $pair.value) .textFieldStyle(.roundedBorder) Button(role: .destructive) { phones.removeAll { $0.id == pair.id } } label: { Image(systemName: "trash") } .buttonStyle(.borderless) } } Button("Add Phone Pair", systemImage: "plus.circle.fill") { phones.append(StorefrontKeyValuePair(key: "", value: "")) } } Section("Social Links") { TextField("Facebook URL", text: $facebook) .textFieldStyle(.roundedBorder) TextField("Instagram URL", text: $instagram) .textFieldStyle(.roundedBorder) TextField("TikTok URL", text: $tiktok) .textFieldStyle(.roundedBorder) } Section("Legal") { TextField("Copyright Year", text: $copyrightYear) .textFieldStyle(.roundedBorder) TextField("Terms URL", text: $termsURL) .textFieldStyle(.roundedBorder) TextField("Privacy URL", text: $privacyURL) .textFieldStyle(.roundedBorder) } HStack { Spacer() Button("Save Settings", action: onSave) .buttonStyle(.borderedProminent) } } .formStyle(.grouped) } .padding(10) } } struct APIKeySettingsTab: View { @Binding var aiProvider: String @Binding var storefrontDomain: String @Binding var geminiKey: String @Binding var ollamaModel: String let availableModels: [String] let isLoadingModels: Bool let onAppear: () -> Void let onSave: () -> Void var body: some View { VStack(alignment: .leading, spacing: 20) { Text("App Settings") .font(.headline) Picker("AI Provider", selection: $aiProvider) { Text("Local (Ollama)").tag("ollama") Text("Cloud (Gemini 3.8 Flash)").tag("gemini-3.8-flash") Text("Cloud (Gemini 3.7 Flash)").tag("gemini-3.7-flash") Text("Cloud (Gemini 3.5 Flash)").tag("gemini-3.5-flash") Text("Cloud (Gemini 3.5 Flash Lite)").tag("gemini-3.5-flash-lite") } TextField("Storefront Domain (e.g., thegroovypanda.com)", text: $storefrontDomain) .textFieldStyle(.roundedBorder) TextField("Gemini API Key", text: $geminiKey) .textFieldStyle(.roundedBorder) HStack { if isLoadingModels { ProgressView() Text("Loading models...") .foregroundStyle(.secondary) } else if !availableModels.isEmpty { Picker("Ollama Model", selection: $ollamaModel) { ForEach(availableModels, id: \.self) { model in Text(model).tag(model) } } } else { TextField( "Ollama Model (e.g., llama3.1:8b or llava:1.6-mistral)", text: $ollamaModel ) .textFieldStyle(.roundedBorder) } } HStack { Spacer() Button("Save Settings", action: onSave) .buttonStyle(.borderedProminent) } } .padding(20) .onAppear(perform: onAppear) } } struct AIPersonasSettingsTab: View { let personas: [AIPersona] @Binding var selectedPersona: AIPersona? @Binding var personaTitle: String @Binding var personaPromptText: String @Binding var personaIsDefault: Bool let onDelete: (AIPersona) -> Void let onMakeDefault: (AIPersona) -> Void let onSubmit: () -> Void let onCancel: () -> Void var body: some View { VStack(alignment: .leading, spacing: 16) { List(personas, selection: $selectedPersona) { persona in HStack { VStack(alignment: .leading) { Text(persona.title) .bold() Text(persona.promptText) .lineLimit(2) .foregroundStyle(.secondary) } Spacer() if persona.isDefault { Text("Default") .font(.caption) .bold() .padding(.horizontal, 8) .padding(.vertical, 4) .background(.blue) .foregroundStyle(.white) .clipShape(.rect(cornerRadius: 4)) } else { Button("Make Default") { onMakeDefault(persona) } .buttonStyle(.bordered) } Button(role: .destructive) { onDelete(persona) } label: { Image(systemName: "trash") } .buttonStyle(.plain) } .tag(persona) .contextMenu { Button("Delete", role: .destructive) { onDelete(persona) } } } VStack(alignment: .leading, spacing: 12) { TextField("Persona Title", text: $personaTitle) .textFieldStyle(.roundedBorder) TextField("Prompt Text", text: $personaPromptText, axis: .vertical) .textFieldStyle(.roundedBorder) .lineLimit(3...6) Toggle("Set as Default", isOn: $personaIsDefault) HStack { Button("Cancel", action: onCancel) Spacer() Button(selectedPersona == nil ? "Add Template" : "Save Changes", action: onSubmit) .buttonStyle(.borderedProminent) } } } .padding(20) } } struct TaxonomySyncSettingsTab: View { @Binding var taxonomyRootPath: String let onChooseDirectory: () -> Void var body: some View { VStack(alignment: .leading, spacing: 20) { Text("Taxonomy Sync") .font(.headline) VStack(alignment: .leading, spacing: 8) { Text("Current Root Folder") .foregroundStyle(.secondary) Text(taxonomyRootPath.isEmpty ? "No folder selected" : taxonomyRootPath) .textSelection(.enabled) } HStack { Button("Choose Folder", action: onChooseDirectory) .buttonStyle(.borderedProminent) Spacer() } Spacer() } .padding(20) } } struct ArtworkDetailView: View { @Bindable var artwork: Artwork var body: some View { VStack { Form { TextField("SKU", text: $artwork.sku) TextField("Name", text: $artwork.name) TextField("Dimensions", text: $artwork.dimensions) TokenField(tokens: $artwork.mediaCompatibilities, placeholder: "Add compatibility (e.g., Cotton)") TextField("Stock Quantity", value: $artwork.stockQty, format: .number) Section("Media") { HeroImageDropZone( heroImageFilename: $artwork.heroImage, specs: $artwork.specs, sku: artwork.sku ) } Section("Custom Specifications") { ForEach($artwork.specs) { $spec in VStack(spacing: 8) { HStack { TextField("Key", text: $spec.key) .textFieldStyle(.roundedBorder) Button(role: .destructive) { artwork.specs.removeAll { $0.id == spec.id } } label: { Image(systemName: "trash") } .buttonStyle(.borderless) } TextField("Value", text: $spec.value) .textFieldStyle(.roundedBorder) } .padding(.bottom, 8) Divider() } Button("Add Spec", systemImage: "plus.circle.fill") { artwork.specs.append(CustomSpec(key: "", value: "")) } } } .padding() } .navigationTitle(artwork.name.isEmpty ? "Artwork" : artwork.name) } } struct BlankMediaDetailView: View { @Bindable var blank: BlankMedia var body: some View { VStack { Form { TextField("SKU", text: $blank.sku) TextField("Name", text: $blank.name) TextField("Media Type", text: $blank.mediaType) TextField("Style", text: $blank.style) TextField("Color", text: $blank.color) TextField("Size", text: $blank.size) CurrencyTextField(title: "Cost", cents: $blank.costCents) TextField("Stock Quantity", value: $blank.stockQty, format: .number) Section("Media") { HeroImageDropZone( heroImageFilename: $blank.heroImage, specs: $blank.specs, sku: blank.sku ) } Section("Custom Specifications") { ForEach($blank.specs) { $spec in VStack(spacing: 8) { HStack { TextField("Key", text: $spec.key) .textFieldStyle(.roundedBorder) Button(role: .destructive) { blank.specs.removeAll { $0.id == spec.id } } label: { Image(systemName: "trash") } .buttonStyle(.borderless) } TextField("Value", text: $spec.value) .textFieldStyle(.roundedBorder) } .padding(.bottom, 8) Divider() } Button("Add Spec", systemImage: "plus.circle.fill") { blank.specs.append(CustomSpec(key: "", value: "")) } } } .padding() } .navigationTitle(blank.name.isEmpty ? "Blank Media" : blank.name) } } struct HeroImageDropZone: View { @Binding var heroImageFilename: String? @Binding var specs: [CustomSpec] let sku: String @State private var customBackgroundColor: Color = .white @State private var selectedSwatch: (name: String, color: Color)? var body: some View { VStack(alignment: .leading, spacing: 12) { if let heroImageFilename, let image = ImageManager.shared.loadImage(filename: heroImageFilename) { Image(nsImage: image) .interpolation(.high) .resizable() .scaledToFit() .frame(maxWidth: .infinity, minHeight: 180) .background(selectedSwatch?.color ?? customBackgroundColor) .clipShape(.rect(cornerRadius: 8)) Button("Remove Hero Image", role: .destructive) { ImageManager.shared.deleteImage(filename: heroImageFilename) self.heroImageFilename = nil } } else { ZStack { RoundedRectangle(cornerRadius: 8) .strokeBorder(.secondary.opacity(0.5), style: StrokeStyle(lineWidth: 2, dash: [6])) .background(.secondary.opacity(0.05)) .frame(maxWidth: .infinity, minHeight: 180) VStack { Image(systemName: "photo") .font(.title) .foregroundStyle(.secondary) Text("Drop Hero Image Here or CMD+V") .foregroundStyle(.secondary) } } .onDrop(of: [.image], isTargeted: nil) { providers in handleHeroImageDrop(providers: providers) } .focusable() .onPasteCommand(of: [.image]) { providers in _ = handleHeroImageDrop(providers: providers) } } HStack(alignment: .center) { ColorPicker("Background Color", selection: $customBackgroundColor, supportsOpacity: false) .labelsHidden() .onChange(of: customBackgroundColor, initial: false) { _, _ in selectedSwatch = nil } ForEach(garmentPalette, id: \.name) { swatch in Button { selectedSwatch = swatch } label: { Text(swatch.name) .foregroundStyle(swatchForegroundStyle(for: swatch)) .padding(.horizontal, 10) .padding(.vertical, 6) .background(swatch.color) .overlay { Capsule() .strokeBorder(.secondary.opacity(0.6), lineWidth: 1) } .clipShape(.capsule) } .buttonStyle(.plain) } } if let selectedSwatch { HStack { Button("+ Add '\(selectedSwatch.name)' to Excluded Colors") { addSelectedColorToExcludedSpecs() } .buttonStyle(.bordered) Spacer() } } } } private var garmentPalette: [(name: String, color: Color)] { [ ("White", .white), ("Black", .black), ("Gray", .gray), ("Red", .red), ("Orange", .orange), ("Yellow", .yellow), ("Green", .green), ("Blue", .blue), ("Purple", .purple) ] } private func swatchForegroundStyle(for swatch: (name: String, color: Color)) -> Color { switch swatch.name { case "White", "Yellow", "Orange": .black default: .white } } private func addSelectedColorToExcludedSpecs() { guard let selectedSwatch else { return } if let index = specs.firstIndex(where: { $0.key == "Exclude Colors" }) { let existingColors = specs[index].value .split(separator: ",") .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } .filter { !$0.isEmpty } guard !existingColors.contains(selectedSwatch.name) else { return } let updatedColors = existingColors + [selectedSwatch.name] specs[index].value = updatedColors.joined(separator: ", ") } else { specs.append(CustomSpec(key: "Exclude Colors", value: selectedSwatch.name)) } } private func handleHeroImageDrop(providers: [NSItemProvider]) -> Bool { guard !sku.isEmpty else { print("❌ Cannot attach hero image: SKU is empty.") return false } guard providers.contains(where: { $0.hasItemConformingToTypeIdentifier(UTType.image.identifier) || $0.hasItemConformingToTypeIdentifier(UTType.fileURL.identifier) }) else { return false } for provider in providers { Task { await importHeroImage(from: provider) } } return true } @MainActor private func assignHeroImageFilename(_ filename: String) { if let existingFilename = heroImageFilename { ImageManager.shared.deleteImage(filename: existingFilename) } heroImageFilename = filename } private func importHeroImage(from provider: NSItemProvider) async { if let filename = await importHeroImageFile(from: provider) { await MainActor.run { assignHeroImageFilename(filename) } return } if let filename = await importHeroImageData(from: provider) { await MainActor.run { assignHeroImageFilename(filename) } return } if let filename = await importHeroImageObject(from: provider) { await MainActor.run { assignHeroImageFilename(filename) } } } private func importHeroImageFile(from provider: NSItemProvider) async -> String? { if provider.hasItemConformingToTypeIdentifier(UTType.image.identifier) { do { if let fileURL = try await loadFileRepresentation(for: UTType.image.identifier, provider: provider) { return ImageManager.shared.importImageFile(from: fileURL, for: sku) } } catch { print("❌ Hero image file representation failed: \(error)") } } if provider.hasItemConformingToTypeIdentifier(UTType.fileURL.identifier) { do { if let fileURL = try await loadItemURL(for: UTType.fileURL.identifier, provider: provider) { return ImageManager.shared.importImageFile(from: fileURL, for: sku) } } catch { print("❌ Hero image file URL failed: \(error)") } } return nil } private func importHeroImageData(from provider: NSItemProvider) async -> String? { guard provider.hasItemConformingToTypeIdentifier(UTType.image.identifier) else { return nil } do { let data = try await loadDataRepresentation(for: UTType.image.identifier, provider: provider) return ImageManager.shared.saveImageData(data, suggestedType: .image, for: sku) } catch { print("❌ Hero image data representation failed: \(error)") return nil } } private func importHeroImageObject(from provider: NSItemProvider) async -> String? { guard provider.canLoadObject(ofClass: NSImage.self) else { return nil } do { let image = try await loadImageObject(from: provider) return ImageManager.shared.saveImage(image, for: sku) } catch { print("❌ Hero image NSImage failed: \(error)") return nil } } private func loadFileRepresentation(for typeIdentifier: String, provider: NSItemProvider) async throws -> URL? { try await withCheckedThrowingContinuation { continuation in provider.loadFileRepresentation(forTypeIdentifier: typeIdentifier) { url, error in if let error { continuation.resume(throwing: error) } else { continuation.resume(returning: url) } } } } private func loadItemURL(for typeIdentifier: String, provider: NSItemProvider) async throws -> URL? { try await withCheckedThrowingContinuation { continuation in provider.loadItem(forTypeIdentifier: typeIdentifier, options: nil) { item, error in if let error { continuation.resume(throwing: error) } else if let url = item as? URL { continuation.resume(returning: url) } else if let data = item as? Data, let url = URL(dataRepresentation: data, relativeTo: nil) { continuation.resume(returning: url) } else { continuation.resume(returning: nil) } } } } private func loadDataRepresentation(for typeIdentifier: String, provider: NSItemProvider) async throws -> Data { try await withCheckedThrowingContinuation { continuation in provider.loadDataRepresentation(forTypeIdentifier: typeIdentifier) { data, error in if let error { continuation.resume(throwing: error) } else if let data { continuation.resume(returning: data) } else { continuation.resume(throwing: CocoaError(.fileReadUnknown)) } } } } private func loadImageObject(from provider: NSItemProvider) async throws -> NSImage { try await withCheckedThrowingContinuation { continuation in provider.loadObject(ofClass: NSImage.self) { object, error in if let error { continuation.resume(throwing: error) } else if let image = object as? NSImage { continuation.resume(returning: image) } else { continuation.resume(throwing: CocoaError(.coderReadCorrupt)) } } } } } struct FlowLayout: Layout { var horizontalSpacing: CGFloat = 8 var verticalSpacing: CGFloat = 8 func sizeThatFits( proposal: ProposedViewSize, subviews: Subviews, cache: inout () ) -> CGSize { let maxWidth = proposal.width ?? .greatestFiniteMagnitude var currentX: CGFloat = 0 var currentY: CGFloat = 0 var rowHeight: CGFloat = 0 var contentWidth: CGFloat = 0 for subview in subviews { let size = subview.sizeThatFits(.unspecified) let shouldWrap = currentX > 0 && currentX + size.width > maxWidth if shouldWrap { contentWidth = max(contentWidth, currentX - horizontalSpacing) currentX = 0 currentY += rowHeight + verticalSpacing rowHeight = 0 } currentX += size.width + horizontalSpacing rowHeight = max(rowHeight, size.height) } if !subviews.isEmpty { contentWidth = max(contentWidth, currentX - horizontalSpacing) } return CGSize(width: contentWidth, height: currentY + rowHeight) } func placeSubviews( in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout () ) { var currentX = bounds.minX var currentY = bounds.minY var rowHeight: CGFloat = 0 for subview in subviews { let size = subview.sizeThatFits(.unspecified) let shouldWrap = currentX > bounds.minX && currentX + size.width > bounds.maxX if shouldWrap { currentX = bounds.minX currentY += rowHeight + verticalSpacing rowHeight = 0 } subview.place( at: CGPoint(x: currentX, y: currentY), anchor: .topLeading, proposal: ProposedViewSize(size) ) currentX += size.width + horizontalSpacing rowHeight = max(rowHeight, size.height) } } } struct WrappingTokenField: View { @Binding var tokens: [String] let placeholder: String var suggestions: [String] = [] @State private var newTagText: String = "" private var matchingSuggestions: [String] { let query = newTagText.trimmingCharacters(in: .whitespacesAndNewlines) guard !query.isEmpty else { return [] } return suggestions .filter { suggestion in guard !tokens.contains(suggestion) else { return false } let lowerQuery = query.lowercased() let lowerSuggestion = suggestion.lowercased() if lowerSuggestion.hasPrefix(lowerQuery) { return true } let words = lowerSuggestion.split(whereSeparator: { !$0.isLetter && !$0.isNumber }) return words.contains { $0.hasPrefix(lowerQuery) } } .sorted { $0.localizedStandardCompare($1) == .orderedAscending } .prefix(6) .map { String($0) } } private func addTokens() { let fragments = newTagText .split(separator: ",") .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } .filter { !$0.isEmpty } for fragment in fragments { if !tokens.contains(fragment) { tokens.append(fragment) } } newTagText = "" } var body: some View { VStack(alignment: .leading, spacing: 8) { if !tokens.isEmpty { FlowLayout(horizontalSpacing: 6, verticalSpacing: 6) { ForEach(tokens, id: \.self) { token in HStack(spacing: 4) { Text(token) .font(.caption) Button { tokens.removeAll { $0 == token } } label: { Image(systemName: "xmark.circle.fill") .font(.caption) } .buttonStyle(.borderless) } .padding(.horizontal, 8) .padding(.vertical, 4) .background(Color.accentColor.opacity(0.2)) .clipShape(Capsule()) } } } HStack { TextField(placeholder, text: $newTagText) .textFieldStyle(.roundedBorder) .onSubmit { addTokens() } if !newTagText.isEmpty { Button("Add") { addTokens() } .buttonStyle(.bordered) .controlSize(.small) } } if !matchingSuggestions.isEmpty { VStack(alignment: .leading, spacing: 0) { ForEach(matchingSuggestions, id: \.self) { suggestion in Button { if !tokens.contains(suggestion) { tokens.append(suggestion) } newTagText = "" } label: { HStack { Text(suggestion) .font(.body) .foregroundStyle(.primary) Spacer() Image(systemName: "plus") .font(.caption) .foregroundStyle(.secondary) } .padding(.horizontal, 10) .padding(.vertical, 6) .contentShape(Rectangle()) } .buttonStyle(.plain) if suggestion != matchingSuggestions.last { Divider() } } } .background(Color(NSColor.windowBackgroundColor)) .clipShape(RoundedRectangle(cornerRadius: 8)) .overlay( RoundedRectangle(cornerRadius: 8) .stroke(Color.secondary.opacity(0.3), lineWidth: 1) ) } } } } struct GroupedContentBlocksListView: View { let contentBlocks: [StoreContentBlock] @Binding var selectedContentBlock: StoreContentBlock? let onCreateBlock: () -> Void let onDeleteBlock: (StoreContentBlock) -> Void private var groupedBlocks: [(group: String, blocks: [StoreContentBlock])] { let grouped = Dictionary(grouping: contentBlocks) { block in let name = block.groupName.trimmingCharacters(in: .whitespacesAndNewlines) return name.isEmpty ? "General" : name } return grouped.map { (group: $0.key, blocks: $0.value.sorted { let t1 = $0.title.isEmpty ? $0.key : $0.title let t2 = $1.title.isEmpty ? $1.key : $1.title return t1.localizedStandardCompare(t2) == .orderedAscending })} .sorted { $0.group.localizedStandardCompare($1.group) == .orderedAscending } } var body: some View { VStack(spacing: 0) { HStack { Text("Content Blocks") .font(.headline) Spacer() Button(action: onCreateBlock) { Label("New Block", systemImage: "plus") } .labelStyle(.iconOnly) .help("Create new content block") } .padding() List(selection: $selectedContentBlock) { ForEach(groupedBlocks, id: \.group) { group in Section(header: Text(group.group)) { ForEach(group.blocks) { block in ContentBlockRow(block: block) .tag(block) .contextMenu { Button("Delete Block", role: .destructive) { onDeleteBlock(block) } } } .onDelete { offsets in for index in offsets { let blockToDelete = group.blocks[index] onDeleteBlock(blockToDelete) } } } } } } .navigationTitle("Content Blocks") } } struct ContentBlockRow: View { let block: StoreContentBlock var body: some View { VStack(alignment: .leading, spacing: 4) { Text(block.title.isEmpty ? (block.key.isEmpty ? "Untitled Block" : block.key) : block.title) .font(.body) .bold() Text(block.key.isEmpty ? "No key" : block.key) .font(.caption) .foregroundStyle(.secondary) if !block.internalDescription.isEmpty { Text(block.internalDescription) .font(.caption2) .foregroundStyle(.secondary) .lineLimit(2) } } .padding(.vertical, 2) } } struct ContentBlockEmptyStateView: View { var body: some View { VStack(spacing: 8) { Image(systemName: "doc.text") .font(.system(size: 36)) .foregroundStyle(.secondary) Text("No Content Block Selected") .font(.headline) Text("Select a block from the list or add a new one.") .font(.subheadline) .foregroundStyle(.secondary) } .frame(maxWidth: .infinity, maxHeight: .infinity) } } struct ContentBlockStudioDetailView: View { @Environment(\.modelContext) private var modelContext @Bindable var block: StoreContentBlock let allBlocks: [StoreContentBlock] let onDelete: () -> Void private var existingGroupNames: [String] { let defaultGroups = ["Home Page", "About Us", "Policies", "General"] let customGroups = allBlocks.map { $0.groupName.trimmingCharacters(in: .whitespacesAndNewlines) } .filter { !$0.isEmpty } let set = Set(defaultGroups + customGroups) return set.sorted { $0.localizedStandardCompare($1) == .orderedAscending } } var body: some View { ScrollView { VStack(alignment: .leading, spacing: 20) { // Group / Section GroupBox("Group / Section") { VStack(alignment: .leading, spacing: 10) { TextField("Group Name (e.g. Home Page, About Us, Policies)", text: $block.groupName) .textFieldStyle(.roundedBorder) Text("Quick Selection:") .font(.caption) .foregroundStyle(.secondary) ScrollView(.horizontal, showsIndicators: false) { HStack(spacing: 8) { ForEach(existingGroupNames, id: \.self) { group in Button { block.groupName = group } label: { Text(group) .font(.caption) .padding(.horizontal, 10) .padding(.vertical, 4) .background( block.groupName == group ? Color.accentColor : Color.secondary.opacity(0.15) ) .foregroundStyle( block.groupName == group ? Color.white : Color.primary ) .clipShape(Capsule()) } .buttonStyle(.plain) } } } } .padding(4) } // Identifier & Header GroupBox("Identifier & Header") { VStack(alignment: .leading, spacing: 12) { ProductFormRow(label: "Key") { TextField("Key (e.g. home_hero, about_story)", text: $block.key) .textFieldStyle(.roundedBorder) } ProductFormRow(label: "Title") { TextField("Title (e.g. Peace, Love, And Groovy Stuff)", text: $block.title) .textFieldStyle(.roundedBorder) } } .padding(4) } // Internal Description / Notes GroupBox("Internal Description / Notes") { VStack(alignment: .leading, spacing: 8) { Text("Non-printing internal notes and layout reminders") .font(.caption) .foregroundStyle(.secondary) TextField("Internal Notes...", text: $block.internalDescription, axis: .vertical) .lineLimit(2...4) .textFieldStyle(.roundedBorder) } .padding(4) } // Short Text (Mobile / Teaser) GroupBox("Short Text (Mobile / Teaser)") { VStack(alignment: .leading, spacing: 8) { Text("Optional teaser or mobile copy. If left blank, the web engine will display Full Content across all viewports.") .font(.caption) .foregroundStyle(.secondary) TextField("Short Text", text: $block.shortText, axis: .vertical) .lineLimit(1...3) .textFieldStyle(.roundedBorder) } .padding(4) } // Full Content GroupBox("Full Content") { VStack(alignment: .leading, spacing: 8) { Text("Main body copy") .font(.caption) .foregroundStyle(.secondary) TextEditor(text: $block.fullText) .font(.body) .frame(minHeight: 180) .padding(4) .overlay( RoundedRectangle(cornerRadius: 6) .stroke(Color.secondary.opacity(0.2), lineWidth: 1) ) } .padding(4) } // Actions HStack { Button(role: .destructive, action: onDelete) { Label("Delete Block", systemImage: "trash") } .buttonStyle(.bordered) Spacer() Button { try? modelContext.save() JSONExporter.publishProducts(context: modelContext) } label: { Label("Save Changes", systemImage: "checkmark.circle.fill") } .buttonStyle(.borderedProminent) } } .padding() } .navigationTitle(block.title.isEmpty ? (block.key.isEmpty ? "Content Block" : block.key) : block.title) } } // MARK: - AI Personas & Prompts Dashboard struct AIPersonasDashboardView: View { private let globalRulesPreferenceKey = "global_ai_base_rules" private let defaultBaseRules = """ Use standard HTML formatting for product descriptions: - Wrap paragraphs in

...

tags. - Use ... for bolding and highlighting key features. - Use

...

for clean section subheadings. - Use
    and
  • for bulleted feature lists. - Do NOT include wrapper tags (such as , , or ```html codeblocks). - Ensure output is well-structured, readable, and directly ready for web publishing. """ @Environment(\.modelContext) private var modelContext @Query(sort: \AIPersona.title) private var personas: [AIPersona] @Binding var selectedPersona: AIPersona? @State private var globalBaseRules: String = "" @State private var personaTitle: String = "" @State private var personaPromptText: String = "" @State private var personaIsDefault: Bool = false var body: some View { ScrollView { VStack(alignment: .leading, spacing: 24) { // Section 1: Global Base Rules (Always Applied) GroupBox { VStack(alignment: .leading, spacing: 12) { HStack { Label("Global Base Rules (Always Applied)", systemImage: "globe") .font(.headline) Spacer() Button("Reset to Default") { globalBaseRules = defaultBaseRules PreferencesManager.shared.set(defaultBaseRules, for: globalRulesPreferenceKey) } .buttonStyle(.borderless) .font(.caption) } Text("These system directives are appended to all AI description and metadata generation prompts.") .font(.caption) .foregroundStyle(.secondary) TextEditor(text: $globalBaseRules) .font(.monospaced(.body)()) .frame(minHeight: 120) .padding(4) .overlay( RoundedRectangle(cornerRadius: 6) .stroke(Color.secondary.opacity(0.2), lineWidth: 1) ) } .padding(4) } // Section 2: Persona Definition GroupBox { VStack(alignment: .leading, spacing: 16) { HStack { Label(selectedPersona == nil ? "New Persona Definition" : "Persona Definition", systemImage: "person.text.rectangle") .font(.headline) Spacer() if selectedPersona != nil { Button("Add New Persona", systemImage: "plus.circle") { createNewPersona() } .buttonStyle(.bordered) .controlSize(.small) } } VStack(alignment: .leading, spacing: 8) { Text("Title") .font(.subheadline) .bold() TextField("e.g. Groovy Panda Voice, Technical Spec Writer", text: $personaTitle) .textFieldStyle(.roundedBorder) } VStack(alignment: .leading, spacing: 8) { Text("Voice & Style Prompt") .font(.subheadline) .bold() TextEditor(text: $personaPromptText) .font(.body) .frame(minHeight: 140) .padding(4) .overlay( RoundedRectangle(cornerRadius: 6) .stroke(Color.secondary.opacity(0.2), lineWidth: 1) ) } Toggle("Set as Default Persona", isOn: $personaIsDefault) Divider() HStack { if selectedPersona != nil { Button(role: .destructive, action: deleteSelectedPersona) { Label("Delete Persona", systemImage: "trash") } .buttonStyle(.bordered) } Spacer() Button(action: saveChanges) { Label("Save Changes", systemImage: "checkmark.circle.fill") } .buttonStyle(.borderedProminent) .disabled(personaTitle.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) } } .padding(4) } } .padding() } .frame(maxWidth: .infinity, maxHeight: .infinity) .navigationTitle("AI Personas & Prompts") .onAppear { loadGlobalBaseRules() if selectedPersona == nil, let first = personas.first { selectedPersona = first } populateForm(from: selectedPersona) } .onChange(of: selectedPersona, initial: false) { _, newPersona in populateForm(from: newPersona) } .onChange(of: globalBaseRules, initial: false) { _, newRules in PreferencesManager.shared.set(newRules, for: globalRulesPreferenceKey) } } private func loadGlobalBaseRules() { let stored = PreferencesManager.shared.get(for: globalRulesPreferenceKey) ?? "" if stored.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { globalBaseRules = defaultBaseRules PreferencesManager.shared.set(defaultBaseRules, for: globalRulesPreferenceKey) } else { globalBaseRules = stored } } private func populateForm(from persona: AIPersona?) { if let persona { personaTitle = persona.title personaPromptText = persona.promptText personaIsDefault = persona.isDefault } else { personaTitle = "" personaPromptText = "" personaIsDefault = false } } private func createNewPersona() { selectedPersona = nil personaTitle = "" personaPromptText = "" personaIsDefault = false } private func deleteSelectedPersona() { guard let persona = selectedPersona else { return } let remaining = personas.filter { $0.id != persona.id } modelContext.delete(persona) try? modelContext.save() selectedPersona = remaining.first populateForm(from: selectedPersona) } private func saveChanges() { PreferencesManager.shared.set(globalBaseRules, for: globalRulesPreferenceKey) let trimmedTitle = personaTitle.trimmingCharacters(in: .whitespacesAndNewlines) guard !trimmedTitle.isEmpty else { return } if personaIsDefault { for existing in personas { existing.isDefault = false } } if let selectedPersona { selectedPersona.title = trimmedTitle selectedPersona.promptText = personaPromptText selectedPersona.isDefault = personaIsDefault } else { let newPersona = AIPersona( title: trimmedTitle, promptText: personaPromptText, isDefault: personaIsDefault ) modelContext.insert(newPersona) selectedPersona = newPersona } try? modelContext.save() } } struct TemplateDetailView: View { @Environment(\.modelContext) private var modelContext @Bindable var template: ProductTemplate let onCreateProduct: (ProductTemplate, String?) -> Void let onDeleteTemplate: () -> Void let onJumpToGroup: (AttributeGroup) -> Void @Query(sort: \Category.name) private var allCategories: [Category] @Query(sort: \AIPersona.title) private var personas: [AIPersona] @Query(sort: \Tag.name) private var allTags: [Tag] @State private var activeTagStrings: [String] = [] @State private var showingSizeSelectionSheet = false var body: some View { ScrollView { VStack(alignment: .leading, spacing: 24) { GroupBox("Template Basic Info") { VStack(spacing: 12) { ProductFormRow(label: "Template Name") { TextField("Template Name", text: $template.name) } ProductFormRow(label: "Category") { Picker("Category", selection: Binding( get: { template.category }, set: { template.category = $0 } )) { Text("None (Uncategorized)").tag(Category?.none) ForEach(allCategories) { category in Text(category.fullPath).tag(Optional(category)) } } .labelsHidden() } Toggle("Unique / 1-of-1 Item", isOn: $template.isUniqueOneOff) } .textFieldStyle(.roundedBorder) } GroupBox("Default Tags") { VStack(alignment: .leading, spacing: 8) { WrappingTokenField(tokens: $activeTagStrings, placeholder: "Add default tag", suggestions: allTags.map(\.name)) } } GroupBox("Default Persona & AI Prompt") { VStack(spacing: 12) { HStack { Text("Active Persona") Spacer() Picker("Active Persona", selection: Binding( get: { personas.first(where: { $0.promptText == template.savedAIPrompt }) }, set: { newPersona in if let newPersona { template.savedAIPrompt = newPersona.promptText } } )) { Text("Custom / Manual").tag(AIPersona?.none) ForEach(personas) { persona in Text(persona.title).tag(Optional(persona)) } } .labelsHidden() } TextField("Default AI Persona Prompt (Context)", text: Binding( get: { template.savedAIPrompt ?? "" }, set: { template.savedAIPrompt = $0.isEmpty ? nil : $0 } ), axis: .vertical) .lineLimit(3...10) .textFieldStyle(.roundedBorder) } } GroupBox("Default Category Properties") { if let category = template.category { TemplateCategoryPropertiesSection( template: template, attributeGroups: category.allAttributeGroups, onJumpToGroup: onJumpToGroup ) } else { Text("Select a category above to configure default properties.") .foregroundStyle(.secondary) } } GroupBox("Web Accordions / Custom Fields") { VStack(alignment: .leading, spacing: 16) { let categoryDefaults = template.category?.allDefaultAccordions ?? [] if !categoryDefaults.isEmpty { VStack(alignment: .leading, spacing: 12) { Text("Inherited Category Defaults (Reference)") .font(.caption) .fontWeight(.bold) .foregroundStyle(.secondary) ForEach(categoryDefaults, id: \.title) { catAccordion in VStack(alignment: .leading, spacing: 8) { HStack { Text(catAccordion.title) .font(.headline) Text("(Inherited from Category)") .font(.caption) .padding(.horizontal, 6) .padding(.vertical, 2) .background(Color.blue.opacity(0.15)) .foregroundStyle(.blue) .clipShape(Capsule()) } Text(catAccordion.content.isEmpty ? "No content defined in category" : catAccordion.content) .font(.body) .foregroundStyle(catAccordion.content.isEmpty ? .tertiary : .secondary) .padding(8) .frame(maxWidth: .infinity, alignment: .leading) .background(Color.secondary.opacity(0.05)) .clipShape(RoundedRectangle(cornerRadius: 6)) } .padding(8) .background(Color.secondary.opacity(0.03)) .clipShape(RoundedRectangle(cornerRadius: 8)) } } Divider() } VStack(alignment: .leading, spacing: 12) { Text("Template Custom Accordions") .font(.caption) .fontWeight(.bold) .foregroundStyle(.secondary) ForEach($template.savedAccordions) { $accordion in VStack(alignment: .leading, spacing: 8) { HStack { TextField("Tab/Accordion Title", text: $accordion.title) .textFieldStyle(.roundedBorder) Button(role: .destructive) { template.savedAccordions.removeAll { $0.id == accordion.id } } label: { Image(systemName: "trash") } .buttonStyle(.borderless) } TextEditor(text: $accordion.content) .font(.body) .frame(minHeight: 60) .overlay( RoundedRectangle(cornerRadius: 6) .stroke(Color.secondary.opacity(0.2), lineWidth: 1) ) } .padding(.bottom, 8) Divider() } Button(action: { template.savedAccordions.append(WebAccordion(title: "New Detail", content: "")) }) { Label("Add Custom Accordion Field", systemImage: "plus.circle.fill") } .padding(.top, 4) } } } } .padding() } .navigationTitle(template.name.isEmpty ? "New Template" : template.name) .toolbar { ToolbarItem { Button { handleCreateProductTapped() } label: { Label("Create Product from this Template", systemImage: "plus.box") .labelStyle(.titleAndIcon) } .buttonStyle(.borderedProminent) } ToolbarItem { Button(role: .destructive) { onDeleteTemplate() } label: { Label("Delete Template", systemImage: "trash") } } } .sheet(isPresented: $showingSizeSelectionSheet) { TemplateSizePickerSheet( sizeGroup: sizeGroup, onSelectSize: { chosenSize in showingSizeSelectionSheet = false onCreateProduct(template, chosenSize) }, onCancel: { showingSizeSelectionSheet = false } ) } .onChange(of: template.id, initial: true) { _, _ in syncActiveTags() } .onChange(of: activeTagStrings, initial: false) { _, _ in saveActiveTags() } } private var sizeGroup: AttributeGroup? { guard let category = template.category else { return nil } return category.allAttributeGroups.first { group in group.name.localizedCaseInsensitiveContains("Size") || (group.displayName?.localizedCaseInsensitiveContains("Size") ?? false) } } private func handleCreateProductTapped() { if let sizeGroup, let options = sizeGroup.options, !options.isEmpty { showingSizeSelectionSheet = true } else { onCreateProduct(template, nil) } } @MainActor private func syncActiveTags() { let tagNames = (template.savedTags ?? []).map(\.name) if activeTagStrings != tagNames { activeTagStrings = tagNames } } @MainActor private func saveActiveTags() { let cleanedNames = activeTagStrings .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } .filter { !$0.isEmpty } if activeTagStrings != cleanedNames { activeTagStrings = cleanedNames return } var resolvedTags: [Tag] = [] for tagName in cleanedNames { let slug = slugify(tagName) let descriptor = FetchDescriptor( predicate: #Predicate { tag in tag.slug == slug } ) if let existingTag = try? modelContext.fetch(descriptor).first { resolvedTags.append(existingTag) } else { let newTag = Tag(slug: slug, name: tagName) modelContext.insert(newTag) resolvedTags.append(newTag) } } let existingTagIDs = Set((template.savedTags ?? []).map(\.id)) let resolvedTagIDs = Set(resolvedTags.map(\.id)) if existingTagIDs != resolvedTagIDs { template.savedTags = resolvedTags.isEmpty ? nil : resolvedTags } } private func slugify(_ name: String) -> String { name .lowercased() .replacing("'", with: "") .replacing("&", with: "and") .split(whereSeparator: { !$0.isLetter && !$0.isNumber }) .map(String.init) .joined(separator: "-") } } struct TemplateCategoryPropertiesSection: View { @Bindable var template: ProductTemplate let attributeGroups: [AttributeGroup] let onJumpToGroup: (AttributeGroup) -> Void var body: some View { VStack(alignment: .leading, spacing: 12) { if attributeGroups.isEmpty { Text("No category properties available.") .foregroundStyle(.secondary) } else { ForEach(attributeGroups) { group in TemplatePropertyRow( template: template, group: group, onJumpToGroup: onJumpToGroup ) } } } } } struct TemplatePropertyRow: View { @Bindable var template: ProductTemplate let group: AttributeGroup let onJumpToGroup: (AttributeGroup) -> Void var body: some View { VStack(alignment: .leading, spacing: 8) { HStack { Text(group.displayName ?? group.name) .bold() Button("Jump to Group", systemImage: "arrow.right.circle") { onJumpToGroup(group) } .labelStyle(.iconOnly) .buttonStyle(.borderless) Spacer() if !(template.savedAttributes[group.name]?.isEmpty ?? true) { Button("Clear Default") { template.savedAttributes.removeValue(forKey: group.name) } .buttonStyle(.borderless) .font(.caption) .foregroundStyle(.secondary) } } switch group.displayStyle { case .tags: WrappingTokenField(tokens: tagTokensBinding, placeholder: "Add default \(group.displayName ?? group.name)", suggestions: group.options?.map(\.value) ?? []) case .radio: OneOfOneRadioOptionsView( options: sortedOptions, selectedValue: selectedValueBinding ) case .checkbox: OneOfOneCheckboxOptionsView( options: sortedOptions, selectedValues: checkboxValuesBinding, highlightedStyles: [], promotedStyles: [] ) case .popup: HStack { OneOfOnePopupOptionsView( mainOptions: mainPopupOptions, otherOptions: otherPopupOptions, selectedValue: selectedValueBinding ) Button("Clear") { selectedValueBinding.wrappedValue = "" } .buttonStyle(.bordered) .controlSize(.small) .disabled(selectedValueBinding.wrappedValue.isEmpty) } } } } private var sortedOptions: [AttributeOption] { sortedAttributeOptions(group.options ?? [], strategy: group.sortStrategy) } private var mainPopupOptions: [String] { sortedOptions .map(\.value) .filter { !$0.hasPrefix(".") } } private var otherPopupOptions: [String] { sortedOptions.compactMap { option in guard option.value.hasPrefix(".") else { return nil } return String(option.value.dropFirst()) } } private var selectedValueBinding: Binding { Binding( get: { template.savedAttributes[group.name] ?? "" }, set: { newValue in if newValue.isEmpty { template.savedAttributes.removeValue(forKey: group.name) } else { template.savedAttributes[group.name] = newValue } } ) } private var tagTokensBinding: Binding<[String]> { Binding( get: { let storedValue = template.savedAttributes[group.name] ?? "" return storedValue .split(separator: ",") .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } .filter { !$0.isEmpty } }, set: { newTokens in let normalizedTokens = newTokens .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } .filter { !$0.isEmpty } if normalizedTokens.isEmpty { template.savedAttributes.removeValue(forKey: group.name) } else { template.savedAttributes[group.name] = normalizedTokens.joined(separator: ", ") } } ) } private var checkboxValuesBinding: Binding<[String]> { Binding( get: { let storedValue = template.savedAttributes[group.name] ?? "" return storedValue .split(separator: ",") .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } .filter { !$0.isEmpty } }, set: { newValues in let normalizedValues = newValues .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } .filter { !$0.isEmpty } if normalizedValues.isEmpty { template.savedAttributes.removeValue(forKey: group.name) } else { template.savedAttributes[group.name] = normalizedValues.joined(separator: ", ") } } ) } } struct TemplateSizePickerSheet: View { let sizeGroup: AttributeGroup? let onSelectSize: (String?) -> Void let onCancel: () -> Void var body: some View { VStack(spacing: 20) { Text("Select Product Size") .font(.headline) Text("Choose a default size for the new product, or create without specifying a size.") .font(.subheadline) .foregroundStyle(.secondary) if let sizeGroup, let options = sizeGroup.options, !options.isEmpty { let sortedSizeOptions = sortedAttributeOptions(options, strategy: sizeGroup.sortStrategy) FlowLayout { ForEach(sortedSizeOptions) { option in Button(option.value) { onSelectSize(option.value) } .buttonStyle(.borderedProminent) .controlSize(.large) } } .padding() } HStack { Button("Cancel") { onCancel() } Spacer() Button("Skip / No Size") { onSelectSize(nil) } .buttonStyle(.bordered) } } .padding() .frame(minWidth: 360, minHeight: 220) } } #Preview { ContentView() .modelContainer(for: ApparelProduct.self, inMemory: true) }