import React, { useMemo, useState } from "react"; import { LayoutAnimation, Platform, Pressable, ScrollView, StyleSheet, Text, UIManager, View, } from "react-native"; import { Ionicons } from "@expo/vector-icons"; import { useRouter } from "expo-router"; import { moderateScale, verticalScale } from "react-native-size-matters"; import { Colors, Radius } from "@/theme"; import { useSettingsStore } from "@/store/settings.store"; import type { DetailRendererProps } from "../../types/renderer.types"; import { useModuleTemplateContentDetailsQuery } from "../../hooks/use-content-queries"; import { buildContentReferenceRoute, parseNavigableContentReference, } from "../../utils/content-reference"; import { asRecord, asRecordArray, asString, asStringArray, } from "../helpers/value"; import { BulletList } from "../shared/BulletList"; import { ContentLinkAttributeSections } from "../shared/ContentLinkAttributeSections"; import { Hero } from "../shared/Hero"; import { OverviewCard } from "../shared/OverviewCard"; import { Images } from "./categoryParts"; if (Platform.OS === "android" && UIManager.setLayoutAnimationEnabledExperimental) { UIManager.setLayoutAnimationEnabledExperimental(true); } interface PointItemProps { key?: React.Key; item: Record; defaultExpanded: boolean; moduleCode: string; pointsCatalogMap?: Map; } function sanitizeMeridianHeading(meridian: string, chineseName: string): string { const cleanChinese = chineseName.replace(/^\((.*)\)$/, "$1").trim(); // Strip meridian abbreviation codes or point codes in parentheses, // e.g. (ST), (LU-9), (LI), (LV), (LR), (PC), (GB), (HT), etc. const cleanedMeridian = meridian .replace(/\s*\(\s*[A-Z]{1,4}(?:[\s\-_]*\d+)?\s*\)\s*/g, " ") .replace(/\s+/g, " ") .trim(); if (cleanedMeridian && cleanChinese) { if (cleanedMeridian.toLowerCase().includes(cleanChinese.toLowerCase())) { return cleanedMeridian; } return `${cleanedMeridian} (${cleanChinese})`; } return cleanedMeridian || cleanChinese || "Point"; } function PointAccordionCard({ item, defaultExpanded, moduleCode, pointsCatalogMap, }: PointItemProps) { const router = useRouter(); const [expanded, setExpanded] = useState(defaultExpanded); const meridian = asString(item.meridian).trim(); const chineseName = asString(item.chinese_name).trim(); const element = asString(item.element).trim(); const caution = asString(item.caution).trim(); const cautionList = asStringArray(item.caution); const actions = asStringArray(item.actions); const indications = asStringArray(item.indications); // Format header title: e.g. "Stomach (Chongyang)", "Lung (Taiyuan)" const title = useMemo(() => { return sanitizeMeridianHeading(meridian, chineseName); }, [meridian, chineseName]); // Resolve point reference for linkable button const rawPoint = asRecord(item.point); const directRef = parseNavigableContentReference(item.point); // Extract candidate point codes/labels: e.g. "LU 9", "LU-9" const pointLabel = directRef?.label?.trim() || asString(rawPoint.label).trim() || (rawPoint.target && typeof rawPoint.target === "object" ? asString((rawPoint.target as Record).source_code).trim() : "") || ""; // Construct button display label: e.g. "LU-9 (Taiyuan)" or "LU 9 (Taiyuan)" const pointButtonLabel = useMemo(() => { const baseCode = pointLabel || "Point Details"; if (chineseName && !baseCode.toLowerCase().includes(chineseName.toLowerCase())) { return `${baseCode} (${chineseName})`; } return baseCode; }, [pointLabel, chineseName]); // Resolve navigation destination const navigateToPoint = () => { if (directRef) { router.push(buildContentReferenceRoute(directRef) as never); return; } if (rawPoint.target && typeof rawPoint.target === "object") { const target = rawPoint.target as Record; const targetModule = asString(target.module_code).trim() || moduleCode || "m0001"; const targetTemplate = asString(target.template_code).trim() || "m0001_ct0003"; const contentId = asString(target.content_id).trim(); const sourceCode = asString(target.source_code).trim(); if (contentId) { router.push( `/modules/${encodeURIComponent(targetModule)}/${encodeURIComponent(targetTemplate)}/${encodeURIComponent(contentId)}` as never, ); return; } // Fallback: match by catalog map (from m0001_ct0003) using sourceCode or label if (pointsCatalogMap && sourceCode) { const found = pointsCatalogMap.get(sourceCode.toLowerCase()) || pointsCatalogMap.get(sourceCode.replace(/[- ]/g, "").toLowerCase()); if (found) { router.push( `/modules/${encodeURIComponent(targetModule)}/${encodeURIComponent(targetTemplate)}/${encodeURIComponent(found.contentId)}` as never, ); return; } } } // Secondary fallback matching by pointLabel in catalog if (pointsCatalogMap && pointLabel) { const found = pointsCatalogMap.get(pointLabel.toLowerCase()) || pointsCatalogMap.get(pointLabel.replace(/[- ]/g, "").toLowerCase()); if (found) { router.push( `/modules/${encodeURIComponent(moduleCode || "m0001")}/m0001_ct0003/${encodeURIComponent(found.contentId)}` as never, ); } } }; const toggle = () => { LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut); setExpanded((prev) => !prev); }; return ( {/* Accordion Header */} [ styles.cardHeader, expanded && styles.cardHeaderExpanded, pressed && styles.pressed, ]} > {title} {element ? ( {element} ) : null} {/* Accordion Body (Expanded State) */} {expanded ? ( {/* Actions */} {actions.length > 0 ? ( ACTIONS {actions.length === 1 ? ( {actions[0]} ) : ( )} ) : null} {/* Indications */} {indications.length > 0 ? ( INDICATIONS ) : null} {/* Caution (same UI as Actions and Indications) */} {caution ? ( CAUTION {cautionList.length > 1 ? ( ) : ( {caution} )} ) : null} {/* Linkable Point Button (matching standard ReferenceChipList styling) */} {pointLabel ? ( [ styles.pointLinkButton, pressed && styles.pressed, ]} > {pointButtonLabel} ) : null} ) : null} ); } export function YuanSourceDetailRenderer({ moduleCode = "m0001", content, data, definitions, presentationAttributes, }: DetailRendererProps) { const accordionDefaultExpanded = useSettingsStore( (state) => state.accordionDefaultExpanded, ); // Fetch points from m0001_ct0003 for robust ID navigation fallback const { data: pointsCatalog } = useModuleTemplateContentDetailsQuery({ module_code: moduleCode || "m0001", template_code: "m0001_ct0003", }); const pointsCatalogMap = useMemo(() => { const map = new Map(); if (pointsCatalog?.items) { for (const item of pointsCatalog.items) { const id = item.content.id; const title = item.content.title; const code = asString(item.data.code).trim().toLowerCase(); const name = asString(item.data.name).trim().toLowerCase(); if (code) { map.set(code, { contentId: id, title }); map.set(code.replace(/[- ]/g, ""), { contentId: id, title }); } if (name) { map.set(name, { contentId: id, title }); } } } return map; }, [pointsCatalog]); const rawTitle = asString(data.title) || asString(data.name) || content.title || "Yuan Source"; const altNames = asStringArray(data.alt_name); const descriptionParagraphs = asStringArray(data.description); const points = asRecordArray(data.points); return ( {/* Screen Title & Subtitle */} 0 ? altNames.join(" ยท ") : undefined} /> {/* Visual images (if any assigned) */} {/* Overview Section */} {descriptionParagraphs.length > 0 ? ( ) : null} {/* Points Accordion List */} {points.length > 0 ? ( {points.map((pointItem, index) => ( ))} ) : null} {/* Generic content link attributes (excluding points already rendered above) */} ); } const styles = StyleSheet.create({ container: { paddingHorizontal: moderateScale(16), paddingTop: verticalScale(14), paddingBottom: verticalScale(40), gap: verticalScale(14), }, pointsList: { gap: verticalScale(12), }, card: { backgroundColor: "#FFFFFF", borderRadius: moderateScale(16), borderWidth: 1, borderColor: "#E2E8F0", overflow: "hidden", }, cardHeader: { minHeight: verticalScale(54), paddingHorizontal: moderateScale(14), paddingVertical: verticalScale(12), flexDirection: "row", alignItems: "center", justifyContent: "space-between", backgroundColor: "#FFFFFF", gap: moderateScale(10), }, cardHeaderExpanded: { backgroundColor: "#F0F7F3", borderBottomWidth: 1, borderBottomColor: "#E2E8F0", }, pressed: { opacity: 0.75, }, headerLeft: { flex: 1, flexDirection: "row", alignItems: "center", gap: moderateScale(10), }, headerAccent: { width: moderateScale(4), height: verticalScale(22), borderRadius: moderateScale(2), backgroundColor: Colors.primary, }, headerTitle: { flex: 1, fontSize: moderateScale(15), lineHeight: moderateScale(21), fontWeight: "700", color: "#1E293B", }, headerRight: { flexDirection: "row", alignItems: "center", gap: moderateScale(8), }, elementBadge: { paddingHorizontal: moderateScale(9), paddingVertical: verticalScale(3), borderRadius: moderateScale(10), backgroundColor: "#E8F5E9", borderWidth: 1, borderColor: "#C6E4CE", }, elementBadgeText: { fontSize: 11, lineHeight: 16, fontWeight: "600", color: "#285A44", }, chevron: { width: moderateScale(28), height: moderateScale(28), borderRadius: moderateScale(14), backgroundColor: "#FFFFFFB8", alignItems: "center", justifyContent: "center", borderWidth: 1, borderColor: "#E2E8F0", }, cardBody: { paddingHorizontal: moderateScale(16), paddingTop: verticalScale(14), paddingBottom: verticalScale(16), gap: verticalScale(12), backgroundColor: "#FFFFFF", }, sectionRow: { gap: verticalScale(6), paddingBottom: verticalScale(10), borderBottomWidth: StyleSheet.hairlineWidth, borderBottomColor: "#E8ECEF", }, sectionLabel: { fontSize: 12, lineHeight: 17, fontWeight: "700", color: "#597064", textTransform: "uppercase", letterSpacing: 0.4, }, sectionValue: { fontSize: 16, lineHeight: 25, color: "#334155", }, pointLinkButton: { alignSelf: "flex-start", minHeight: verticalScale(34), paddingHorizontal: moderateScale(12), paddingVertical: verticalScale(6), borderRadius: Radius.full, backgroundColor: "#E8F5E9", borderWidth: 1, borderColor: "#CDE5D0", flexDirection: "row", alignItems: "center", gap: moderateScale(6), marginTop: verticalScale(6), }, pointLinkLabel: { fontSize: moderateScale(13), lineHeight: moderateScale(18), fontWeight: "700", color: Colors.primaryDark, }, });