acupedia-web-ui/src/components/modules/ModuleBuilderTab.tsx

2517 lines
110 KiB
TypeScript

import React, { useState, useEffect } from 'react';
import {
Layers, Plus, Trash2, Save, RefreshCw, AlertCircle, CheckCircle2,
FolderPlus, FilePlus, Sparkles, BookOpen, ChevronRight, X, RotateCcw,
HelpCircle, ChevronDown, ChevronUp, Stethoscope, HeartPulse, Download, Eye,
Package, UploadCloud, Check, FileArchive
} from 'lucide-react';
import {
moduleBuilderService,
type BuilderModuleSummary,
type BuilderCategorySummary,
type BuilderDiseaseSummary,
type BuilderPattern,
} from '../../services/moduleBuilderService';
import { ErrorBoundary } from '../common/ErrorBoundary';
const COMMON_TONGUE_SUGGESTIONS = [
'Pale and Thin.',
'Purple.',
'Normal.',
'Red with yellow coat.',
'Pale with tooth marks.',
'Slightly Red sides or normal.',
];
const COMMON_PULSE_SUGGESTIONS = [
'Choppy.',
'Wiry.',
'Deep and Wiry.',
'Deep and Weak.',
'Choppy or Fine.',
'Rapid and Slippery.',
'Floating.',
];
const COMMON_POINT_SUGGESTIONS = [
'RN-6', 'RN-4', 'ST-36', 'SP-6', 'LR-8', 'SP-4', 'PC-6',
'KI-14', 'ST-30', 'SP-10', 'BL-17', 'LR-3', 'ST-29', 'BL-23', 'BL-20', 'BL-18'
];
// Strictly convert human text to lowercase underscore format (e.g. "Period Pain" -> "period_pain")
const toSnakeCase = (text: string): string =>
(text || '')
.toLowerCase()
.trim()
.replace(/['"]/g, '')
.replace(/[^\w\s-]/g, '_')
.replace(/[\s_-]+/g, '_')
.replace(/^_+|_+$/g, '');
// Convert text to Title Case (e.g. "period pain" -> "Period Pain")
const toTitleCase = (text: string): string =>
(text || '').replace(/\w\S*/g, (txt) => txt.charAt(0).toUpperCase() + txt.substring(1).toLowerCase());
// Safely format API errors to ALWAYS return a plain string (never an object or array)
const formatApiError = (err: any, fallback: string): string => {
const detail = err?.response?.data?.detail;
if (!detail) return err?.message || fallback;
if (typeof detail === 'string') return detail;
if (Array.isArray(detail)) {
return detail.map((d: any) => d?.msg || d?.message || JSON.stringify(d)).join('; ');
}
if (typeof detail === 'object') {
return detail.message || detail.msg || JSON.stringify(detail);
}
return String(detail);
};
const createBlankPattern = (moduleCode: string, catCode: string, disCode: string): BuilderPattern => ({
module_code: moduleCode,
category_code: catCode,
disease_code: disCode,
pattern_code: 'primary_pattern',
name: 'Primary Pattern',
description: '',
clinical_data: {
clinical_manifestations: [''],
tongue: '',
pulse: '',
treatment_principle: '',
acupuncture: { points: '', method: '' },
explanation: [''],
},
sort_order: 0,
});
export const ModuleBuilderTabContent: React.FC = () => {
// Modules management
const [modules, setModules] = useState<BuilderModuleSummary[]>([]);
const [moduleCode, setModuleCode] = useState<string>(() => {
return localStorage.getItem('acupedia_active_module_builder_code') || 'm0042';
});
const [showModuleDropdown, setShowModuleDropdown] = useState(false);
const [showNewModuleModal, setShowNewModuleModal] = useState(false);
const [newModuleName, setNewModuleName] = useState('');
const [newModuleCode, setNewModuleCode] = useState('');
const [newModuleDesc, setNewModuleDesc] = useState('');
const [modalModError, setModalModError] = useState<string | null>(null);
const [creatingModule, setCreatingModule] = useState(false);
const [exportingZip, setExportingZip] = useState(false);
const [syncingRepo, setSyncingRepo] = useState(false);
const [syncRepoEnabled, setSyncRepoEnabled] = useState(false);
const [showExportMenu, setShowExportMenu] = useState(false);
const [categories, setCategories] = useState<BuilderCategorySummary[]>([]);
const [selectedCategoryCode, setSelectedCategoryCode] = useState<string>('');
const [categoryOverview, setCategoryOverview] = useState<string>('');
const [diseases, setDiseases] = useState<BuilderDiseaseSummary[]>([]);
const [selectedDiseaseCode, setSelectedDiseaseCode] = useState<string>('');
const [diseaseName, setDiseaseName] = useState<string>('');
const [diseaseOverview, setDiseaseOverview] = useState<string>('');
const [isCreatingNewDisease, setIsCreatingNewDisease] = useState<boolean>(false);
const [patterns, setPatterns] = useState<BuilderPattern[]>([]);
const [activePatternIndex, setActivePatternIndex] = useState<number>(0);
const [loading, setLoading] = useState(false);
const [saving, setSaving] = useState(false);
const [downloading, setDownloading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [successMsg, setSuccessMsg] = useState<string | null>(null);
const [showQuickGuide, setShowQuickGuide] = useState(false);
const [showPreviewModal, setShowPreviewModal] = useState(false);
const [previewPatternIdx, setPreviewPatternIdx] = useState(0);
// Modals for creating new category & disease (Name only, code generated automatically)
const [showNewCategoryModal, setShowNewCategoryModal] = useState(false);
const [newCategoryName, setNewCategoryName] = useState('');
const [modalCatError, setModalCatError] = useState<string | null>(null);
const [showNewDiseaseModal, setShowNewDiseaseModal] = useState(false);
const [newDiseaseName, setNewDiseaseName] = useState('');
const [modalDisError, setModalDisError] = useState<string | null>(null);
// Point input state
const [customPointInput, setCustomPointInput] = useState('');
// 0. Load Modules List
const fetchModules = async (selectCode?: string) => {
try {
const list = await moduleBuilderService.getModules();
setModules(list || []);
if (selectCode) {
setModuleCode(selectCode);
localStorage.setItem('acupedia_active_module_builder_code', selectCode);
} else if (list && list.length > 0) {
const saved = localStorage.getItem('acupedia_active_module_builder_code');
const match = list.find(m => m.code === saved);
const target = match ? match.code : list[0].code;
setModuleCode(target);
localStorage.setItem('acupedia_active_module_builder_code', target);
}
} catch (err: any) {
setError(formatApiError(err, 'Failed to load modules list.'));
}
};
useEffect(() => {
fetchModules();
moduleBuilderService
.getConfig()
.then((cfg) => setSyncRepoEnabled(Boolean(cfg?.sync_repo_enabled)))
.catch(() => setSyncRepoEnabled(false));
}, []);
// Compute active module object
const activeModule = modules.find(m => m.code === moduleCode) || null;
// 1. Load Categories
const fetchCategories = async (modCode = moduleCode, selectCatCode?: string, selectDisCode?: string) => {
setLoading(true);
setError(null);
try {
const cats = await moduleBuilderService.getCategories(modCode);
setCategories(cats || []);
if (cats && cats.length > 0) {
const nextCat = (selectCatCode && cats.some(c => c.category_code === selectCatCode))
? selectCatCode
: (cats.some(c => c.category_code === selectedCategoryCode) ? selectedCategoryCode : cats[0].category_code);
setSelectedCategoryCode(nextCat);
const catObj = cats.find(c => c.category_code === nextCat);
setCategoryOverview(catObj?.overview || '');
await fetchDiseases(nextCat, selectDisCode);
} else {
setSelectedCategoryCode('');
setCategoryOverview('');
setDiseases([]);
setSelectedDiseaseCode('');
setDiseaseName('');
setDiseaseOverview('');
setPatterns([]);
setIsCreatingNewDisease(false);
}
} catch (err: any) {
setError(formatApiError(err, 'Failed to load disease categories. Please check your connection.'));
} finally {
setLoading(false);
}
};
useEffect(() => {
if (moduleCode) {
fetchCategories(moduleCode);
}
}, [moduleCode]);
// 2. Load Diseases when category changes
const fetchDiseases = async (catCode: string, selectDisCode?: string) => {
if (!catCode) {
setDiseases([]);
setSelectedDiseaseCode('');
setDiseaseName('');
setDiseaseOverview('');
setPatterns([]);
setIsCreatingNewDisease(false);
return;
}
setLoading(true);
setError(null);
try {
const disList = await moduleBuilderService.getDiseases(moduleCode, catCode);
setDiseases(disList || []);
if (selectDisCode && disList.some(d => d.disease_code === selectDisCode)) {
// Explicitly selected disease (e.g. after modal creation or save)
setSelectedDiseaseCode(selectDisCode);
setIsCreatingNewDisease(false);
await fetchDiseaseDetail(catCode, selectDisCode);
} else if (!selectDisCode && disList.length > 0 && selectedDiseaseCode && disList.some(d => d.disease_code === selectedDiseaseCode)) {
// Retain currently selected disease if it still exists in list
await fetchDiseaseDetail(catCode, selectedDiseaseCode);
} else {
// Keep blank by default on load so user actively picks or starts fresh
setSelectedDiseaseCode('');
setDiseaseName('');
setDiseaseOverview('');
setPatterns([]);
setIsCreatingNewDisease(false);
}
} catch (err: any) {
setError(formatApiError(err, 'Failed to load diseases for this category.'));
} finally {
setLoading(false);
}
};
// 3. Load Disease Details & Patterns when disease changes
const fetchDiseaseDetail = async (catCode: string, disCode: string) => {
if (!catCode || !disCode) {
setPatterns([]);
return;
}
setLoading(true);
setError(null);
try {
const detail = await moduleBuilderService.getDiseaseDetail(moduleCode, catCode, disCode);
setDiseaseName(detail?.name || toTitleCase(disCode.replace(/_/g, ' ')));
setDiseaseOverview(detail?.overview || '');
setIsCreatingNewDisease(false);
if (detail && detail.patterns && detail.patterns.length > 0) {
const normalized: BuilderPattern[] = detail.patterns.map(p => ({
...p,
clinical_data: {
clinical_manifestations: Array.isArray(p.clinical_data?.clinical_manifestations)
? p.clinical_data.clinical_manifestations
: [''],
tongue: p.clinical_data?.tongue || '',
pulse: p.clinical_data?.pulse || '',
treatment_principle: p.clinical_data?.treatment_principle || '',
acupuncture: {
points: p.clinical_data?.acupuncture?.points || '',
method: p.clinical_data?.acupuncture?.method || '',
},
explanation: Array.isArray(p.clinical_data?.explanation)
? p.clinical_data.explanation
: [''],
},
}));
setPatterns(normalized);
setActivePatternIndex(0);
} else {
const initial = createBlankPattern(moduleCode, catCode, disCode);
setPatterns([initial]);
setActivePatternIndex(0);
}
} catch (err: any) {
setError(formatApiError(err, 'Failed to load clinical patterns for this disease.'));
} finally {
setLoading(false);
}
};
useEffect(() => {
if (selectedCategoryCode && selectedDiseaseCode && !isCreatingNewDisease) {
fetchDiseaseDetail(selectedCategoryCode, selectedDiseaseCode);
}
}, [selectedCategoryCode, selectedDiseaseCode]);
// Revert / Reset to Blank Form
const handleResetToBlankForm = () => {
if (!selectedCategoryCode) {
setError('Please select or create a Category first before starting a blank form.');
return;
}
if (
(diseaseName || diseaseOverview) &&
!window.confirm('Reset form to blank to start a new disease from scratch?\n\nAny unsaved edits to the current disease will be cleared.')
) {
return;
}
setSelectedDiseaseCode('');
setDiseaseName('');
setDiseaseOverview('');
setIsCreatingNewDisease(true);
const blank = createBlankPattern(moduleCode, selectedCategoryCode, '');
setPatterns([blank]);
setActivePatternIndex(0);
setError(null);
setSuccessMsg('Blank form ready. Enter the disease name, pathology, and clinical patterns.');
setTimeout(() => setSuccessMsg(null), 3500);
};
// Create Category Handler (Name only -> Code auto-generated)
const handleCreateCategory = async (e: React.FormEvent) => {
e.preventDefault();
const cleanName = newCategoryName.trim();
if (!cleanName) {
setModalCatError('Please enter a category name.');
return;
}
const code = toSnakeCase(cleanName);
const title = toTitleCase(cleanName);
if (categories.some(c => c.category_code === code || c.name.toLowerCase() === title.toLowerCase())) {
setModalCatError(`A category named "${title}" already exists. Please enter a distinct name.`);
return;
}
setSaving(true);
setModalCatError(null);
setError(null);
try {
await moduleBuilderService.saveCategory(moduleCode, {
category_code: code,
name: title,
overview: '',
sort_order: categories.length,
});
setShowNewCategoryModal(false);
setNewCategoryName('');
setModalCatError(null);
setSuccessMsg(`Category "${title}" created successfully!`);
await fetchCategories(moduleCode, code);
} catch (err: any) {
setModalCatError(formatApiError(err, 'Failed to create category. Please try again.'));
} finally {
setSaving(false);
}
};
// Delete Category Handler
const handleDeleteCategory = async () => {
if (!selectedCategoryCode) {
setError('Please select a category to delete.');
return;
}
const catName = categories.find(c => c.category_code === selectedCategoryCode)?.name || selectedCategoryCode;
const confirmed = window.confirm(
`Are you sure you want to permanently delete category "${catName}"?\n\n` +
`WARNING: This will delete ALL diseases and clinical patterns contained inside it. This action cannot be undone.`
);
if (!confirmed) return;
setSaving(true);
setError(null);
try {
await moduleBuilderService.deleteCategory(moduleCode, selectedCategoryCode);
setSuccessMsg(`Category "${catName}" deleted successfully.`);
await fetchCategories(moduleCode);
} catch (err: any) {
setError(formatApiError(err, 'Failed to delete category.'));
} finally {
setSaving(false);
}
};
// Create Disease Handler (Name only -> Code auto-generated)
const handleCreateDisease = async (e: React.FormEvent) => {
e.preventDefault();
const cleanName = newDiseaseName.trim();
if (!cleanName) {
setModalDisError('Please enter a disease name.');
return;
}
if (!selectedCategoryCode) {
setModalDisError('Please select or create a Category first.');
return;
}
const code = toSnakeCase(cleanName);
const title = toTitleCase(cleanName);
if (diseases.some(d => d.disease_code === code || d.name.toLowerCase() === title.toLowerCase())) {
setModalDisError(`A disease named "${title}" already exists in this category. Please choose a different name.`);
return;
}
setSaving(true);
setModalDisError(null);
setError(null);
try {
const savedDis = await moduleBuilderService.saveDisease(moduleCode, selectedCategoryCode, {
category_code: selectedCategoryCode,
disease_code: code,
name: title,
overview: '',
sort_order: diseases.length,
});
setShowNewDiseaseModal(false);
setNewDiseaseName('');
setModalDisError(null);
setIsCreatingNewDisease(false);
setSuccessMsg(`Disease "${title}" created successfully!`);
const targetDisCode = savedDis?.disease_code || code;
await fetchCategories(moduleCode, selectedCategoryCode, targetDisCode);
} catch (err: any) {
setModalDisError(formatApiError(err, 'Failed to create disease. Please try again.'));
} finally {
setSaving(false);
}
};
// Delete Disease Handler
const handleDeleteDisease = async () => {
if (!selectedCategoryCode || !selectedDiseaseCode) {
setError('Please select a disease to delete.');
return;
}
const disName = diseaseName || selectedDiseaseCode;
const confirmed = window.confirm(
`Are you sure you want to permanently delete disease "${disName}" and all of its clinical patterns?\n\n` +
`This action cannot be undone.`
);
if (!confirmed) return;
setSaving(true);
setError(null);
try {
await moduleBuilderService.deleteDisease(moduleCode, selectedCategoryCode, selectedDiseaseCode);
setSuccessMsg(`Disease "${disName}" deleted.`);
setSelectedDiseaseCode('');
setDiseaseName('');
setDiseaseOverview('');
setPatterns([]);
setIsCreatingNewDisease(false);
await fetchCategories(moduleCode, selectedCategoryCode);
} catch (err: any) {
setError(formatApiError(err, 'Failed to delete disease.'));
} finally {
setSaving(false);
}
};
// Active Pattern Safety
const safePatternIndex = patterns.length > 0 ? Math.min(Math.max(0, activePatternIndex), patterns.length - 1) : -1;
const activePattern = safePatternIndex >= 0 ? patterns[safePatternIndex] : null;
const updateActivePattern = (updater: (prev: BuilderPattern) => BuilderPattern) => {
if (safePatternIndex < 0) return;
setPatterns(prev => {
const copy = [...prev];
if (copy[safePatternIndex]) {
copy[safePatternIndex] = updater(copy[safePatternIndex]);
}
return copy;
});
};
const handleAddPattern = () => {
const nextIdx = patterns.length + 1;
const patName = `Pattern ${nextIdx}`;
const newPat: BuilderPattern = {
module_code: moduleCode,
category_code: selectedCategoryCode,
disease_code: selectedDiseaseCode || toSnakeCase(diseaseName || 'new_disease'),
pattern_code: toSnakeCase(patName),
name: patName,
description: '',
clinical_data: {
clinical_manifestations: [''],
tongue: '',
pulse: '',
treatment_principle: '',
acupuncture: { points: '', method: '' },
explanation: [''],
},
sort_order: patterns.length,
};
setPatterns(prev => [...prev, newPat]);
setActivePatternIndex(patterns.length);
setError(null);
};
const handleRemovePattern = (idx: number) => {
if (patterns.length <= 1) {
setError('A disease must have at least one clinical pattern. You cannot delete the only pattern.');
return;
}
const patName = patterns[idx]?.name || `Pattern ${idx + 1}`;
if (!window.confirm(`Delete pattern "${patName}"? This will remove all its symptoms and prescription data.`)) {
return;
}
setPatterns(prev => prev.filter((_, i) => i !== idx));
setActivePatternIndex(Math.max(0, idx - 1));
setSuccessMsg(`Pattern "${patName}" deleted.`);
setTimeout(() => setSuccessMsg(null), 3000);
};
// Symptom List Helpers
const handleSymptomChange = (sIdx: number, val: string) => {
updateActivePattern(p => {
const list = [...(p.clinical_data?.clinical_manifestations || [])];
list[sIdx] = val;
return {
...p,
clinical_data: { ...p.clinical_data, clinical_manifestations: list },
};
});
};
const handleAddSymptom = () => {
updateActivePattern(p => ({
...p,
clinical_data: {
...p.clinical_data,
clinical_manifestations: [...(p.clinical_data?.clinical_manifestations || []), ''],
},
}));
};
const handleRemoveSymptom = (sIdx: number) => {
updateActivePattern(p => ({
...p,
clinical_data: {
...p.clinical_data,
clinical_manifestations: (p.clinical_data?.clinical_manifestations || []).filter((_, i) => i !== sIdx),
},
}));
};
// Point Chips Helpers (100% Safe Optional Chaining)
const currentPoints = (activePattern?.clinical_data?.acupuncture?.points || '')
.split(',')
.map(s => s.trim())
.filter(Boolean);
const handleAddPointChip = (point: string) => {
const trimmed = point.trim().toUpperCase();
if (!trimmed) {
setError('Please enter a valid acupuncture point code (e.g. ST-36, RN-6).');
return;
}
if (currentPoints.includes(trimmed)) {
setError(`Point "${trimmed}" is already added to this prescription.`);
return;
}
setError(null);
const updated = [...currentPoints, trimmed].join(', ');
updateActivePattern(p => ({
...p,
clinical_data: {
...p.clinical_data,
acupuncture: {
points: updated,
method: p.clinical_data?.acupuncture?.method || '',
},
},
}));
setCustomPointInput('');
};
const handleRemovePointChip = (pointToRemove: string) => {
const updated = currentPoints.filter(p => p !== pointToRemove).join(', ');
updateActivePattern(p => ({
...p,
clinical_data: {
...p.clinical_data,
acupuncture: {
points: updated,
method: p.clinical_data?.acupuncture?.method || '',
},
},
}));
};
// Explanation Helpers
const handleExplanationChange = (eIdx: number, val: string) => {
updateActivePattern(p => {
const list = [...(p.clinical_data?.explanation || [])];
list[eIdx] = val;
return {
...p,
clinical_data: { ...p.clinical_data, explanation: list },
};
});
};
const handleAddExplanation = () => {
updateActivePattern(p => ({
...p,
clinical_data: {
...p.clinical_data,
explanation: [...(p.clinical_data?.explanation || []), ''],
},
}));
};
const handleRemoveExplanation = (eIdx: number) => {
updateActivePattern(p => ({
...p,
clinical_data: {
...p.clinical_data,
explanation: (p.clinical_data?.explanation || []).filter((_, i) => i !== eIdx),
},
}));
};
// Save Full Disease & Patterns with Granular Validation
const handleSaveFullDisease = async () => {
if (!selectedCategoryCode) {
setError('Please select or create a Category before saving.');
return;
}
const effectiveDiseaseName = diseaseName.trim();
if (!effectiveDiseaseName) {
setError('Please enter a Disease Name before saving.');
return;
}
if (!patterns || patterns.length === 0) {
setError('A disease must contain at least one clinical pattern before saving.');
return;
}
// Validate Pattern Names & Duplicates
const seenPatternNames = new Set<string>();
for (let i = 0; i < patterns.length; i++) {
const pName = patterns[i]?.name?.trim();
if (!pName) {
setActivePatternIndex(i);
setError(`Clinical Pattern #${i + 1} is missing a name. Please enter a pattern name.`);
return;
}
const lower = pName.toLowerCase();
if (seenPatternNames.has(lower)) {
setActivePatternIndex(i);
setError(`Duplicate pattern name "${pName}". Each clinical pattern within a disease must have a distinct name.`);
return;
}
seenPatternNames.add(lower);
}
// Validate Symptoms exist
for (let i = 0; i < patterns.length; i++) {
const cleanSymptoms = (patterns[i].clinical_data?.clinical_manifestations || []).filter(s => s && s.trim().length > 0);
if (cleanSymptoms.length === 0) {
setActivePatternIndex(i);
setError(`Pattern "${patterns[i].name}" has no symptoms. Please enter at least one clinical symptom before saving.`);
return;
}
}
// Validate Points formula exist
for (let i = 0; i < patterns.length; i++) {
const pts = (patterns[i].clinical_data?.acupuncture?.points || '').trim();
if (!pts) {
setActivePatternIndex(i);
setError(`Pattern "${patterns[i].name}" has no acupuncture points. Please select or add at least one point before saving.`);
return;
}
}
const effectiveDiseaseCode = toSnakeCase(effectiveDiseaseName);
setSaving(true);
setError(null);
setSuccessMsg(null);
try {
// 1. Update category overview if changed
await moduleBuilderService.saveCategory(moduleCode, {
category_code: selectedCategoryCode,
name: categories.find(c => c.category_code === selectedCategoryCode)?.name || selectedCategoryCode,
overview: categoryOverview,
});
// 2. Prepare payload
const payload = {
category_code: selectedCategoryCode,
disease_code: effectiveDiseaseCode,
name: effectiveDiseaseName,
overview: diseaseOverview,
patterns: patterns.map((p, idx) => ({
category_code: selectedCategoryCode,
disease_code: effectiveDiseaseCode,
pattern_code: toSnakeCase(p.name?.trim() || `pattern_${idx + 1}`),
name: p.name?.trim() || `Pattern ${idx + 1}`,
description: p.description || '',
clinical_data: {
clinical_manifestations: (p.clinical_data?.clinical_manifestations || []).filter(s => s && s.trim().length > 0),
tongue: (p.clinical_data?.tongue || '').trim(),
pulse: (p.clinical_data?.pulse || '').trim(),
treatment_principle: (p.clinical_data?.treatment_principle || '').trim(),
acupuncture: {
points: (p.clinical_data?.acupuncture?.points || '').trim(),
method: (p.clinical_data?.acupuncture?.method || '').trim(),
},
explanation: (p.clinical_data?.explanation || []).filter(e => e && e.trim().length > 0),
},
sort_order: idx,
})),
};
await moduleBuilderService.saveFullDisease(moduleCode, payload);
setIsCreatingNewDisease(false);
setSelectedDiseaseCode(effectiveDiseaseCode);
setSuccessMsg('All disease details and clinical patterns saved successfully!');
setTimeout(() => setSuccessMsg(null), 4000);
await fetchCategories(moduleCode, selectedCategoryCode, effectiveDiseaseCode);
} catch (err: any) {
setError(formatApiError(err, 'Failed to save changes. Please check all fields and try again.'));
} finally {
setSaving(false);
}
};
// Download Module JSON
const handleDownloadJson = async () => {
if (categories.length === 0) {
setError('No module content to download. Please create a category and disease, or load the sample template first.');
return;
}
setDownloading(true);
setError(null);
try {
const data = await moduleBuilderService.exportModuleJson(moduleCode);
const jsonStr = JSON.stringify(data, null, 2);
const blob = new Blob([jsonStr], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = `module_builder_${moduleCode}.json`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
setSuccessMsg(`Downloaded module_builder_${moduleCode}.json successfully!`);
setTimeout(() => setSuccessMsg(null), 4500);
} catch (err: any) {
setError(formatApiError(err, 'Failed to export module JSON. Please try again.'));
} finally {
setDownloading(false);
}
};
// Download Production ZIP Package
const handleExportZip = async () => {
if (categories.length === 0) {
setError('Cannot export package: Please add at least one category to this module first.');
return;
}
setExportingZip(true);
setError(null);
setShowExportMenu(false);
try {
const { blob, filename } = await moduleBuilderService.exportBundleZip(moduleCode);
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
setSuccessMsg(`Production bundle "${filename}" downloaded successfully!`);
setTimeout(() => setSuccessMsg(null), 4500);
} catch (err: any) {
if (err?.response?.data instanceof Blob) {
try {
const text = await err.response.data.text();
const parsed = JSON.parse(text);
setError(parsed.detail || 'Failed to export module bundle package.');
} catch {
setError(formatApiError(err, 'Failed to export module bundle package.'));
}
} else {
setError(formatApiError(err, 'Failed to export module bundle package.'));
}
} finally {
setExportingZip(false);
}
};
// Sync Directly to acupedia-content Repository
const handleSyncContentRepo = async () => {
if (categories.length === 0) {
setError('Cannot sync repository: Please add at least one category to this module first.');
return;
}
const confirmed = window.confirm(
`Compile and sync module "${activeModule?.name || moduleCode}" directly to the server's content repository?\n\n` +
`This will write compiled production files (module.json, templates, data, search_facets) into the local repository on the server.\n\n` +
`Tip: To save the module files directly to your personal computer, use "Download Acupedia (.zip)" instead.`
);
if (!confirmed) return;
setSyncingRepo(true);
setError(null);
setShowExportMenu(false);
try {
const res = await moduleBuilderService.syncContentRepo(moduleCode);
setSuccessMsg(res.message || `Successfully synced ${moduleCode} to acupedia-content repository!`);
setTimeout(() => setSuccessMsg(null), 5000);
} catch (err: any) {
setError(formatApiError(err, 'Failed to sync module to content repository.'));
} finally {
setSyncingRepo(false);
}
};
// Switch Active Module
const handleSwitchModule = (newCode: string) => {
if (newCode === moduleCode) {
setShowModuleDropdown(false);
return;
}
setModuleCode(newCode);
localStorage.setItem('acupedia_active_module_builder_code', newCode);
setShowModuleDropdown(false);
setSelectedCategoryCode('');
setSelectedDiseaseCode('');
setDiseaseName('');
setDiseaseOverview('');
setPatterns([]);
setIsCreatingNewDisease(false);
};
// Auto-suggest next module code
const getSuggestedNextModuleCode = (): string => {
const codes = modules
.map(m => m.code)
.filter(c => /^m\d{4}$/.test(c))
.map(c => parseInt(c.slice(1), 10));
const nextNum = (codes.length > 0 ? Math.max(...codes) : 42) + 1;
return `m${String(nextNum).padStart(4, '0')}`;
};
// Create New Module Handler
const handleCreateModule = async (e: React.FormEvent) => {
e.preventDefault();
const cleanName = newModuleName.trim();
if (!cleanName) {
setModalModError('Please enter a module name.');
return;
}
const codeToUse = newModuleCode.trim().toLowerCase();
if (codeToUse && !/^m[0-9]{4}$/.test(codeToUse)) {
setModalModError("Module code must start with 'm' followed by 4 digits (e.g. 'm0043').");
return;
}
if (codeToUse && modules.some(m => m.code === codeToUse)) {
setModalModError(`Module code "${codeToUse}" is already taken. Please choose another.`);
return;
}
setCreatingModule(true);
setModalModError(null);
setError(null);
try {
const created = await moduleBuilderService.createModule({
name: cleanName,
code: codeToUse || undefined,
short_description: newModuleDesc.trim() || undefined,
kind: 'therapeutic',
managed_by: 'module_builder',
});
setShowNewModuleModal(false);
setNewModuleName('');
setNewModuleCode('');
setNewModuleDesc('');
setModalModError(null);
setSuccessMsg(`Module "${created.name}" (${created.code}) created successfully!`);
setTimeout(() => setSuccessMsg(null), 4000);
// Refresh modules list and switch active module
await fetchModules(created.code);
} catch (err: any) {
setModalModError(formatApiError(err, 'Failed to create module.'));
} finally {
setCreatingModule(false);
}
};
// Delete Module Handler
const handleDeleteModule = async () => {
if (!activeModule) return;
const confirmed = window.confirm(
`Are you sure you want to permanently delete module "${activeModule.name}" (${activeModule.code})?\n\n` +
`WARNING: This will delete ALL ${activeModule.category_count} categories, ${activeModule.disease_count} diseases, and ${activeModule.pattern_count} patterns contained in this module. This action cannot be undone.`
);
if (!confirmed) return;
setLoading(true);
setError(null);
try {
await moduleBuilderService.deleteModule(moduleCode);
setSuccessMsg(`Module "${activeModule.name}" deleted successfully.`);
setTimeout(() => setSuccessMsg(null), 4000);
await fetchModules();
} catch (err: any) {
setError(formatApiError(err, 'Failed to delete module.'));
} finally {
setLoading(false);
}
};
// Seed sample Gynecological content if completely empty
const handleSeedSampleData = async () => {
if (categories.length > 0 && !window.confirm('Sample template will add standard Gynecological Disorders to the current database. Continue?')) {
return;
}
setLoading(true);
setError(null);
try {
const sampleContents = [
{
name: 'Diseases after Childbirth',
code: 'diseases_after_childbirth',
overview: 'Pathologies arising during the puerperium, typically categorized as blood deficiency or blood stasis.',
diseases: [
{
name: 'Abdominal Pain after Childbirth',
code: 'abdominal_pain_after_childbirth',
overview: 'The pathology of Abdominal Pain after Childbirth is characterized by either a deficiency or an excess condition. Deficient Blood and Qi cause mild abdominal pain better with pressure and eating. Excess conditions like Blood stasis cause severe stabbing pain worse with pressure.',
patterns: [
{
name: 'Blood deficiency',
code: 'blood_deficiency',
description: 'Dull abdominal pain relieved by pressure and after eating',
clinical_manifestations: [
'Dull abdominal pain after childbirth which is relieved by pressure and after eating',
'Scanty, but continuous uterine bleeding which is pale in color',
'Dizziness',
'Tiredness',
'Blurred vision',
'Constipation',
],
tongue: 'Pale and Thin.',
pulse: 'Choppy.',
treatment_principle: 'Tonify Qi, nourish Blood, stop pain.',
acupuncture: {
points: 'RN-6, RN-4, ST-36, SP-6, LR-8',
method: 'All with reinforcing method, moxa is applicable.',
},
explanation: [
'RN-6 tonifies Qi in general and moves Qi in the abdomen.',
'RN-4 nourishes Blood and strengthens the Uterus.',
'ST-36 and SP-6 tonify Qi and Blood.',
'LR-8 nourishes Liver-Blood.',
],
},
{
name: 'Blood Stasis',
code: 'blood_stasis',
description: 'Sharp, stabbing abdominal pain worse with pressure',
clinical_manifestations: [
'Abdominal pain after childbirth that is worse with pressure and worse after eating',
'Discharge of dark lochia',
'Dark complexion',
'Cold limbs',
],
tongue: 'Purple.',
pulse: 'Deep and Wiry.',
treatment_principle: 'Invigorate Blood, eliminate stasis, scatter Cold, stop pain.',
acupuncture: {
points: 'SP-4, PC-6, ST-30, KI-14, SP-10, BL-17, SP-6, LR-3, ST-29',
method: 'All with reducing or even method. Moxa can be used if there are symptoms of Cold.',
},
explanation: [
'SP-4 and PC-6 regulate the Penetrating Vessel, subdue rebellious Qi and eliminate stasis in the abdomen.',
'ST-30 regulates Qi and Blood in this vessel.',
'KI-14 moves Qi and Blood in this vessel and stops abdominal pain.',
],
},
],
},
{
name: 'Fever after Childbirth',
code: 'fever_after_childbirth',
overview: 'Postpartum fever can be due to external infection, blood deficiency, blood stasis, or food stagnation.',
patterns: [
{
name: 'Blood deficiency with mild fever',
code: 'fever_blood_deficiency',
description: 'Low-grade fever in the afternoon or evening accompanied by palpitations and dizziness.',
clinical_manifestations: [
'Low-grade fever',
'Dizziness and blurred vision',
'Palpitations',
'Insomnia',
'Pale complexion',
],
tongue: 'Pale.',
pulse: 'Fine and Rapid.',
treatment_principle: 'Nourish Blood, clear heat.',
acupuncture: {
points: 'ST-36, SP-6, BL-20, BL-17, RN-4',
method: 'Reinforcing method.',
},
explanation: [
'ST-36 and SP-6 nourish Qi and Blood to clear deficient heat.',
'RN-4 tonifies the Uterus and replenishes postpartum Blood.',
],
},
],
},
],
},
{
name: 'Diseases of Pregnancy',
code: 'diseases_of_pregnancy',
overview: 'Conditions affecting women during gestational periods requiring careful point selection avoiding contraindicated points.',
diseases: [
{
name: 'Morning Sickness (Nausea and Vomiting)',
code: 'morning_sickness',
overview: 'Nausea and vomiting during early pregnancy due to rebellious Qi in the Penetrating Vessel.',
patterns: [
{
name: 'Disharmony of Stomach and Chong Mai',
code: 'disharmony_stomach_chong',
description: 'Nausea and vomiting of clear fluid soon after eating.',
clinical_manifestations: [
'Nausea and vomiting',
'Fullness in the epigastrium',
'Tiredness',
'Poor appetite',
],
tongue: 'Pale with white coating.',
pulse: 'Slippery and Weak.',
treatment_principle: 'Subdue rebellious Qi, harmonize Stomach.',
acupuncture: {
points: 'PC-6, CV-12, ST-36, SP-4',
method: 'Even or mild reinforcing method.',
},
explanation: [
'PC-6 opens the chest and subdues rebellious Stomach Qi.',
'CV-12 harmonizes the Middle Burner.',
],
},
],
},
],
},
];
await moduleBuilderService.importModuleJson(moduleCode, sampleContents);
setSuccessMsg('Sample Gynecological Disorders template imported successfully!');
fetchModules();
await fetchCategories(moduleCode);
} catch (err: any) {
setError(formatApiError(err, 'Failed to import sample template data.'));
} finally {
setLoading(false);
}
};
const isFormActive = Boolean(selectedDiseaseCode || isCreatingNewDisease);
return (
<div className="space-y-6">
{/* Top Banner & Context Bar */}
<div className="bg-white border border-slate-200 rounded-2xl p-5 shadow-sm space-y-4">
<div className="flex flex-col md:flex-row items-start md:items-center justify-between gap-4">
<div className="flex items-center gap-3">
<div className="h-10 w-10 rounded-xl bg-indigo-600 text-white flex items-center justify-center shadow-md shadow-indigo-600/20">
<Layers className="h-5 w-5" />
</div>
<div>
<h3 className="text-lg font-black text-slate-900 tracking-tight flex flex-wrap items-center gap-2">
Clinical Module Builder
{/* Module Selector Dropdown */}
<div className="relative inline-block">
<button
type="button"
onClick={() => setShowModuleDropdown(!showModuleDropdown)}
className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-indigo-50 hover:bg-indigo-100 border border-indigo-200 text-indigo-700 font-bold text-xs transition-colors shadow-2xs"
>
<span>{activeModule?.name || 'Gynecological Disorders'} ({moduleCode.toUpperCase()})</span>
<ChevronDown className="h-3.5 w-3.5 text-indigo-500" />
</button>
{showModuleDropdown && (
<>
<div
className="fixed inset-0 z-40"
onClick={() => setShowModuleDropdown(false)}
/>
<div className="absolute left-0 mt-2 w-72 bg-white rounded-2xl shadow-xl border border-slate-200 py-2 z-50">
<div className="px-3.5 py-1.5 text-[10px] font-black uppercase tracking-wider text-slate-400">
Active Clinical Modules
</div>
<div className="max-h-60 overflow-y-auto divide-y divide-slate-100">
{modules.map((m) => (
<button
key={m.code}
type="button"
onClick={() => handleSwitchModule(m.code)}
className={`w-full text-left px-3.5 py-2.5 flex items-center justify-between hover:bg-indigo-50/50 transition-colors ${m.code === moduleCode ? 'bg-indigo-50/70 text-indigo-900 font-bold' : 'text-slate-700'
}`}
>
<div>
<div className="text-xs font-bold flex items-center gap-1.5">
<span>{m.name}</span>
<span className="font-mono text-[10px] px-1.5 py-0.2 rounded bg-slate-100 text-slate-600 uppercase">
{m.code}
</span>
</div>
<div className="text-[10px] text-slate-400 font-medium">
{m.category_count} categories · {m.disease_count} diseases
</div>
</div>
<div className="flex items-center gap-1.5 shrink-0">
{m.code === moduleCode && <Check className="h-4 w-4 text-indigo-600" />}
{m.code !== 'm0042' && (
<button
type="button"
onClick={(e) => {
e.stopPropagation();
handleDeleteModule();
}}
className="p-1 hover:bg-rose-100 text-slate-300 hover:text-rose-600 rounded-lg transition-colors"
title={`Delete module ${m.name}`}
>
<Trash2 className="h-3 w-3" />
</button>
)}
</div>
</button>
))}
</div>
<div className="p-2 border-t border-slate-100 mt-1">
<button
type="button"
onClick={() => {
setShowModuleDropdown(false);
setNewModuleName('');
setNewModuleCode(getSuggestedNextModuleCode());
setNewModuleDesc('');
setModalModError(null);
setShowNewModuleModal(true);
}}
className="w-full py-2 px-3 bg-indigo-600 hover:bg-indigo-500 text-white rounded-xl text-xs font-bold flex items-center justify-center gap-1.5 shadow-sm transition-colors"
>
<Plus className="h-3.5 w-3.5" />
<span>+ Create New Module</span>
</button>
</div>
</div>
</>
)}
</div>
</h3>
<p className="text-xs text-slate-500 font-medium">
Author and customize disease categories, clinical patterns, and treatment formulas.
</p>
</div>
</div>
{/* Action Toolbar */}
<div className="flex flex-wrap items-center gap-2 self-end md:self-auto">
{/* Quick Guide Toggle */}
<button
type="button"
onClick={() => setShowQuickGuide(!showQuickGuide)}
className="px-3 py-2 bg-slate-100 hover:bg-slate-200 text-slate-700 text-xs font-bold rounded-xl flex items-center gap-1.5 transition-colors"
>
<HelpCircle className="h-3.5 w-3.5 text-indigo-600" />
<span>Guide</span>
{showQuickGuide ? <ChevronUp className="h-3 w-3" /> : <ChevronDown className="h-3 w-3" />}
</button>
{/* Revert to Blank Form Button */}
<button
type="button"
onClick={handleResetToBlankForm}
disabled={loading || saving || !selectedCategoryCode}
className="px-3.5 py-2 bg-amber-50 hover:bg-amber-100 disabled:bg-slate-100 disabled:text-slate-400 border border-amber-300 text-amber-800 text-xs font-bold rounded-xl flex items-center gap-1.5 transition-all shadow-xs"
title="Clear all fields and start authoring a new disease from scratch"
>
<RotateCcw className="h-3.5 w-3.5 text-amber-600" />
Reset to Blank Form
</button>
{/* Live Clinical Preview Button */}
<button
type="button"
onClick={() => {
if (!isFormActive) {
setError('Please select or author a disease first to preview its clinical card.');
return;
}
setPreviewPatternIdx(0);
setShowPreviewModal(true);
}}
disabled={!isFormActive}
className="px-3.5 py-2 bg-slate-100 hover:bg-slate-200 disabled:bg-slate-100 disabled:text-slate-400 text-slate-700 text-xs font-bold rounded-xl flex items-center gap-1.5 transition-colors"
title="Preview clinical presentation card"
>
<Eye className="h-3.5 w-3.5 text-indigo-600" />
Preview Card
</button>
{/* Export & Package Menu */}
<div className="relative inline-block">
<button
type="button"
onClick={() => setShowExportMenu(!showExportMenu)}
disabled={downloading || exportingZip || syncingRepo || categories.length === 0}
className="px-3.5 py-2 bg-slate-900 hover:bg-slate-800 disabled:bg-slate-300 text-white text-xs font-bold rounded-xl flex items-center gap-1.5 shadow transition-colors"
title="Export or publish clinical module"
>
{exportingZip || syncingRepo ? (
<RefreshCw className="h-3.5 w-3.5 animate-spin" />
) : (
<Package className="h-3.5 w-3.5" />
)}
<span>Export & Publish</span>
<ChevronDown className="h-3 w-3 opacity-70" />
</button>
{showExportMenu && (
<>
<div
className="fixed inset-0 z-40"
onClick={() => setShowExportMenu(false)}
/>
<div className="absolute right-0 mt-2 w-64 bg-white rounded-2xl shadow-xl border border-slate-200 py-2 z-50">
<div className="px-3.5 py-1.5 text-[10px] font-black uppercase tracking-wider text-slate-400">
Production Packaging
</div>
<button
type="button"
onClick={() => {
setShowExportMenu(false);
handleExportZip();
}}
disabled={exportingZip}
className="w-full text-left px-3.5 py-2.5 hover:bg-indigo-50/50 flex items-start gap-2.5 transition-colors group"
>
<FileArchive className="h-4 w-4 text-indigo-600 mt-0.5 shrink-0" />
<div>
<div className="text-xs font-bold text-slate-800 group-hover:text-indigo-600">
Download Acupedia (.zip)
</div>
<div className="text-[10px] text-slate-400">
Download complete package with module.json, templates/, & data/ to your computer
</div>
</div>
</button>
{syncRepoEnabled && (
<button
type="button"
onClick={() => {
setShowExportMenu(false);
handleSyncContentRepo();
}}
disabled={syncingRepo}
className="w-full text-left px-3.5 py-2.5 hover:bg-emerald-50/50 flex items-start gap-2.5 transition-colors group"
>
<UploadCloud className="h-4 w-4 text-emerald-600 mt-0.5 shrink-0" />
<div>
<div className="text-xs font-bold text-slate-800 group-hover:text-emerald-600">
Sync to Server Repository
</div>
<div className="text-[10px] text-slate-400">
Compile and write directly to server content repository
</div>
</div>
</button>
)}
<div className="my-1 border-t border-slate-100" />
<button
type="button"
onClick={() => {
setShowExportMenu(false);
handleDownloadJson();
}}
disabled={downloading}
className="w-full text-left px-3.5 py-2 hover:bg-slate-50 flex items-center gap-2.5 text-slate-600 text-xs font-semibold"
>
<Download className="h-3.5 w-3.5 text-slate-400" />
<span>Download Raw JSON (Backup)</span>
</button>
</div>
</>
)}
</div>
{categories.length === 0 && (
<button
type="button"
onClick={handleSeedSampleData}
disabled={loading}
className="px-3.5 py-2 bg-emerald-600 hover:bg-emerald-500 text-white text-xs font-bold rounded-xl flex items-center gap-1.5 shadow transition-colors"
>
<Sparkles className="h-3.5 w-3.5" />
Load Sample Template
</button>
)}
{/* Save Button */}
<button
type="button"
onClick={handleSaveFullDisease}
disabled={saving || !isFormActive}
className="px-4 py-2 bg-indigo-600 hover:bg-indigo-500 disabled:bg-slate-300 text-white text-xs font-bold rounded-xl flex items-center gap-1.5 shadow-md shadow-indigo-600/20 transition-all"
>
{saving ? <RefreshCw className="h-3.5 w-3.5 animate-spin" /> : <Save className="h-3.5 w-3.5" />}
Save Changes
</button>
</div>
</div>
{/* Quick User Guide (Expandable) */}
{showQuickGuide && (
<div className="p-4 bg-indigo-50/70 border border-indigo-100 rounded-2xl space-y-3 transition-all animate-fade-in">
<div className="flex items-center justify-between">
<h4 className="text-xs font-black text-indigo-900 uppercase tracking-wider flex items-center gap-1.5">
<HelpCircle className="h-4 w-4 text-indigo-600" /> Quick Guide: How to Use the Module Builder
</h4>
<button
type="button"
onClick={() => setShowQuickGuide(false)}
className="text-indigo-400 hover:text-indigo-700"
>
<X className="h-3.5 w-3.5" />
</button>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3 text-xs">
<div className="p-3 bg-white border border-indigo-100 rounded-xl space-y-1">
<span className="h-5 w-5 rounded-full bg-indigo-600 text-white font-black text-[10px] flex items-center justify-center">1</span>
<p className="font-bold text-slate-800">Disease Category</p>
<p className="text-[11px] text-slate-500 leading-relaxed">
Select a category or click <strong>+ Add Category</strong>. Enter the human name; system codes are generated automatically in lowercase underscore format.
</p>
</div>
<div className="p-3 bg-white border border-indigo-100 rounded-xl space-y-1">
<span className="h-5 w-5 rounded-full bg-indigo-600 text-white font-black text-[10px] flex items-center justify-center">2</span>
<p className="font-bold text-slate-800">Choose or Blank Form</p>
<p className="text-[11px] text-slate-500 leading-relaxed">
Pick an existing disease or click <strong>Reset to Blank Form</strong>. Enter the disease name; the code is created automatically as <code>underscore_format</code>.
</p>
</div>
<div className="p-3 bg-white border border-indigo-100 rounded-xl space-y-1">
<span className="h-5 w-5 rounded-full bg-indigo-600 text-white font-black text-[10px] flex items-center justify-center">3</span>
<p className="font-bold text-slate-800">Clinical Patterns</p>
<p className="text-[11px] text-slate-500 leading-relaxed">
Click pattern tabs. Type symptoms (hit Enter for next row), pick tongue & pulse pills, and click point badges.
</p>
</div>
<div className="p-3 bg-white border border-indigo-100 rounded-xl space-y-1">
<span className="h-5 w-5 rounded-full bg-indigo-600 text-white font-black text-[10px] flex items-center justify-center">4</span>
<p className="font-bold text-slate-800">Download & Seed</p>
<p className="text-[11px] text-slate-500 leading-relaxed">
Save your changes, then click <strong>Download JSON</strong> to get the verified <code>module_builder.json</code> file to place into Acupedia content.
</p>
</div>
</div>
</div>
)}
{/* Category & Disease Selector Controls */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-4 pt-2 border-t border-slate-100">
{/* Category Dropdown */}
<div className="space-y-1.5">
<div className="flex justify-between items-center">
<label className="text-[11px] uppercase font-black tracking-wider text-slate-500 flex items-center gap-1">
<BookOpen className="h-3.5 w-3.5 text-indigo-500" /> 1. Disease Category
</label>
<div className="flex items-center gap-2">
<button
type="button"
onClick={() => {
setNewCategoryName('');
setModalCatError(null);
setShowNewCategoryModal(true);
}}
className="text-indigo-600 hover:text-indigo-800 text-[11px] font-bold flex items-center gap-0.5"
>
<Plus className="h-3 w-3" /> Add Category
</button>
{selectedCategoryCode && (
<button
type="button"
onClick={handleDeleteCategory}
className="text-rose-500 hover:text-rose-700 text-[11px] font-bold flex items-center gap-0.5 ml-2"
title="Delete Category"
>
<Trash2 className="h-3 w-3" />
</button>
)}
</div>
</div>
<select
value={selectedCategoryCode}
onChange={(e) => {
const val = e.target.value;
setSelectedCategoryCode(val);
setError(null);
const catObj = categories.find(c => c.category_code === val);
setCategoryOverview(catObj?.overview || '');
fetchDiseases(val);
}}
disabled={loading || categories.length === 0}
className="w-full bg-slate-50 border border-slate-200 rounded-xl px-3 py-2 text-xs font-bold text-slate-800 focus:outline-none focus:border-indigo-500 cursor-pointer"
>
{categories.length === 0 && <option value="">No categories available</option>}
{categories.map((cat) => (
<option key={cat.category_code} value={cat.category_code}>
{cat.name} ({cat.disease_count} diseases)
</option>
))}
</select>
</div>
{/* Disease Dropdown */}
<div className="space-y-1.5">
<div className="flex justify-between items-center">
<label className="text-[11px] uppercase font-black tracking-wider text-slate-500 flex items-center gap-1">
<ChevronRight className="h-3.5 w-3.5 text-indigo-500" /> 2. Specific Disease
</label>
<div className="flex items-center gap-2">
<button
type="button"
onClick={() => {
if (!selectedCategoryCode) {
setError('Please select or create a category before adding a disease.');
return;
}
setNewDiseaseName('');
setModalDisError(null);
setShowNewDiseaseModal(true);
}}
disabled={!selectedCategoryCode}
className="text-indigo-600 hover:text-indigo-800 disabled:text-slate-400 text-[11px] font-bold flex items-center gap-0.5"
>
<Plus className="h-3 w-3" /> Add Disease
</button>
{selectedDiseaseCode && (
<button
type="button"
onClick={handleDeleteDisease}
className="text-rose-500 hover:text-rose-700 text-[11px] font-bold flex items-center gap-0.5 ml-2"
title="Delete Disease"
>
<Trash2 className="h-3 w-3" />
</button>
)}
</div>
</div>
<select
value={isCreatingNewDisease ? '__new__' : selectedDiseaseCode}
onChange={(e) => {
setError(null);
if (e.target.value === '__new__') {
handleResetToBlankForm();
} else if (!e.target.value) {
setSelectedDiseaseCode('');
setDiseaseName('');
setDiseaseOverview('');
setPatterns([]);
setIsCreatingNewDisease(false);
} else {
setIsCreatingNewDisease(false);
setSelectedDiseaseCode(e.target.value);
}
}}
disabled={loading || (diseases.length === 0 && !isCreatingNewDisease)}
className="w-full bg-slate-50 border border-slate-200 rounded-xl px-3 py-2 text-xs font-bold text-slate-800 focus:outline-none focus:border-indigo-500 cursor-pointer"
>
{isCreatingNewDisease && (
<option value="__new__">✨ Blank Disease (In Progress...)</option>
)}
{diseases.length === 0 && !isCreatingNewDisease ? (
<option value="">No diseases in this category</option>
) : (
<option value="">-- Select a Disease ({diseases.length} available) --</option>
)}
{diseases.map((dis) => (
<option key={dis.disease_code} value={dis.disease_code}>
{dis.name} ({dis.pattern_count} patterns)
</option>
))}
</select>
</div>
</div>
{/* Feedback Banners with Dismiss Button */}
{error && (
<div className="p-3 bg-rose-50 border border-rose-200 text-rose-700 text-xs rounded-xl font-semibold flex items-center justify-between gap-2 animate-fade-in shadow-xs">
<div className="flex items-center gap-2 min-w-0">
<AlertCircle className="h-4 w-4 shrink-0 text-rose-600" />
<span className="break-words">{error}</span>
</div>
<button
type="button"
onClick={() => setError(null)}
className="text-rose-400 hover:text-rose-700 p-1 shrink-0"
title="Dismiss error"
>
<X className="h-3.5 w-3.5" />
</button>
</div>
)}
{successMsg && (
<div className="p-3 bg-emerald-50 border border-emerald-200 text-emerald-700 text-xs rounded-xl font-semibold flex items-center justify-between gap-2 shadow-xs">
<div className="flex items-center gap-2 min-w-0">
<CheckCircle2 className="h-4 w-4 shrink-0 text-emerald-600" />
<span>{successMsg}</span>
</div>
<button
type="button"
onClick={() => setSuccessMsg(null)}
className="text-emerald-400 hover:text-emerald-700 p-1 shrink-0"
title="Dismiss"
>
<X className="h-3.5 w-3.5" />
</button>
</div>
)}
</div>
{/* Main Phased Form Canvas */}
{isFormActive ? (
<div className="grid grid-cols-1 gap-6">
{/* Disease Pathology Card */}
<div className="bg-white border border-slate-200 rounded-2xl p-5 shadow-sm space-y-3">
<div className="flex items-center justify-between">
<h4 className="text-sm font-black text-slate-900 tracking-tight flex items-center gap-1.5">
<Stethoscope className="h-4 w-4 text-indigo-600" />
Disease Pathology & Overview
</h4>
<div className="flex items-center gap-2">
{isCreatingNewDisease && (
<span className="text-[10px] px-2 py-0.5 rounded-full bg-amber-100 text-amber-800 font-bold">
Authoring New
</span>
)}
<span className="text-[10px] px-2.5 py-1 rounded-lg bg-slate-100 border border-slate-200 text-slate-600 font-mono font-bold">
System Code: {toSnakeCase(diseaseName || selectedDiseaseCode || 'new_disease')}
</span>
</div>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
{/* Disease Name Only (Code generated internally) */}
<div className="space-y-1">
<label className="text-[10px] uppercase font-bold text-slate-500">
Disease Name <span className="text-rose-500">*</span>
</label>
<input
type="text"
value={diseaseName}
onChange={(e) => {
setDiseaseName(e.target.value);
if (error) setError(null);
}}
onBlur={() => {
if (diseaseName.trim()) {
setDiseaseName(toTitleCase(diseaseName.trim()));
}
}}
className="w-full bg-slate-50 border border-slate-200 rounded-xl px-3 py-2 text-xs font-bold text-slate-800 focus:outline-none focus:border-indigo-500"
placeholder="e.g. Period Pain"
/>
</div>
{/* Category Overview */}
<div className="space-y-1">
<label className="text-[10px] uppercase font-bold text-slate-500">
Category Context Notes
</label>
<input
type="text"
value={categoryOverview}
onChange={(e) => setCategoryOverview(e.target.value)}
className="w-full bg-slate-50 border border-slate-200 rounded-xl px-3 py-2 text-xs font-medium text-slate-800 focus:outline-none focus:border-indigo-500"
placeholder="General category notes"
/>
</div>
</div>
{/* Disease Pathology Description */}
<div className="space-y-1">
<label className="text-[10px] uppercase font-bold text-slate-500">
Detailed Disease Overview / Etiology
</label>
<textarea
rows={3}
value={diseaseOverview}
onChange={(e) => setDiseaseOverview(e.target.value)}
className="w-full bg-slate-50 border border-slate-200 rounded-xl p-3 text-xs text-slate-800 focus:outline-none focus:border-indigo-500 leading-relaxed font-medium resize-y"
placeholder="Explain the primary etiology, deficiency vs. excess mechanisms, classical quotes..."
/>
</div>
</div>
{/* Pattern Differentiation & Clinical Data Form */}
<div className="bg-white border border-slate-200 rounded-2xl p-5 shadow-sm space-y-5">
{/* Pattern Tabs Header */}
<div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3 border-b border-slate-100 pb-3">
<div>
<h4 className="text-sm font-black text-slate-900 tracking-tight flex items-center gap-1.5">
<HeartPulse className="h-4 w-4 text-rose-500" />
Clinical Patterns ({patterns.length})
</h4>
<p className="text-[11px] text-slate-500">
Select a clinical pattern tab to customize manifestations, tongue, pulse, and acupuncture prescription.
</p>
</div>
<button
type="button"
onClick={handleAddPattern}
className="px-3 py-1.5 bg-indigo-50 hover:bg-indigo-100 border border-indigo-200 text-indigo-700 text-xs font-bold rounded-xl flex items-center gap-1 transition-colors"
>
<Plus className="h-3.5 w-3.5" />
Add Pattern
</button>
</div>
{/* Pattern Tabs Pills */}
<div className="flex flex-wrap gap-2">
{patterns.map((pat, idx) => (
<div
key={idx}
className={`flex items-center gap-1 px-3 py-1.5 rounded-xl text-xs font-bold transition-all cursor-pointer ${safePatternIndex === idx
? 'bg-indigo-600 text-white shadow-sm shadow-indigo-600/30'
: 'bg-slate-100 hover:bg-slate-200 text-slate-700'
}`}
onClick={() => {
setActivePatternIndex(idx);
if (error) setError(null);
}}
>
<span>{pat?.name || `Pattern ${idx + 1}`}</span>
{patterns.length > 1 && (
<button
type="button"
onClick={(e) => {
e.stopPropagation();
handleRemovePattern(idx);
}}
className={`h-4 w-4 rounded-full flex items-center justify-center hover:bg-black/10 transition-colors ml-1 ${safePatternIndex === idx ? 'text-white' : 'text-slate-400 hover:text-slate-700'
}`}
title="Delete pattern"
>
<X className="h-2.5 w-2.5" />
</button>
)}
</div>
))}
</div>
{/* Active Pattern Fields */}
{activePattern ? (
<div className="space-y-5 pt-2">
{/* Pattern Identification (Name only -> Code auto-generated) */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="space-y-1">
<label className="text-[10px] uppercase font-bold text-slate-500">
Pattern Name <span className="text-rose-500">*</span>
</label>
<input
type="text"
value={activePattern.name || ''}
onChange={(e) => {
const val = e.target.value;
updateActivePattern(p => ({
...p,
name: val,
pattern_code: toSnakeCase(val || 'pattern'),
}));
if (error) setError(null);
}}
onBlur={() => {
if (activePattern.name?.trim()) {
updateActivePattern(p => ({
...p,
name: toTitleCase(activePattern.name.trim()),
}));
}
}}
placeholder="e.g. Blood Deficiency"
className="w-full bg-slate-50 border border-slate-200 rounded-xl px-3 py-2 text-xs font-bold text-slate-800 focus:outline-none focus:border-indigo-500"
/>
</div>
<div className="space-y-1">
<label className="text-[10px] uppercase font-bold text-slate-500">Auto-Generated System Code</label>
<div className="w-full bg-slate-100 border border-slate-200 rounded-xl px-3 py-2 text-xs font-mono font-bold text-slate-600 flex items-center">
{toSnakeCase(activePattern.name || 'primary_pattern')}
</div>
</div>
</div>
<div className="space-y-1">
<label className="text-[10px] uppercase font-bold text-slate-500">Pattern Description / Summary</label>
<input
type="text"
value={activePattern.description || ''}
onChange={(e) => updateActivePattern(p => ({ ...p, description: e.target.value }))}
placeholder="Brief summary of key characteristics"
className="w-full bg-slate-50 border border-slate-200 rounded-xl px-3 py-2 text-xs font-medium text-slate-800 focus:outline-none focus:border-indigo-500"
/>
</div>
{/* Clinical Manifestations (Symptoms List) */}
<div className="space-y-2">
<div className="flex justify-between items-center">
<label className="text-[10px] uppercase font-bold text-slate-500">
🩺 Clinical Manifestations & Symptoms ({activePattern.clinical_data?.clinical_manifestations?.length || 0}) <span className="text-rose-500">*</span>
</label>
<button
type="button"
onClick={handleAddSymptom}
className="text-indigo-600 hover:text-indigo-800 text-[11px] font-bold flex items-center gap-1"
>
<Plus className="h-3 w-3" /> Add Symptom
</button>
</div>
<div className="space-y-2">
{(activePattern.clinical_data?.clinical_manifestations || []).map((sym, sIdx) => (
<div key={sIdx} className="flex items-center gap-2">
<span className="text-[11px] font-mono text-slate-400 w-5 text-right">{sIdx + 1}.</span>
<input
type="text"
value={sym}
onChange={(e) => handleSymptomChange(sIdx, e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.preventDefault();
handleAddSymptom();
}
}}
placeholder="e.g. Dull abdominal pain after childbirth relieved by pressure..."
className="flex-1 bg-slate-50 border border-slate-200 rounded-xl px-3 py-2 text-xs text-slate-800 focus:outline-none focus:border-indigo-500 font-medium"
/>
<button
type="button"
onClick={() => handleRemoveSymptom(sIdx)}
className="p-1.5 text-slate-400 hover:text-rose-500 transition-colors"
title="Remove Symptom"
>
<Trash2 className="h-3.5 w-3.5" />
</button>
</div>
))}
{(activePattern.clinical_data?.clinical_manifestations || []).length === 0 && (
<p className="text-xs text-slate-400 italic">No symptoms added. Click "Add Symptom" above.</p>
)}
</div>
</div>
{/* Tongue & Pulse Diagnosis */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
{/* Tongue */}
<div className="space-y-1.5">
<label className="text-[10px] uppercase font-bold text-slate-500">👅 Tongue Diagnosis</label>
<input
type="text"
value={activePattern.clinical_data?.tongue || ''}
onChange={(e) =>
updateActivePattern(p => ({
...p,
clinical_data: { ...p.clinical_data, tongue: e.target.value },
}))
}
placeholder="e.g. Pale and Thin."
className="w-full bg-slate-50 border border-slate-200 rounded-xl px-3 py-2 text-xs font-bold text-slate-800 focus:outline-none focus:border-indigo-500"
/>
<div className="flex flex-wrap gap-1.5 pt-1">
{COMMON_TONGUE_SUGGESTIONS.map((t, idx) => (
<button
key={idx}
type="button"
onClick={() =>
updateActivePattern(p => ({
...p,
clinical_data: { ...p.clinical_data, tongue: t },
}))
}
className="text-[10px] px-2 py-0.5 rounded-lg bg-slate-100 hover:bg-slate-200 text-slate-600 font-medium"
>
{t}
</button>
))}
</div>
</div>
{/* Pulse */}
<div className="space-y-1.5">
<label className="text-[10px] uppercase font-bold text-slate-500">💓 Pulse Diagnosis</label>
<input
type="text"
value={activePattern.clinical_data?.pulse || ''}
onChange={(e) =>
updateActivePattern(p => ({
...p,
clinical_data: { ...p.clinical_data, pulse: e.target.value },
}))
}
placeholder="e.g. Choppy."
className="w-full bg-slate-50 border border-slate-200 rounded-xl px-3 py-2 text-xs font-bold text-slate-800 focus:outline-none focus:border-indigo-500"
/>
<div className="flex flex-wrap gap-1.5 pt-1">
{COMMON_PULSE_SUGGESTIONS.map((pls, idx) => (
<button
key={idx}
type="button"
onClick={() =>
updateActivePattern(p => ({
...p,
clinical_data: { ...p.clinical_data, pulse: pls },
}))
}
className="text-[10px] px-2 py-0.5 rounded-lg bg-slate-100 hover:bg-slate-200 text-slate-600 font-medium"
>
{pls}
</button>
))}
</div>
</div>
</div>
{/* Treatment Principle */}
<div className="space-y-1">
<label className="text-[10px] uppercase font-bold text-slate-500">🎯 Treatment Principle</label>
<input
type="text"
value={activePattern.clinical_data?.treatment_principle || ''}
onChange={(e) =>
updateActivePattern(p => ({
...p,
clinical_data: { ...p.clinical_data, treatment_principle: e.target.value },
}))
}
placeholder="e.g. Tonify Qi, nourish Blood, stop pain."
className="w-full bg-slate-50 border border-slate-200 rounded-xl px-3 py-2 text-xs font-bold text-slate-800 focus:outline-none focus:border-indigo-500"
/>
</div>
{/* Acupuncture Formula & Points Chips */}
<div className="space-y-3 p-4 bg-slate-50 border border-slate-200 rounded-2xl">
<h5 className="text-xs font-black text-slate-800 uppercase tracking-wider flex items-center gap-1.5">
📍 Acupuncture Prescription <span className="text-rose-500">*</span>
</h5>
{/* Active Point Chips */}
<div className="space-y-1.5">
<label className="text-[10px] uppercase font-bold text-slate-500">Selected Point Chips</label>
<div className="flex flex-wrap items-center gap-1.5 min-h-[38px] p-2 bg-white border border-slate-200 rounded-xl">
{currentPoints.map((pt, pIdx) => (
<span
key={pIdx}
className="inline-flex items-center gap-1 px-2.5 py-1 rounded-lg bg-indigo-50 border border-indigo-200 text-indigo-700 text-xs font-black shadow-xs"
>
{pt}
<button
type="button"
onClick={() => handleRemovePointChip(pt)}
className="text-indigo-400 hover:text-indigo-700"
title="Remove point"
>
<X className="h-3 w-3" />
</button>
</span>
))}
<input
type="text"
value={customPointInput}
onChange={(e) => setCustomPointInput(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.preventDefault();
handleAddPointChip(customPointInput);
}
}}
placeholder={currentPoints.length === 0 ? 'Type point (e.g. RN-6) and hit Enter...' : '+ add...'}
className="text-xs font-semibold text-slate-800 focus:outline-none bg-transparent min-w-[120px] px-1 py-0.5"
/>
</div>
</div>
{/* Quick Suggestions for Points */}
<div className="flex flex-wrap items-center gap-1.5 pt-1">
<span className="text-[10px] text-slate-400 font-bold uppercase mr-1">Quick Add:</span>
{COMMON_POINT_SUGGESTIONS.map((pt, idx) => {
const isAdded = currentPoints.includes(pt);
return (
<button
key={idx}
type="button"
onClick={() => handleAddPointChip(pt)}
disabled={isAdded}
className={`text-[10px] font-bold px-2 py-0.5 rounded-lg border transition-all ${isAdded
? 'bg-slate-200 text-slate-400 border-slate-200 cursor-default'
: 'bg-white hover:bg-indigo-50 border-slate-200 hover:border-indigo-300 text-slate-700 hover:text-indigo-600'
}`}
>
+{pt}
</button>
);
})}
</div>
{/* Needling Method */}
<div className="space-y-1 pt-2">
<label className="text-[10px] uppercase font-bold text-slate-500">Needling Method & Technique</label>
<input
type="text"
value={activePattern.clinical_data?.acupuncture?.method || ''}
onChange={(e) =>
updateActivePattern(p => ({
...p,
clinical_data: {
...p.clinical_data,
acupuncture: {
points: p.clinical_data?.acupuncture?.points || '',
method: e.target.value,
},
},
}))
}
placeholder="e.g. All with reinforcing method, moxa is applicable."
className="w-full bg-white border border-slate-200 rounded-xl px-3 py-2 text-xs font-semibold text-slate-800 focus:outline-none focus:border-indigo-500"
/>
</div>
</div>
{/* Point Explanations */}
<div className="space-y-2">
<div className="flex justify-between items-center">
<label className="text-[10px] uppercase font-bold text-slate-500">
💡 Point-by-Point Explanations ({activePattern.clinical_data?.explanation?.length || 0})
</label>
<button
type="button"
onClick={handleAddExplanation}
className="text-indigo-600 hover:text-indigo-800 text-[11px] font-bold flex items-center gap-1"
>
<Plus className="h-3 w-3" /> Add Explanation
</button>
</div>
<div className="space-y-2">
{(activePattern.clinical_data?.explanation || []).map((exp, eIdx) => (
<div key={eIdx} className="flex items-center gap-2">
<span className="text-[11px] font-mono text-slate-400 w-5 text-right">•</span>
<input
type="text"
value={exp}
onChange={(e) => handleExplanationChange(eIdx, e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.preventDefault();
handleAddExplanation();
}
}}
placeholder="e.g. RN-6 tonifies Qi in general and moves Qi in the abdomen."
className="flex-1 bg-slate-50 border border-slate-200 rounded-xl px-3 py-2 text-xs text-slate-800 focus:outline-none focus:border-indigo-500 font-medium"
/>
<button
type="button"
onClick={() => handleRemoveExplanation(eIdx)}
className="p-1.5 text-slate-400 hover:text-rose-500 transition-colors"
title="Remove Explanation"
>
<Trash2 className="h-3.5 w-3.5" />
</button>
</div>
))}
{(activePattern.clinical_data?.explanation || []).length === 0 && (
<p className="text-xs text-slate-400 italic">No explanations added yet.</p>
)}
</div>
</div>
</div>
) : (
<div className="p-6 text-center text-xs text-slate-400 italic">
No active pattern selected. Click "+ Add Pattern" above.
</div>
)}
</div>
</div>
) : (
<div className="p-12 text-center bg-white border border-slate-200 rounded-2xl shadow-sm space-y-4">
<BookOpen className="h-10 w-10 text-slate-300 mx-auto" />
<div className="space-y-1">
<h4 className="text-sm font-bold text-slate-700">No Disease Selected</h4>
<p className="text-xs text-slate-400 max-w-md mx-auto">
Choose an existing disease from the dropdown above, click <strong>+ Add Disease</strong>, or start with a <strong>Blank Form</strong> to author a new condition.
</p>
</div>
<div className="flex flex-wrap items-center justify-center gap-3 pt-2">
<button
type="button"
onClick={() => {
if (!selectedCategoryCode) {
setError('Please select or create a Category first.');
return;
}
setNewDiseaseName('');
setModalDisError(null);
setShowNewDiseaseModal(true);
}}
disabled={!selectedCategoryCode}
className="px-4 py-2 bg-indigo-600 hover:bg-indigo-500 disabled:bg-slate-200 disabled:text-slate-400 text-white text-xs font-bold rounded-xl flex items-center gap-1.5 shadow transition-all"
>
<Plus className="h-4 w-4" /> Add Disease
</button>
<button
type="button"
onClick={handleResetToBlankForm}
disabled={!selectedCategoryCode}
className="px-4 py-2 bg-amber-50 hover:bg-amber-100 disabled:bg-slate-100 disabled:text-slate-400 border border-amber-300 text-amber-800 text-xs font-bold rounded-xl flex items-center gap-1.5 transition-all shadow-xs"
>
<RotateCcw className="h-3.5 w-3.5 text-amber-600" /> Start Blank Form
</button>
</div>
</div>
)}
{/* MODAL: Clinical Card Preview */}
{showPreviewModal && (
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-900/60 backdrop-blur-xs">
<div className="bg-white rounded-3xl p-6 w-full max-w-3xl shadow-2xl border border-slate-100 max-h-[90vh] overflow-y-auto space-y-5">
<div className="flex justify-between items-center pb-3 border-b border-slate-100">
<div className="flex items-center gap-2">
<div className="h-8 w-8 rounded-lg bg-indigo-50 text-indigo-600 flex items-center justify-center">
<Stethoscope className="h-4 w-4" />
</div>
<div>
<h4 className="text-base font-black text-slate-900">{diseaseName || 'Untitled Disease'}</h4>
<p className="text-xs text-slate-400">
Category: {categories.find(c => c.category_code === selectedCategoryCode)?.name || selectedCategoryCode}
</p>
</div>
</div>
<button
type="button"
onClick={() => setShowPreviewModal(false)}
className="text-slate-400 hover:text-slate-600 p-1"
>
<X className="h-5 w-5" />
</button>
</div>
{/* Disease Pathology Overview */}
{diseaseOverview && (
<div className="p-4 bg-slate-50 border border-slate-200 rounded-2xl space-y-1">
<h5 className="text-[10px] uppercase font-black text-slate-400 tracking-wider">Pathology & Etiology</h5>
<p className="text-xs text-slate-700 leading-relaxed font-medium">{diseaseOverview}</p>
</div>
)}
{/* Pattern Tabs */}
{patterns.length > 0 && (
<div className="space-y-4">
<div className="flex flex-wrap gap-2 border-b border-slate-100 pb-2">
{patterns.map((p, idx) => (
<button
key={idx}
type="button"
onClick={() => setPreviewPatternIdx(idx)}
className={`px-3 py-1.5 rounded-xl text-xs font-bold transition-all ${previewPatternIdx === idx
? 'bg-indigo-600 text-white shadow-xs'
: 'bg-slate-100 hover:bg-slate-200 text-slate-700'
}`}
>
{p.name || `Pattern ${idx + 1}`}
</button>
))}
</div>
{patterns[previewPatternIdx] && (
<div className="space-y-4 p-4 border border-indigo-100 bg-indigo-50/20 rounded-2xl">
<div>
<h5 className="text-sm font-black text-indigo-950">{patterns[previewPatternIdx].name}</h5>
{patterns[previewPatternIdx].description && (
<p className="text-xs text-slate-600 mt-0.5">{patterns[previewPatternIdx].description}</p>
)}
</div>
{/* Symptoms */}
<div className="space-y-1.5">
<h6 className="text-[10px] uppercase font-black text-slate-400">Key Manifestations</h6>
<ul className="space-y-1 text-xs text-slate-700">
{(patterns[previewPatternIdx].clinical_data?.clinical_manifestations || []).map((s, idx) => (
<li key={idx} className="flex items-start gap-1.5">
<span className="text-indigo-600 font-bold">•</span>
<span>{s}</span>
</li>
))}
</ul>
</div>
{/* Tongue & Pulse Grid */}
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3 text-xs">
<div className="p-3 bg-white rounded-xl border border-slate-200">
<span className="text-[10px] font-black uppercase text-slate-400 block mb-0.5">Tongue</span>
<span className="font-bold text-slate-800">
{patterns[previewPatternIdx].clinical_data?.tongue || '—'}
</span>
</div>
<div className="p-3 bg-white rounded-xl border border-slate-200">
<span className="text-[10px] font-black uppercase text-slate-400 block mb-0.5">Pulse</span>
<span className="font-bold text-slate-800">
{patterns[previewPatternIdx].clinical_data?.pulse || '—'}
</span>
</div>
</div>
{/* Treatment Principle */}
<div className="p-3 bg-white rounded-xl border border-amber-200 text-xs">
<span className="text-[10px] font-black uppercase text-amber-600 block mb-0.5">Treatment Principle</span>
<span className="font-bold text-slate-800">
{patterns[previewPatternIdx].clinical_data?.treatment_principle || '—'}
</span>
</div>
{/* Acupuncture Prescription */}
<div className="p-4 bg-white rounded-xl border border-indigo-100 space-y-2 text-xs">
<span className="text-[10px] font-black uppercase text-indigo-600 block">Acupuncture Points</span>
<div className="flex flex-wrap gap-1.5">
{(patterns[previewPatternIdx].clinical_data?.acupuncture?.points || '')
.split(',')
.map(s => s.trim())
.filter(Boolean)
.map((pt, idx) => (
<span key={idx} className="px-2 py-0.5 rounded-md bg-indigo-50 border border-indigo-200 text-indigo-700 font-black text-xs">
{pt}
</span>
))}
</div>
{patterns[previewPatternIdx].clinical_data?.acupuncture?.method && (
<p className="text-[11px] text-slate-600 italic pt-1">
<strong>Method:</strong> {patterns[previewPatternIdx].clinical_data.acupuncture.method}
</p>
)}
</div>
{/* Point Explanations */}
{(patterns[previewPatternIdx].clinical_data?.explanation || []).length > 0 && (
<div className="space-y-1 text-xs">
<span className="text-[10px] font-black uppercase text-slate-400 block">Explanations</span>
<ul className="space-y-1 text-slate-600 text-[11px]">
{(patterns[previewPatternIdx].clinical_data?.explanation || []).map((exp, idx) => (
<li key={idx} className="flex items-start gap-1.5">
<span className="text-slate-400">•</span>
<span>{exp}</span>
</li>
))}
</ul>
</div>
)}
</div>
)}
</div>
)}
<div className="flex justify-between items-center pt-3 border-t border-slate-100">
<button
type="button"
onClick={handleDownloadJson}
className="px-4 py-2 bg-slate-900 hover:bg-slate-800 text-white text-xs font-bold rounded-xl flex items-center gap-1.5"
>
<Download className="h-3.5 w-3.5" /> Download Full JSON
</button>
<button
type="button"
onClick={() => setShowPreviewModal(false)}
className="px-4 py-2 bg-slate-100 hover:bg-slate-200 text-slate-700 text-xs font-bold rounded-xl"
>
Close Preview
</button>
</div>
</div>
</div>
)}
{/* MODAL: New Category (Name only -> Code auto-generated) */}
{showNewCategoryModal && (
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-900/50 backdrop-blur-xs">
<div className="bg-white rounded-3xl p-6 w-full max-w-md shadow-2xl border border-slate-100 space-y-4 animate-scale-in">
<div className="flex justify-between items-center">
<h4 className="text-base font-black text-slate-900 flex items-center gap-2">
<FolderPlus className="h-5 w-5 text-indigo-600" /> Add Disease Category
</h4>
<button
type="button"
onClick={() => {
setShowNewCategoryModal(false);
setModalCatError(null);
}}
className="text-slate-400 hover:text-slate-600"
>
<X className="h-4 w-4" />
</button>
</div>
{modalCatError && (
<div className="p-3 bg-rose-50 border border-rose-200 text-rose-700 text-xs rounded-xl font-semibold flex items-center justify-between gap-2">
<div className="flex items-center gap-2">
<AlertCircle className="h-4 w-4 shrink-0 text-rose-600" />
<span>{modalCatError}</span>
</div>
<button
type="button"
onClick={() => setModalCatError(null)}
className="text-rose-400 hover:text-rose-700 p-0.5"
>
<X className="h-3 w-3" />
</button>
</div>
)}
<form onSubmit={handleCreateCategory} className="space-y-4">
<div className="space-y-2">
<label className="text-[11px] uppercase font-bold text-slate-700">Category Name <span className="text-rose-500">*</span></label>
<input
type="text"
required
autoFocus
value={newCategoryName}
onChange={(e) => {
setNewCategoryName(e.target.value);
if (modalCatError) setModalCatError(null);
}}
placeholder="e.g. Diseases after Childbirth"
className="w-full bg-slate-50 border border-slate-200 rounded-xl px-3 py-2.5 text-xs font-bold text-slate-800 focus:outline-none focus:border-indigo-500"
/>
<div className="text-[11px] text-slate-500 flex items-center gap-1.5 font-mono bg-slate-100 px-3 py-1.5 rounded-lg border border-slate-200">
<span className="text-slate-400">System Code (Auto):</span>
<span className="font-bold text-indigo-600">
{toSnakeCase(newCategoryName) || '...'}
</span>
</div>
<p className="text-[11px] text-slate-400">
Enter only the readable name. The system generates the standard underscore code automatically.
</p>
</div>
<div className="flex justify-end gap-2 pt-2">
<button
type="button"
onClick={() => {
setShowNewCategoryModal(false);
setModalCatError(null);
}}
className="px-4 py-2 bg-slate-100 hover:bg-slate-200 text-slate-700 text-xs font-bold rounded-xl"
>
Cancel
</button>
<button
type="submit"
disabled={saving || !newCategoryName.trim()}
className="px-4 py-2 bg-indigo-600 hover:bg-indigo-500 disabled:bg-slate-300 text-white text-xs font-bold rounded-xl shadow font-semibold"
>
{saving ? 'Creating...' : 'Create Category'}
</button>
</div>
</form>
</div>
</div>
)}
{/* Create New Module Modal */}
{showNewModuleModal && (
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-900/40 backdrop-blur-xs">
<div className="bg-white rounded-2xl max-w-md w-full p-6 shadow-2xl border border-slate-200 space-y-4">
<div className="flex items-center justify-between pb-2 border-b border-slate-100">
<div className="flex items-center gap-2">
<div className="p-2 rounded-xl bg-indigo-50 text-indigo-600">
<Package className="h-4 w-4" />
</div>
<h4 className="text-sm font-black text-slate-900">Create New Therapeutic Module</h4>
</div>
<button
type="button"
onClick={() => {
setShowNewModuleModal(false);
setModalModError(null);
}}
className="text-slate-400 hover:text-slate-600"
>
<X className="h-4 w-4" />
</button>
</div>
{modalModError && (
<div className="p-3 bg-rose-50 border border-rose-200 text-rose-700 text-xs rounded-xl font-semibold flex items-center justify-between gap-2">
<div className="flex items-center gap-2">
<AlertCircle className="h-4 w-4 shrink-0 text-rose-600" />
<span>{modalModError}</span>
</div>
<button
type="button"
onClick={() => setModalModError(null)}
className="text-rose-400 hover:text-rose-700 p-0.5"
>
<X className="h-3 w-3" />
</button>
</div>
)}
<form onSubmit={handleCreateModule} className="space-y-4">
<div className="space-y-2">
<label className="text-[11px] uppercase font-bold text-slate-700">
Module Name <span className="text-rose-500">*</span>
</label>
<input
type="text"
required
autoFocus
value={newModuleName}
onChange={(e) => {
setNewModuleName(e.target.value);
if (modalModError) setModalModError(null);
}}
placeholder="e.g. Pediatric Disorders"
className="w-full bg-slate-50 border border-slate-200 rounded-xl px-3 py-2.5 text-xs font-bold text-slate-800 focus:outline-none focus:border-indigo-500"
/>
</div>
<div className="space-y-2">
<label className="text-[11px] uppercase font-bold text-slate-700">
Module Code (e.g. m0043)
</label>
<input
type="text"
value={newModuleCode}
onChange={(e) => {
setNewModuleCode(e.target.value.toLowerCase().trim());
if (modalModError) setModalModError(null);
}}
placeholder="e.g. m0043"
className="w-full bg-slate-50 border border-slate-200 rounded-xl px-3 py-2.5 text-xs font-mono font-bold text-indigo-600 focus:outline-none focus:border-indigo-500"
/>
<p className="text-[11px] text-slate-400">
Must start with 'm' followed by 4 digits. Leave as suggested or customize.
</p>
</div>
<div className="space-y-2">
<label className="text-[11px] uppercase font-bold text-slate-700">
Short Description
</label>
<input
type="text"
value={newModuleDesc}
onChange={(e) => setNewModuleDesc(e.target.value)}
placeholder="e.g. TCM pediatrics and children's health"
className="w-full bg-slate-50 border border-slate-200 rounded-xl px-3 py-2 text-xs text-slate-800 focus:outline-none focus:border-indigo-500"
/>
</div>
<div className="text-[11px] text-slate-500 flex items-center justify-between font-mono bg-slate-100 px-3 py-1.5 rounded-lg border border-slate-200">
<span className="text-slate-400">System Slug:</span>
<span className="font-bold text-indigo-600">
{toSnakeCase(newModuleName).replace(/_/g, '-') || '...'}
</span>
</div>
<div className="flex items-center justify-between text-[11px] bg-emerald-50/60 border border-emerald-200 text-emerald-800 px-3 py-1.5 rounded-lg font-mono">
<span>Kind: <strong className="uppercase">therapeutic</strong></span>
<span className="text-slate-300">|</span>
<span>Managed By: <strong>module_builder</strong></span>
</div>
<div className="flex justify-end gap-2 pt-2">
<button
type="button"
onClick={() => {
setShowNewModuleModal(false);
setModalModError(null);
}}
className="px-4 py-2 bg-slate-100 hover:bg-slate-200 text-slate-700 text-xs font-bold rounded-xl"
>
Cancel
</button>
<button
type="submit"
disabled={creatingModule || !newModuleName.trim()}
className="px-4 py-2 bg-indigo-600 hover:bg-indigo-500 disabled:bg-slate-300 text-white text-xs font-bold rounded-xl shadow"
>
{creatingModule ? 'Creating Module...' : 'Create Module'}
</button>
</div>
</form>
</div>
</div>
)}
{/* MODAL: New Disease (Name only -> Code auto-generated) */}
{showNewDiseaseModal && (
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-900/50 backdrop-blur-xs">
<div className="bg-white rounded-3xl p-6 w-full max-w-md shadow-2xl border border-slate-100 space-y-4 animate-scale-in">
<div className="flex justify-between items-center">
<h4 className="text-base font-black text-slate-900 flex items-center gap-2">
<FilePlus className="h-5 w-5 text-indigo-600" /> Add Disease to Category
</h4>
<button
type="button"
onClick={() => {
setShowNewDiseaseModal(false);
setModalDisError(null);
}}
className="text-slate-400 hover:text-slate-600"
>
<X className="h-4 w-4" />
</button>
</div>
{modalDisError && (
<div className="p-3 bg-rose-50 border border-rose-200 text-rose-700 text-xs rounded-xl font-semibold flex items-center justify-between gap-2">
<div className="flex items-center gap-2">
<AlertCircle className="h-4 w-4 shrink-0 text-rose-600" />
<span>{modalDisError}</span>
</div>
<button
type="button"
onClick={() => setModalDisError(null)}
className="text-rose-400 hover:text-rose-700 p-0.5"
>
<X className="h-3 w-3" />
</button>
</div>
)}
<form onSubmit={handleCreateDisease} className="space-y-4">
<div className="space-y-2">
<label className="text-[11px] uppercase font-bold text-slate-700">Disease Name <span className="text-rose-500">*</span></label>
<input
type="text"
required
autoFocus
value={newDiseaseName}
onChange={(e) => {
setNewDiseaseName(e.target.value);
if (modalDisError) setModalDisError(null);
}}
placeholder="e.g. Period Pain"
className="w-full bg-slate-50 border border-slate-200 rounded-xl px-3 py-2.5 text-xs font-bold text-slate-800 focus:outline-none focus:border-indigo-500"
/>
<div className="text-[11px] text-slate-500 flex items-center gap-1.5 font-mono bg-slate-100 px-3 py-1.5 rounded-lg border border-slate-200">
<span className="text-slate-400">System Code (Auto):</span>
<span className="font-bold text-indigo-600">
{toSnakeCase(newDiseaseName) || '...'}
</span>
</div>
<p className="text-[11px] text-slate-400">
Enter only the readable disease name. The system generates the standard underscore code automatically.
</p>
</div>
<div className="flex justify-end gap-2 pt-2">
<button
type="button"
onClick={() => {
setShowNewDiseaseModal(false);
setModalDisError(null);
}}
className="px-4 py-2 bg-slate-100 hover:bg-slate-200 text-slate-700 text-xs font-bold rounded-xl"
>
Cancel
</button>
<button
type="submit"
disabled={saving || !newDiseaseName.trim() || !selectedCategoryCode}
className="px-4 py-2 bg-indigo-600 hover:bg-indigo-500 disabled:bg-slate-300 text-white text-xs font-bold rounded-xl shadow font-semibold"
>
{saving ? 'Creating...' : 'Create Disease'}
</button>
</div>
</form>
</div>
</div>
)}
</div>
);
};
export const ModuleBuilderTab: React.FC = () => (
<ErrorBoundary fallbackTitle="Module Builder encountered an error">
<ModuleBuilderTabContent />
</ErrorBoundary>
);