import React, { useMemo, useState } from "react";
import {
ActivityIndicator,
LayoutAnimation,
Platform,
Pressable,
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 } from "@/theme";
import { asNumber, asString, asStringArray, humanizeKey } from "../helpers/value";
import { CollectionScaffold } from "../shared/CollectionScaffold";
import { ContentCountBadge } from "../shared/ContentCountBadge";
import { greenTone } from "../shared/reading-palette";
import {
useModuleContentDetailQuery,
useModuleTemplateContentDetailsQuery,
} from "../../hooks/use-content-queries";
import type {
CollectionItemRendererProps,
CollectionRendererProps,
} from "../../types/renderer.types";
if (Platform.OS === "android" && UIManager.setLayoutAnimationEnabledExperimental) {
UIManager.setLayoutAnimationEnabledExperimental(true);
}
export function ModuleCatalogCollectionRenderer(props: CollectionRendererProps) {
return ;
}
function normalizePointCode(raw: string): string {
let code = raw.replace(/\s*\([^)]*\)/g, "").trim().toLowerCase();
code = code.replace(/^ren-/, "cv-");
code = code.replace(/^rn-/, "cv-");
code = code.replace(/^du-/, "gv-");
code = code.replace(/^sj-/, "te-");
code = code.replace(/^tb-/, "te-");
code = code.replace(/^liv-/, "lr-");
code = code.replace(/^ub-/, "bl-");
return code;
}
export function PatternAccordionCardRenderer({
item,
}: CollectionItemRendererProps) {
const router = useRouter();
const [expanded, setExpanded] = useState(false);
const attributes = item.attributes;
const rawTitle =
asString(attributes.food_name) ||
asString(attributes.name) ||
item.title;
const title = humanizeKey(rawTitle);
const link = attributes?.link as Record | undefined;
const linkTarget = link?.target as Record | undefined;
const contentId = (linkTarget?.content_id as string) || item.id;
const moduleCode = (linkTarget?.module_code as string) || "m0042";
const detailQuery = useModuleContentDetailQuery(
{ module_code: moduleCode },
contentId,
);
// Query all acupuncture points from m0001 to resolve links
const { data: pointsData } = useModuleTemplateContentDetailsQuery({
module_code: "m0001",
template_code: "m0001_ct0003",
});
const pointsMap = useMemo(() => {
const map = new Map();
if (!pointsData?.items) return map;
for (const pItem of pointsData.items) {
const id = pItem.content.id;
const code = asString(pItem.data.code) || asString(pItem.data.name);
if (code) {
const lower = code.toLowerCase().trim();
map.set(lower, id);
if (lower.startsWith("cv-")) {
map.set(lower.replace("cv-", "ren-"), id);
map.set(lower.replace("cv-", "rn-"), id);
}
if (lower.startsWith("gv-")) {
map.set(lower.replace("gv-", "du-"), id);
}
if (lower.startsWith("te-")) {
map.set(lower.replace("te-", "sj-"), id);
map.set(lower.replace("te-", "tb-"), id);
}
if (lower.startsWith("lr-")) {
map.set(lower.replace("lr-", "liv-"), id);
}
if (lower.startsWith("bl-")) {
map.set(lower.replace("bl-", "ub-"), id);
}
}
if (pItem.content.title) {
map.set(pItem.content.title.toLowerCase().trim(), id);
}
}
return map;
}, [pointsData?.items]);
const handlePointPress = (rawPt: string) => {
const match = rawPt.match(/([A-Za-z]{1,4}-\d{1,2})/);
const pointCode = match ? match[1] : rawPt.trim();
const normalized = normalizePointCode(pointCode);
const pointContentId = pointsMap.get(normalized);
if (pointContentId) {
router.push(`/modules/m0001/m0001_ct0003/${encodeURIComponent(pointContentId)}` as never);
} else {
router.push(`/modules/m0001/search?q=${encodeURIComponent(pointCode)}` as never);
}
};
const toggle = () => {
LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut);
setExpanded((prev) => !prev);
};
const detailData = (detailQuery.data?.data as Record | undefined) || attributes;
// Extract fields matching the user's diagram
const rawManifestations = detailData.clinical_manifestations;
const clinicalManifestations: string[] = Array.isArray(rawManifestations)
? (rawManifestations as string[]).map(String)
: typeof rawManifestations === "string" && rawManifestations.trim()
? rawManifestations.split("\n").map((s) => s.trim()).filter(Boolean)
: [];
const tongue = asString(detailData.tongue);
const pulse = asString(detailData.pulse);
const rawPrinciples = detailData.treatment_principle;
const treatmentPrinciples: string[] = Array.isArray(rawPrinciples)
? (rawPrinciples as string[]).map(String).map((s) => s.trim()).filter(Boolean)
: typeof rawPrinciples === "string" && rawPrinciples.trim()
? rawPrinciples
.split(/[,;\n]/)
.map((s) => s.trim().replace(/^[-*•]\s*/, ""))
.filter(Boolean)
: [];
const rawAcupuncture = detailData.acupuncture;
let acuPoints = "";
let acuMethod = "";
if (rawAcupuncture && typeof rawAcupuncture === "object") {
const acuObj = rawAcupuncture as Record;
acuPoints = asString(acuObj.points);
acuMethod = asString(acuObj.method);
} else if (typeof rawAcupuncture === "string") {
acuPoints = rawAcupuncture;
}
const rawExplanation = detailData.explanation;
const explanations: string[] = Array.isArray(rawExplanation)
? (rawExplanation as string[]).map(String)
: typeof rawExplanation === "string" && rawExplanation.trim()
? rawExplanation.split("\n").map((s) => s.trim()).filter(Boolean)
: [];
const category = asString(detailData.category);
// Split points by comma into chips
const pointChips = acuPoints
? acuPoints.split(/,\s*/).map((p) => p.trim()).filter(Boolean)
: [];
return (
[
accordionStyles.headerRow,
expanded && accordionStyles.headerRowExpanded,
pressed && accordionStyles.pressed,
]}
>
{title}
{expanded ? (
{detailQuery.isLoading && !detailQuery.data ? (
Loading pattern details…
) : (
<>
{/* 1. Clinical Manifestations */}
{clinicalManifestations.length > 0 ? (
Clinical Manifestations
{clinicalManifestations.map((itemText, idx) => (
{itemText}
))}
) : null}
{/* 2. Tongue & Pulse (Side-by-Side as drawn) */}
{tongue || pulse ? (
{tongue ? (
Tongue
{tongue}
) : null}
{tongue && pulse ? : null}
{pulse ? (
Pulse
{pulse}
) : null}
) : null}
{/* 3. Treatment Principle */}
{treatmentPrinciples.length > 0 ? (
Treatment Principle
{treatmentPrinciples.map((itemText, idx) => (
{itemText}
))}
) : null}
{/* 4. Acupuncture Points & Method */}
{pointChips.length > 0 || acuMethod ? (
Acupuncture Points
{pointChips.length > 0 ? (
{pointChips.map((pt, idx) => (
handlePointPress(pt)}
style={({ pressed }) => [
accordionStyles.pointChip,
pressed && accordionStyles.pointChipPressed,
]}
>
{pt}
))}
) : null}
{acuMethod ? (
Method:
{acuMethod}
) : null}
) : null}
{/* 5. Explanation */}
{explanations.length > 0 ? (
Explanation
{explanations.map((exp, idx) => (
{exp}
))}
) : null}
{/* 6. Category */}
{category ? (
Category:
{category}
) : null}
>
)}
) : null}
);
}
export function ModuleCatalogCardRenderer({
item,
onPress,
}: CollectionItemRendererProps) {
const attributes = item.attributes;
const rawTitle =
asString(attributes.food_name) ||
asString(attributes.name) ||
item.title;
const parenMatch = rawTitle.match(/^(.*?)\s*\(([^()]+)\)\s*(.*?)$/);
const title = parenMatch
? [parenMatch[1], parenMatch[3]].filter(Boolean).join(" ").trim()
: rawTitle;
const parenSubtitle = parenMatch ? parenMatch[2].trim() : null;
const rawLabel =
parenSubtitle ||
asString(attributes.sub_title) ||
asString(attributes.subtitle) ||
(asStringArray(attributes.alt_name).length > 0
? asStringArray(attributes.alt_name).join(", ")
: asString(attributes.alt_name)) ||
asString(attributes.pattern_category) ||
asString(attributes.category) ||
asString(attributes.classification) ||
(asString(attributes.title) && asString(attributes.title) !== title
? asString(attributes.title)
: null) ||
asString(attributes.description) ||
item.summary ||
null;
const cleanTitle = humanizeKey(title);
const label = rawLabel ? humanizeKey(rawLabel) : null;
const count = asNumber(attributes.content_count);
const itemCode = asString(attributes.code).toLowerCase().trim();
const rawTitleLower = rawTitle.toLowerCase().trim();
const rawLink = attributes.link as { type?: unknown; target?: unknown } | undefined;
const hasNavigableLink = Boolean(
rawLink && typeof rawLink === "object" && rawLink.type && rawLink.target,
);
const isSpecialDisabled = false;
const isClickable =
!isSpecialDisabled &&
(hasNavigableLink || (count !== null && count > 0) || count === null);
return (
[
styles.row,
isClickable && pressed && styles.pressed,
]}
>
{cleanTitle}
{label ? (
{label}
) : null}
{isClickable ? (
) : null}
);
}
const accordionStyles = StyleSheet.create({
cardContainer: {
backgroundColor: "#FFFFFF",
width: "100%",
},
headerRow: {
minHeight: verticalScale(54),
flexDirection: "row",
alignItems: "center",
paddingHorizontal: moderateScale(14),
paddingVertical: verticalScale(12),
backgroundColor: greenTone.soft,
gap: moderateScale(10),
},
headerRowExpanded: {
borderBottomWidth: StyleSheet.hairlineWidth,
borderBottomColor: greenTone.border,
},
accentBar: {
width: moderateScale(4),
alignSelf: "stretch",
minHeight: verticalScale(26),
borderRadius: moderateScale(999),
backgroundColor: greenTone.accent,
},
accentBarExpanded: {
backgroundColor: greenTone.accent,
},
pressed: {
opacity: 0.74,
},
title: {
flex: 1,
fontSize: moderateScale(15),
lineHeight: moderateScale(21),
fontWeight: "700",
color: greenTone.title,
letterSpacing: 0.1,
},
titleExpanded: {
color: greenTone.title,
},
chevronWrapper: {
width: moderateScale(30),
height: moderateScale(30),
borderRadius: moderateScale(15),
alignItems: "center",
justifyContent: "center",
backgroundColor: "#FFFFFFB8",
},
expandedBody: {
paddingHorizontal: moderateScale(18),
paddingTop: verticalScale(16),
paddingBottom: verticalScale(18),
backgroundColor: "#FFFFFF",
gap: verticalScale(16),
},
loadingRow: {
flexDirection: "row",
alignItems: "center",
justifyContent: "center",
paddingVertical: verticalScale(16),
gap: moderateScale(8),
},
loadingText: {
fontSize: moderateScale(13),
color: "#64748B",
},
section: {
borderBottomWidth: StyleSheet.hairlineWidth,
borderBottomColor: "#E2EAE5",
paddingBottom: verticalScale(14),
gap: verticalScale(8),
},
sectionTitle: {
fontSize: moderateScale(12),
lineHeight: moderateScale(16),
fontWeight: "700",
color: "#4A6B5B",
textTransform: "uppercase",
letterSpacing: 0.7,
},
bulletList: {
gap: verticalScale(8),
},
bulletRow: {
flexDirection: "row",
alignItems: "flex-start",
gap: moderateScale(10),
},
bulletDot: {
width: moderateScale(6),
height: moderateScale(6),
marginTop: verticalScale(7),
borderRadius: moderateScale(3),
backgroundColor: greenTone.accent,
},
bulletText: {
flex: 1,
fontSize: moderateScale(14),
lineHeight: moderateScale(21),
color: "#334155",
},
twoColumnBox: {
flexDirection: "row",
backgroundColor: greenTone.soft,
borderRadius: moderateScale(10),
borderWidth: 1,
borderColor: greenTone.border,
paddingHorizontal: moderateScale(14),
paddingVertical: verticalScale(11),
alignItems: "stretch",
},
column: {
flex: 1,
gap: verticalScale(3),
},
columnDivider: {
width: StyleSheet.hairlineWidth,
backgroundColor: greenTone.border,
marginHorizontal: moderateScale(12),
},
columnLabel: {
fontSize: moderateScale(11),
lineHeight: moderateScale(15),
fontWeight: "700",
color: "#597064",
textTransform: "uppercase",
letterSpacing: 0.5,
},
columnValue: {
fontSize: moderateScale(14),
lineHeight: moderateScale(20),
color: "#1E293B",
fontWeight: "600",
},
principleBox: {
backgroundColor: greenTone.soft,
paddingHorizontal: moderateScale(12),
paddingVertical: verticalScale(10),
borderRadius: moderateScale(8),
borderLeftWidth: moderateScale(3),
borderLeftColor: greenTone.accent,
},
principleText: {
fontSize: moderateScale(14),
lineHeight: moderateScale(21),
color: greenTone.title,
fontStyle: "italic",
},
chipsContainer: {
flexDirection: "row",
flexWrap: "wrap",
gap: moderateScale(7),
},
pointChip: {
flexDirection: "row",
alignItems: "center",
backgroundColor: "#EEF7F1",
borderWidth: 1,
borderColor: "#D5E8DB",
paddingHorizontal: moderateScale(11),
paddingVertical: verticalScale(5),
borderRadius: moderateScale(999),
},
pointChipPressed: {
opacity: 0.72,
transform: [{ scale: 0.96 }],
},
pointChipText: {
fontSize: moderateScale(13),
lineHeight: moderateScale(18),
fontWeight: "700",
color: "#35664E",
},
methodContainer: {
marginTop: verticalScale(4),
flexDirection: "row",
alignItems: "flex-start",
gap: moderateScale(6),
},
subSectionLabel: {
fontSize: moderateScale(13),
fontWeight: "700",
color: "#597064",
},
methodText: {
flex: 1,
fontSize: moderateScale(13),
lineHeight: moderateScale(19),
color: "#334155",
},
explanationList: {
gap: verticalScale(8),
},
explanationRow: {
flexDirection: "row",
alignItems: "flex-start",
gap: moderateScale(10),
},
explanationDot: {
width: moderateScale(5),
height: moderateScale(5),
marginTop: verticalScale(7),
borderRadius: moderateScale(2.5),
backgroundColor: "#829B8E",
},
explanationText: {
flex: 1,
fontSize: moderateScale(13),
lineHeight: moderateScale(19),
color: "#334155",
},
categoryRow: {
flexDirection: "row",
alignItems: "center",
gap: moderateScale(10),
paddingTop: verticalScale(2),
},
categoryLabel: {
fontSize: moderateScale(11),
lineHeight: moderateScale(15),
fontWeight: "700",
color: "#597064",
textTransform: "uppercase",
letterSpacing: 0.5,
},
categoryBadge: {
backgroundColor: "#EEF7F1",
borderWidth: 1,
borderColor: "#D5E8DB",
paddingHorizontal: moderateScale(11),
paddingVertical: verticalScale(4),
borderRadius: moderateScale(999),
},
categoryBadgeText: {
fontSize: moderateScale(12),
lineHeight: moderateScale(16),
fontWeight: "600",
color: "#35664E",
},
});
const styles = StyleSheet.create({
row: {
minHeight: moderateScale(68),
flexDirection: "row",
alignItems: "center",
padding: moderateScale(14),
},
pressed: {
opacity: 0.72,
},
iconWrapper: {
width: moderateScale(40),
height: moderateScale(40),
borderRadius: moderateScale(20),
justifyContent: "center",
alignItems: "center",
backgroundColor: "#E8F5E9",
},
textContainer: {
flex: 1,
marginLeft: moderateScale(12),
marginRight: moderateScale(10),
},
title: {
fontSize: moderateScale(15),
fontWeight: "600",
color: Colors.textPrimary,
},
subtitle: {
fontSize: moderateScale(12),
color: Colors.textSecondary,
marginTop: verticalScale(2),
lineHeight: moderateScale(16),
},
});