Files
2026-08-27 14:26:19 +07:00

2271 lines
87 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import React, { useState, useEffect, useCallback, useRef } from 'react';
import { Sparkles, RefreshCw, Download } from 'lucide-react';
import {
ComposedChart,
Area,
Bar,
Line,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
ResponsiveContainer,
Legend,
} from 'recharts';
import { useAppContext } from '../context/AppContext.tsx';
import type { DashboardInsightData, DashboardInsightJson } from '../services/aiInsightService.ts';
import { apiClient } from '../services/apiService.ts';
import { getDiagnostikBundle } from '../utils/insightEvidence.ts';
import { DATA_UPDATE_NOTICE, DATA_UPDATE_NOTICE_DETAIL } from '../utils/insightDataSchedule.ts';
import { latestResultRow, loadDashboardData } from './iotPanel/iotApi.ts';
import { computeDashboard } from './iotPanel/computeDashboard.ts';
import { preprocessFlockPayloadForPanel } from './iotPanel/preprocessFlockPayload.ts';
import {
analyzeTrend,
getCyclePhase,
getCobbStandardForDay,
calculateDeviation,
} from '../utils/insightHelpers.ts';
import { AiInsight } from '../types/dashboard.ts';
import type {
AggregatedCounts,
CkaleWeightPoint,
DailyWeightGainPoint,
DailyWeightPoint,
DeviceWeightData,
FcrDataPoint,
LiveCount,
MultiCoopWeightSummary,
PopulationDataPoint,
SensorWeightSummary,
WeightDataPoint,
WeightDistributionStats,
} from '../types.ts';
import type { FeedSackLogEntry } from '../types/counting.ts';
import { marked } from 'marked';
import { HeroFigure, MutedStatRow, StatTile } from './shared/InsightStatTiles.tsx';
import { exportCardToPdf } from '../utils/pdfExport.ts';
import { formatTruncatedRatio } from '../utils/formatters.ts';
import PdfReportHeader, {
buildPdfFilename,
describeDataDates,
describeKandangScope,
describeReportPeriod,
isoDataDates,
parseDayRangeLabel,
reportPeriodSlug,
} from './shared/PdfReportHeader.tsx';
/**
* Direct label on the final point of the actual-weight line.
*
* Recharts renders a line `label` for every point; labelling all of them is
* chaos and goes unread. Selective direct labelling means the endpoint only —
* the axis and the tooltip carry the rest.
*/
const WeightEndLabel = (props: {
x?: number;
y?: number;
index?: number;
value?: number | string;
rows?: Array<unknown>;
}) => {
const { x, y, index, value, rows } = props;
const total = rows?.length ?? 0;
if (
typeof x !== 'number' ||
typeof y !== 'number' ||
typeof index !== 'number' ||
total === 0 ||
index !== total - 1
) {
return null;
}
const numeric = Math.round(Number(value));
if (!Number.isFinite(numeric)) return null;
return (
<text x={x + 8} y={y + 4} fill="#6d28d9" fontSize={11} fontWeight={700}>
{numeric.toLocaleString('id-ID')} g
</text>
);
};
interface AiInsightCardProps {
kandangId: string | null;
page?: 'hitung_ayam' | 'berat_ayam' | 'fcr' | 'eef' | 'panel_iot' | 'data_quality' | 'dashboard';
}
// Keep in step with INSIGHT_VERSION in backend/services/dashboardInsightService.js:
// a stale browser cache would show pre-fix insights even after the server retires them.
const CACHE_VERSION = 'v6';
const QUOTA_ERROR_PREFIX = 'QUOTA_LIMIT_EXCEEDED';
type InsightStatus = 'ok' | 'warning' | 'critical' | 'unknown';
type StructuredInsightSection = {
status: InsightStatus;
bullets: string[];
evidence: string[];
actions: string[];
};
type StructuredInsight = DashboardInsightJson;
const stripJsonFences = (text: string) =>
text
.trim()
.replace(/^```json\s*/i, '')
.replace(/^```\s*/i, '')
.replace(/```$/i, '')
.trim();
const extractJsonObject = (text: string): string | null => {
const stripped = stripJsonFences(text);
if (!stripped) return null;
if (stripped.startsWith('{') && stripped.endsWith('}')) return stripped;
const first = stripped.indexOf('{');
const last = stripped.lastIndexOf('}');
if (first === -1 || last === -1 || last <= first) return null;
return stripped.slice(first, last + 1);
};
const asNonEmptyString = (value: unknown): string | null => {
if (typeof value !== 'string') return null;
const trimmed = value.trim();
return trimmed.length > 0 ? trimmed : null;
};
const asStringArray = (value: unknown, limit = 3): string[] => {
if (!Array.isArray(value)) return [];
return value
.map((item) => asNonEmptyString(item))
.filter((item): item is string => item !== null)
.slice(0, limit);
};
const asInsightStatus = (value: unknown): InsightStatus => {
if (value === 'ok' || value === 'warning' || value === 'critical' || value === 'unknown') {
return value;
}
return 'unknown';
};
const normalizeInsightSection = (value: unknown): StructuredInsightSection => {
const section = (value && typeof value === 'object' ? value : {}) as Record<string, unknown>;
return {
status: asInsightStatus(section.status),
bullets: asStringArray(section.bullets, 3),
evidence: asStringArray(section.evidence, 4),
actions: asStringArray(section.actions, 3),
};
};
const normalizeStructuredInsight = (rawText: string): StructuredInsight | null => {
try {
const jsonText = extractJsonObject(rawText);
if (!jsonText) return null;
const parsed = JSON.parse(jsonText) as Record<string, unknown>;
const summary = (
parsed.summary && typeof parsed.summary === 'object' ? parsed.summary : {}
) as Record<string, unknown>;
const detailed = (
parsed.detailed && typeof parsed.detailed === 'object' ? parsed.detailed : {}
) as Record<string, unknown>;
return {
summary: {
headline: asNonEmptyString(summary.headline) || 'Ringkasan belum tersedia',
bullets: asStringArray(summary.bullets, 3),
risks: asStringArray(summary.risks, 3),
actions: asStringArray(summary.actions, 3),
},
detailed: {
hitung_ayam: normalizeInsightSection(detailed.hitung_ayam),
berat_ayam: normalizeInsightSection(detailed.berat_ayam),
fcr: normalizeInsightSection(detailed.fcr),
eef: normalizeInsightSection(detailed.eef),
panel_iot: normalizeInsightSection(detailed.panel_iot),
data_quality: normalizeInsightSection(detailed.data_quality),
},
};
} catch (error) {
console.warn('⚠️ Failed to parse structured insight JSON:', error);
return null;
}
};
type CompactLiveCount = Pick<
LiveCount,
'cameraId' | 'cameraName' | 'locationName' | 'count' | 'status'
>;
type CompactAggregatedCounts = Array<{
locationId: string;
locationName: string;
totalCount: number;
coops: Array<{
coopId: string;
coopName: string;
totalCount: number;
floors: Array<{
floorId: string;
floorName: string;
count: number;
}>;
}>;
}>;
type CompactIotPanelSummary = {
raw: {
latestId: string | number | null;
flockId: string | null;
flockCount: number;
updatedAt: string | null;
day: number | null;
deviceName: string | null;
coopCode: string | null;
setpointCurrent: number | null;
fanTargetTemperature: Record<string, number>;
heaterTargetTemperature: Record<string, { targetOn?: number; targetOff?: number }>;
coolerTargetTemperature: number | null;
sensors: {
temperature1: number | null;
temperature2: number | null;
temperature3: number | null;
temperatureOutside: number | null;
humidity: number | null;
ammonia: number | null;
co2: number | null;
water: number | null;
wind: number | null;
lux: number | null;
};
alarms: {
humidityAlarmNilai: number | null;
batasAtasNilai: number | null;
batasAtasSensorInUse: string | null;
batasBawah1Nilai: number | null;
batasBawah1SensorInUse: string | null;
batasBawah2Nilai: number | null;
batasBawah2SensorInUse: string | null;
};
};
display: {
datetime: string;
avgTemp: string;
setPoint: string;
temp1: string;
temp2: string;
temp3: string;
humidity: string;
outsideTemp: string;
dayAge: string;
ammonia: string;
co2: string;
water: string;
wind: string;
lux: string;
inverterLabel: string;
coopName: string;
fanDevices: Array<{ key: string; label: string; status: string; setpoint: string }>;
hvacDevices: Array<{ key: string; label: string; status: string; setpoint: string }>;
humidityAlarmHighlight: boolean;
avgTempAlarmHighlight: boolean;
temp1AlarmHighlight: boolean;
temp2AlarmHighlight: boolean;
temp3AlarmHighlight: boolean;
};
computed: ReturnType<typeof computeDashboard>;
};
const toNumber = (value: unknown): number | null => {
const n = Number(value);
return Number.isFinite(n) ? n : null;
};
const pickRecent = <T,>(items: T[], limit = 14): T[] =>
items.slice(Math.max(items.length - limit, 0));
const compactLiveCount = (count: LiveCount): CompactLiveCount => ({
cameraId: count.cameraId,
cameraName: count.cameraName,
locationName: count.locationName,
count: count.count,
status: count.status,
});
const compactAggregatedCounts = (counts: AggregatedCounts): CompactAggregatedCounts =>
counts.map((location) => ({
locationId: location.locationId,
locationName: location.locationName,
totalCount: location.totalCount,
coops: location.coops.map((coop) => ({
coopId: coop.coopId,
coopName: coop.coopName,
totalCount: coop.totalCount,
floors: coop.floors.map((floor) => ({
floorId: floor.floorId,
floorName: floor.floorName,
count: floor.count,
})),
})),
}));
const compactPopulationHistory = (history: PopulationDataPoint[]) =>
pickRecent(history, 14).map((point) => ({
date: point.date,
population: point.population,
}));
const compactWeightHistory = (history: WeightDataPoint[]) =>
history.map((point) => ({
day: point.day,
actual: point.actual,
target: point.target,
}));
const compactDailyWeightData = (data: DailyWeightPoint[]) =>
data.map((point) => ({
day: point.day,
date: point.date,
actual: point.actual,
target: point.target,
min: point.min,
max: point.max,
chickenCount: point.chickenCount,
}));
const compactDailyWeightGainData = (data: DailyWeightGainPoint[]) =>
data.map((point) => ({
day: point.day,
date: point.date,
gain: point.gain,
targetGain: point.targetGain,
status: point.status,
}));
const compactDeviceWeightData = (data: DeviceWeightData[]) =>
data.map((point) => ({
deviceId: point.deviceId,
deviceName: point.deviceName,
avgWeight: point.avgWeight,
chickenCount: point.chickenCount,
isOnline: point.isOnline,
lastOnline: point.lastOnline,
}));
const compactSensorWeightSummary = (data: SensorWeightSummary[]) =>
data.map((point) => ({
device_id: point.device_id,
device_name: point.device_name,
total_weight_prediction: point.total_weight_prediction,
total_weight_actual: point.total_weight_actual,
avg_weight_prediction: point.avg_weight_prediction,
avg_weight_actual: point.avg_weight_actual,
chicken_count: point.chicken_count,
}));
const compactMultiCoopSummary = (data: MultiCoopWeightSummary[]) =>
data.map((point) => ({
coopId: point.coopId,
coopName: point.coopName,
currentWeight: point.currentWeight,
adg: point.adg,
uniformity: point.uniformity,
deviation: point.deviation,
}));
const compactFcrComparisonData = (data: FcrDataPoint[]) =>
data.map((point) => ({
day: point.day,
manualFcr: point.manualFcr,
iotFcr: point.iotFcr,
cobbFcr: point.cobbFcr,
}));
/**
* Feed-sack figures for the prompt.
*
* The dashboard has always shown "Karung Dituang" on the insight card, but the
* number was never put into the context pack — so `hitung_karung` had no data to
* read and every report came back "data tidak tersedia" for a topic the user can
* see on screen. The daily series comes from the KPI trend, which is already
* day-aligned, so period slicing applies to it like any other history.
*/
const compactFeedSack = (input: {
karungDituangToday: number | null;
trend: number[];
trendDates: string[];
history: FeedSackLogEntry[];
currentDay: number;
}) => {
const { karungDituangToday, trend, trendDates, history, currentDay } = input;
// Align the trend to day numbers so the period pruning can slice it: the last
// point is the current day, walking backwards one day per entry.
const firstDay = currentDay - trend.length + 1;
const riwayatHarian = trend.map((count, index) => ({
day: firstDay + index,
date: trendDates[index] ?? null,
karungDituang: count,
}));
const totalByType = (type: FeedSackLogEntry['type']) =>
history.filter((entry) => entry.type === type).reduce((sum, entry) => sum + entry.count, 0);
const perKamera = Object.values(
history.reduce<Record<string, { cameraName: string; count: number }>>((acc, entry) => {
const key = entry.cameraName || 'tidak diketahui';
acc[key] = acc[key] || { cameraName: key, count: 0 };
acc[key].count += entry.count;
return acc;
}, {})
).sort((a, b) => b.count - a.count);
return {
karungDituangHariIni_karung: karungDituangToday,
totalKarungMasuk_karung: totalByType('inbound'),
totalKarungDituang_karung: totalByType('usage'),
totalKarungKeluar_karung: totalByType('outbound'),
saldoKarung_karung: totalByType('inbound') - totalByType('usage') - totalByType('outbound'),
jumlahCatatanKamera: history.length,
riwayatHarian,
perKamera,
note: 'Karung masuk = stok diterima; karung dituang = pakan yang benar-benar dikonsumsi ayam. Satuan semua angka: karung.',
};
};
const compactCkaleData = (data: CkaleWeightPoint[]) =>
data.map((point) => ({
day: point.day,
manual: point.manual,
all: point.all,
front: point.front,
back: point.back,
}));
const summarizeIotPanel = async (): Promise<CompactIotPanelSummary | null> => {
try {
const { raw, data } = await loadDashboardData();
const sanitized = preprocessFlockPayloadForPanel(data);
const computed = computeDashboard(sanitized);
const latestRow = latestResultRow(raw);
return {
raw: {
latestId: latestRow?.id ?? null,
flockId: latestRow?.flock_id || latestRow?.flock || null,
flockCount: Number(raw.count ?? raw.results?.length ?? 0),
updatedAt: sanitized.updatedAt ?? null,
day: sanitized.day ?? null,
deviceName: sanitized.name ?? null,
coopCode: sanitized.coop?.kode ?? null,
setpointCurrent: toNumber(sanitized.setpointCurrent),
fanTargetTemperature: sanitized.fanTargetTemperature || {},
heaterTargetTemperature: sanitized.heaterTargetTemperature || {},
coolerTargetTemperature: toNumber(sanitized.coolerTargetTemperature),
sensors: {
temperature1: toNumber(sanitized.sensors?.temperature1?.value),
temperature2: toNumber(sanitized.sensors?.temperature2?.value),
temperature3: toNumber(sanitized.sensors?.temperature3?.value),
temperatureOutside: toNumber(sanitized.sensors?.temperatureOutside?.value),
humidity: toNumber(sanitized.sensors?.humidity?.value),
ammonia: toNumber(sanitized.sensors?.ammonia?.value),
co2: toNumber(sanitized.sensors?.co2?.value),
water: toNumber(sanitized.sensors?.water?.value),
wind: toNumber(sanitized.sensors?.wind?.value),
lux: toNumber(sanitized.sensors?.lux?.value),
},
alarms: {
humidityAlarmNilai: toNumber(sanitized.humidityAlarmNilai),
batasAtasNilai: toNumber(sanitized.batasAtasNilai),
batasAtasSensorInUse: sanitized.batasAtasSensorInUse ?? null,
batasBawah1Nilai: toNumber(sanitized.batasBawah1Nilai),
batasBawah1SensorInUse: sanitized.batasBawah1SensorInUse ?? null,
batasBawah2Nilai: toNumber(sanitized.batasBawah2Nilai),
batasBawah2SensorInUse: sanitized.batasBawah2SensorInUse ?? null,
},
},
display: {
datetime: computed.datetime,
avgTemp: computed.avgTemp,
setPoint: computed.setPoint,
temp1: computed.temp1,
temp2: computed.temp2,
temp3: computed.temp3,
humidity: computed.humidity,
outsideTemp: computed.outsideTemp,
dayAge: computed.dayAge,
ammonia: computed.ammonia,
co2: computed.co2,
water: computed.water,
wind: computed.wind,
lux: computed.lux,
inverterLabel: computed.inverterLabel,
coopName: computed.coopName,
fanDevices: computed.fanDevices,
hvacDevices: computed.hvacDevices,
humidityAlarmHighlight: computed.humidityAlarmHighlight,
avgTempAlarmHighlight: computed.avgTempAlarmHighlight,
temp1AlarmHighlight: computed.temp1AlarmHighlight,
temp2AlarmHighlight: computed.temp2AlarmHighlight,
temp3AlarmHighlight: computed.temp3AlarmHighlight,
},
computed,
};
} catch (error) {
console.warn('⚠️ Failed to load live IoT panel snapshot for AI insight:', error);
return null;
}
};
const buildContextPack = (input: {
kandangId: string | null;
kandangName: string;
currentDay: number;
totalDays: number;
phase: string;
initialPopulation: number;
docInCount: number | null;
liveCounts: LiveCount[];
aggregatedCounts: AggregatedCounts;
populationHistory: PopulationDataPoint[];
mortality: {
mortalityCount: number;
status: string;
trend: string;
mati: number;
afkir: number;
panen: number;
};
/**
* Mortality per cycle day, carrying the running cumulative.
*
* Only cycle totals used to reach the backend, so a weekly report had nothing
* to scope and quoted the day-48 figure under a week-1 heading.
* `kumulatifMatiAfkir` is cumulative THROUGH that day because the CP 707
* mortality standard is itself cumulative — the last row of a sliced window is
* then directly comparable to the standard for that window's last day.
*/
mortalityHistory: Array<{
day: number;
mati: number;
afkir: number;
panen: number;
kumulatifMatiAfkir: number;
}>;
weight: {
stats: {
averageWeight: number;
targetWeight: number;
deviation: number;
status: string;
dailyGain: number;
dailyGainStatus: string;
uniformity: number;
uniformityStatus: string;
fcr: number;
fcrCobbStandard: number;
fcrStatus: string;
fcrTrend: string;
};
weightHistory: WeightDataPoint[];
dailyWeightData: DailyWeightPoint[];
dailyWeightGainData: DailyWeightGainPoint[];
deviceWeightData: DeviceWeightData[];
distributionStats: WeightDistributionStats | null;
sensorWeightSummary: SensorWeightSummary[];
multiCoopSummaryData: MultiCoopWeightSummary[];
fcrComparisonData: FcrDataPoint[];
ckaleData: CkaleWeightPoint[];
};
iotPanel: CompactIotPanelSummary | null;
feedSack: {
karungDituangToday: number | null;
trend: number[];
trendDates: string[];
history: FeedSackLogEntry[];
};
}) => {
const onlineCounts = input.liveCounts.filter((count) => count.status !== 'offline');
const totalCameras = input.liveCounts.length;
const onlineCameraCount = input.liveCounts.filter((count) => count.status === 'online').length;
const offlineCameraCount = input.liveCounts.filter((count) => count.status === 'offline').length;
const processingCameraCount = input.liveCounts.filter(
(count) => count.status === 'processing'
).length;
const estimatedPopulation = onlineCounts.reduce((sum, count) => sum + count.count, 0);
const topCameras = [...onlineCounts]
.sort((a, b) => b.count - a.count)
.slice(0, 8)
.map(compactLiveCount);
const offlineCameras = input.liveCounts
.filter((count) => count.status === 'offline')
.map(compactLiveCount);
const latestPopulationHistory = compactPopulationHistory(input.populationHistory);
const latestPopulationPoint = input.populationHistory[input.populationHistory.length - 1] ?? null;
const previousPopulationPoint =
input.populationHistory[input.populationHistory.length - 2] ?? null;
// Send the COMPUTED readings only. `raw.sensors` holds the sensor's own
// encoding — temperature and humidity arrive multiplied by ten, so 31.6 °C is
// stored as 316 and 62.8 % as 628. Handing those to the model produced
// "suhu 316°C". `display` is what `computeDashboard` already scaled and
// labelled ("31.6 °C", "62.8 %", "0.4 ppm"), so it is the only safe source.
const promptSafeIotPanel = input.iotPanel
? {
kandang: input.iotPanel.raw?.coopCode ?? input.iotPanel.display?.coopName ?? null,
perangkat: input.iotPanel.raw?.deviceName ?? null,
hariKe: input.iotPanel.raw?.day ?? null,
waktuData: input.iotPanel.display?.datetime ?? null,
pembacaan: {
suhuRataRata: input.iotPanel.display?.avgTemp ?? null,
setPoint: input.iotPanel.display?.setPoint ?? null,
// Was read from a non-existent `expectedTemp`, so it always sent
// null; the set point is the panel's target temperature.
suhuTarget: input.iotPanel.display?.setPoint ?? null,
suhu1: input.iotPanel.display?.temp1 ?? null,
suhu2: input.iotPanel.display?.temp2 ?? null,
suhu3: input.iotPanel.display?.temp3 ?? null,
suhuLuar: input.iotPanel.display?.outsideTemp ?? null,
kelembapan: input.iotPanel.display?.humidity ?? null,
amonia: input.iotPanel.display?.ammonia ?? null,
co2: input.iotPanel.display?.co2 ?? null,
kecepatanAngin: input.iotPanel.display?.wind ?? null,
lux: input.iotPanel.display?.lux ?? null,
},
alarmAktif: {
suhuRataRata: input.iotPanel.display?.avgTempAlarmHighlight ?? false,
kelembapan: input.iotPanel.display?.humidityAlarmHighlight ?? false,
suhu1: input.iotPanel.display?.temp1AlarmHighlight ?? false,
suhu2: input.iotPanel.display?.temp2AlarmHighlight ?? false,
suhu3: input.iotPanel.display?.temp3AlarmHighlight ?? false,
},
note: 'Setiap nilai di "pembacaan" sudah lengkap dengan satuannya. Kutip apa adanya, jangan mengubah satuan atau menghitung ulang.',
}
: null;
return {
metadata: {
kandangId: input.kandangId,
kandangName: input.kandangName,
currentDay: input.currentDay,
totalDays: input.totalDays,
phase: input.phase,
initialPopulation: input.initialPopulation,
docInCount: input.docInCount,
},
chickenCounting: {
cameraSummary: {
totalCameras,
onlineCameraCount,
offlineCameraCount,
processingCameraCount,
estimatedPopulation,
estimatedPopulationVsDocIn:
input.docInCount !== null ? estimatedPopulation - input.docInCount : null,
latestPopulationHistoryChange:
latestPopulationPoint && previousPopulationPoint
? latestPopulationPoint.population - previousPopulationPoint.population
: null,
},
liveCounts: input.liveCounts.map(compactLiveCount),
topCameras,
offlineCameras,
aggregatedCounts: compactAggregatedCounts(input.aggregatedCounts),
populationHistory: latestPopulationHistory,
mortality: input.mortality,
mortalityHistory: input.mortalityHistory,
},
weight: {
current: input.weight.stats,
weightHistory: compactWeightHistory(input.weight.weightHistory),
dailyWeightData: compactDailyWeightData(input.weight.dailyWeightData),
dailyWeightGainData: compactDailyWeightGainData(input.weight.dailyWeightGainData),
deviceWeightData: compactDeviceWeightData(input.weight.deviceWeightData),
distributionStats: input.weight.distributionStats,
sensorWeightSummary: compactSensorWeightSummary(input.weight.sensorWeightSummary),
multiCoopSummaryData: compactMultiCoopSummary(input.weight.multiCoopSummaryData),
fcrComparisonData: compactFcrComparisonData(input.weight.fcrComparisonData),
ckaleData: compactCkaleData(input.weight.ckaleData),
},
fcr_eef: {
fcr: {
actual: input.weight.stats.fcr,
cobbStandard: input.weight.stats.fcrCobbStandard,
status: input.weight.stats.fcrStatus,
trend: input.weight.stats.fcrTrend,
comparison: compactFcrComparisonData(input.weight.fcrComparisonData),
note: 'FCR (Feed Conversion Ratio): rasio pakan yang dibutuhkan untuk menghasilkan 1 kg bobot ayam. Nilai lebih rendah = lebih efisien.',
},
eef: {
note: 'EEF/IP (European Efficiency Factor): indeks performa keseluruhan siklus. Rumus: (% hidup × bobot panen rata-rata gram) / (FCR × umur panen × 100). EEF >300 = sangat baik, 250-300 = baik, <250 = perlu perhatian.',
currentDay: input.currentDay,
totalDays: input.totalDays,
mortalityRate: input.mortality.mortalityCount,
avgWeight: input.weight.stats.averageWeight,
fcr: input.weight.stats.fcr,
},
},
iotPanel: promptSafeIotPanel,
hitung_karung: compactFeedSack({
karungDituangToday: input.feedSack.karungDituangToday,
trend: input.feedSack.trend,
trendDates: input.feedSack.trendDates,
history: input.feedSack.history,
currentDay: input.currentDay,
}),
instructionHints: {
focusOrder: ['hitung_ayam', 'berat_ayam', 'hitung_karung', 'fcr', 'eef', 'panel_iot'],
emphasize: [
'Gunakan data hitung ayam sebagai indikator integritas populasi.',
'Gunakan data berat ayam untuk menjelaskan performa pertumbuhan.',
'Gunakan data hitung karung untuk menilai konsumsi pakan — bandingkan karung dituang dengan pertumbuhan bobot.',
'Gunakan data FCR untuk menilai efisiensi konversi pakan — FCR lebih rendah lebih baik.',
'Gunakan data EEF/IP sebagai indeks performa keseluruhan siklus — EEF >300 sangat baik.',
'Gunakan panel IoT untuk menjelaskan stres lingkungan dan dampaknya ke ayam.',
],
},
};
};
/** One day's mortality/harvest row as returned by `/api/mortality/:cycleId`. */
type MortalityDayRow = {
day?: number | null;
mortalityCount?: number | null;
afkir?: number | null;
panen?: number | null;
beratPanen?: number | null;
};
const sumField = (rows: MortalityDayRow[], field: keyof MortalityDayRow) =>
rows.reduce((total, row) => {
const value = row[field];
return total + (typeof value === 'number' && Number.isFinite(value) ? value : 0);
}, 0);
/** Week number requested by a 'weekly' report, e.g. "Minggu 7" -> 7. */
const parseWeekNumber = (period: string | null) => {
const match = period && String(period).match(/\d+/);
const week = match ? parseInt(match[0], 10) : 1;
return Number.isFinite(week) && week > 0 ? week : 1;
};
/**
* Day number requested by a 'daily' report, e.g. "Hari 12" -> 12.
* Null means no day was picked, which keeps the old behaviour of reporting on
* the latest day present in the data.
*/
const parseDayNumber = (period: string | null) => {
const match = period && String(period).match(/\d+/);
if (!match) return null;
const day = parseInt(match[0] ?? '', 10);
return Number.isFinite(day) && day > 0 ? day : null;
};
/**
* Narrow per-day rows to the timeframe the user picked in the report dropdown.
*
* The KPI grid used to show `kpis.mortality.value` — the *selected day's*
* deaths — under the label "Jumlah Kematian (Kematian + Afkir)", which reads as
* a cycle total. On day 48 that printed 0 next to an AI narrative reporting
* 2,477 cumulative deaths in the same card. Tying the figure to the timeframe
* makes the label true in every mode instead of only in one.
*
* `lastDay` is the closing day of the window: stock figures (the running
* balance) are counted up to it, while flow figures (deaths, harvest) are
* counted only inside the window.
*/
const sliceMortalityByPeriod = (
rows: MortalityDayRow[],
reportType: 'daily' | 'weekly' | 'end_cycle',
reportPeriod: string | null
) => {
const dayOf = (row: MortalityDayRow) =>
typeof row.day === 'number' && Number.isFinite(row.day) ? row.day : null;
const days = rows.map(dayOf).filter((day): day is number => day !== null);
const latestDay = days.length > 0 ? Math.max(...days) : null;
if (reportType === 'daily') {
// Picking a day means "the cycle so far, up to that day" — day 0 through
// day N — so the flows below are running totals, matching the cumulative
// mortality rate the card leads with.
const requestedDay = parseDayNumber(reportPeriod);
if (requestedDay !== null) {
const window = rows.filter((row) => (dayOf(row) ?? Infinity) <= requestedDay);
const windowDays = window.map(dayOf).filter((day): day is number => day !== null);
return {
window,
lastDay: requestedDay,
label:
windowDays.length === 0
? `hari ke-${requestedDay}`
: `hari ke-${Math.min(...windowDays)} s/d ke-${requestedDay}`,
};
}
return {
window: latestDay === null ? [] : rows.filter((row) => dayOf(row) === latestDay),
lastDay: latestDay,
label: latestDay === null ? 'hari terakhir' : `hari ke-${latestDay}`,
};
}
if (reportType === 'weekly') {
const week = parseWeekNumber(reportPeriod);
const firstDay = (week - 1) * 7 + 1;
const lastDay = week * 7;
return {
// An empty window must read as "no data for this week", never as some
// other week's numbers.
window: rows.filter((row) => {
const day = dayOf(row);
return day !== null && day >= firstDay && day <= lastDay;
}),
lastDay,
label: `${reportPeriod || 'Minggu ini'} (hari ${firstDay}–${lastDay})`,
};
}
return { window: rows, lastDay: latestDay, label: 'seluruh siklus' };
};
export const AiInsightCard: React.FC<AiInsightCardProps> = ({ kandangId, page = 'dashboard' }) => {
const context = useAppContext();
const [insightText, setInsightText] = useState<string>('');
const [structuredInsight, setStructuredInsight] = useState<StructuredInsight | null>(null);
const [loading, setLoading] = useState<boolean>(false);
const [lastUpdated, setLastUpdated] = useState<Date | null>(null);
const [error, setError] = useState<string | null>(null);
const [detailsOpen, setDetailsOpen] = useState(false);
const [reportType, setReportType] = useState<'daily' | 'weekly' | 'end_cycle'>('daily');
// `dayPeriod` starts null, meaning "the newest day we have".
const [dayPeriod, setDayPeriod] = useState<string | null>(null);
// Per-day mortality/harvest rows for the KPI grid. Loaded independently of
// insight generation so the figures are right even when the insight itself
// comes from cache.
const [mortalityRows, setMortalityRows] = useState<MortalityDayRow[]>([]);
const insightInFlightRef = useRef(false);
const pdfRef = useRef<HTMLDivElement>(null);
const cycleId = context.cycleData?.id;
/** Day the cycle has reached — the newest day any report can cover. */
const currentDayVal = context.kpis?.umur?.value || context.cycleData?.currentDay || 0;
/**
* The label sent to the backend and printed on the PDF. Daily falls back to
* the current day so the card behaves exactly as before until the user picks
* a different one.
*/
const reportPeriod =
reportType === 'daily'
? (dayPeriod ?? (currentDayVal > 0 ? `Hari ${currentDayVal}` : null))
: null;
// Calendar span the report actually covers, per scope: the chosen day for a
// daily report, the requested week for a weekly one, day 1 to now for
// end-cycle. Both the printed header and the filename read from here so they
// cannot disagree.
const { dashboardDataDateLabel, dashboardIsoDates } = (() => {
const startDate = context.cycleData?.startDate;
const currentDay = context.cycleData?.currentDay;
let fromDay: number | null | undefined = currentDay;
let toDay: number | null = null;
if (reportType === 'end_cycle') {
fromDay = 0;
toDay = currentDay ?? null;
} else if (reportType === 'weekly') {
// `reportPeriod` is "Minggu 6" — a week number, not a day number.
// Hitung Ayam days are 0-based: week 1 = hari 0–6.
const { fromDay: weekNo } = parseDayRangeLabel(reportPeriod);
if (weekNo) {
fromDay = (weekNo - 1) * 7;
toDay = weekNo * 7 - 1;
}
} else if (reportType === 'daily') {
// Here the number IS a day, so it is used as-is rather than scaled by 7.
fromDay = parseDayNumber(reportPeriod) ?? currentDay;
toDay = null;
}
return {
dashboardDataDateLabel: describeDataDates(startDate, fromDay, toDay),
dashboardIsoDates: isoDataDates(startDate, fromDay, toDay),
};
})();
useEffect(() => {
let cancelled = false;
if (!cycleId) {
setMortalityRows([]);
return;
}
apiClient
.getMortalityRecords(cycleId, kandangId ? Number(kandangId) : undefined)
.then((records: unknown) => {
if (cancelled) return;
setMortalityRows(Array.isArray(records) ? (records as MortalityDayRow[]) : []);
})
.catch((err: unknown) => {
console.error('❌ Failed to load mortality records for KPI grid:', err);
if (!cancelled) setMortalityRows([]);
});
return () => {
cancelled = true;
};
}, [cycleId, kandangId]);
const applyInsightText = useCallback((text: string) => {
setInsightText(text);
setStructuredInsight(normalizeStructuredInsight(text));
}, []);
const downloadPdf = async () => {
if (!structuredInsight || !pdfRef.current) return;
try {
// Same identity as the printed header, so the file can be matched to its
// report without opening it.
const filename = buildPdfFilename({
reportName: 'Dashboard',
area: context.selectedArea || 'Sukawarna',
kandangLabel: describeKandangScope(context.kandangs, kandangId),
periodSlug: reportPeriodSlug(reportType, reportPeriod),
isoDates: dashboardIsoDates,
});
await exportCardToPdf(pdfRef.current, filename);
} catch (error) {
console.error('Failed to generate PDF:', error);
}
};
// Generate cache key
const getCacheKey = useCallback(() => {
return `ai-insight-${kandangId || 'all'}-${context.cycleData?.id || 'no-cycle'}`;
}, [kandangId, context.cycleData?.id]);
// Load from local cache as a fallback only
// Save to local cache only; backend already persists the database copy.
const saveToCache = useCallback(
async (text: string) => {
try {
const cacheKey = getCacheKey();
const insight: AiInsight = {
text,
generatedAt: new Date(),
kandangId,
version: CACHE_VERSION,
};
localStorage.setItem(cacheKey, JSON.stringify(insight));
} catch (err) {
console.error('❌ Error saving insight to cache:', err);
}
},
[getCacheKey, kandangId]
);
// Prepare data for insight generation
const prepareInsightData = useCallback(async (): Promise<DashboardInsightData | null> => {
try {
const {
kpis,
cycleData,
weightStats,
liveCounts,
aggregatedCounts,
populationHistory,
weightHistory,
dailyWeightData,
dailyWeightGainData,
deviceWeightData,
distributionStats,
multiCoopSummaryData,
fcrComparisonData,
ckaleData,
feedSackHistory,
} = context;
// `cageUuid` is what the scales/sensor APIs are keyed by; the evidence
// bundle needs it to fetch the right coop's history.
const kandangs = ((context as any).kandangs || []) as Array<{
id: number;
name?: string;
cageUuid?: string | null;
}>;
const sensorWeightSummary = ((context as any).sensorWeightSummary ||
[]) as SensorWeightSummary[];
if (!cycleData) {
console.warn('❌ Missing cycle data');
throw new Error('Data siklus tidak tersedia. Pastikan ada siklus aktif.');
}
if (!kpis || Object.keys(kpis).length === 0) {
console.warn('❌ Missing KPIs - object is empty');
console.warn('⏳ Please wait for dashboard data to load completely');
throw new Error('Data KPI tidak tersedia. Tunggu hingga data selesai dimuat.');
}
// Get kandang name
let kandangName = 'Semua Kandang';
if (kandangId && kandangs && kandangs.length > 0) {
const kandang = kandangs.find(
(k: { id: number; name?: string }) => k.id === parseInt(kandangId)
);
kandangName = kandang?.name || `Kandang ${kandangId}`;
} else if (kandangId) {
// If kandangId is provided but kandangs array is empty
kandangName = `Kandang ${kandangId}`;
}
const currentDay = kpis.umur?.value || 0;
const totalDays = cycleData.totalDays || 42;
const phase = getCyclePhase(currentDay);
const cobbStandard = getCobbStandardForDay(currentDay);
const cobbFcr = cobbStandard?.fcr || 1.6;
const cobbWeight = cobbStandard?.weight || 0;
const mortalityRate = kpis.mortality?.value || 0;
const mortalityStatus = kpis.mortality?.status || 'ok';
const mortalityTrend = analyzeTrend(kpis.mortality?.trend || []);
let matiTotal = 0;
let afkirTotal = 0;
let panenTotal = 0;
const avgWeight = weightStats?.averageWeight?.value || kpis.weight?.value || 0;
const targetWeight = cobbWeight || avgWeight || 0;
const deviation =
avgWeight && targetWeight
? calculateDeviation(avgWeight, targetWeight)
: { absolute: 0, percent: 0 };
const weightStatus = kpis.weight?.status || 'ok';
const dailyGain = weightStats?.avgDailyGain?.value || 0;
const dailyGainStatus = weightStats?.avgDailyGain?.status || 'ok';
const uniformity = weightStats?.uniformity?.value || 0;
const uniformityStatus = weightStats?.uniformity?.status || 'ok';
const initialPopulation = cycleData.docInCount || 20000;
const selectedKandangId = kandangId ? parseInt(kandangId) : null;
const mortalityPromise = apiClient.getMortalityRecords(
cycleData.id,
selectedKandangId ?? undefined
);
const iotPanelPromise = summarizeIotPanel();
const [mortalityRecords, iotPanel] = await Promise.allSettled([
mortalityPromise,
iotPanelPromise,
]);
const mortalityHistory: Array<{
day: number;
mati: number;
afkir: number;
panen: number;
kumulatifMatiAfkir: number;
}> = [];
if (mortalityRecords.status === 'fulfilled' && Array.isArray(mortalityRecords.value)) {
// One day can have several rows (one per coop), so fold them together
// before building the running cumulative.
const byDay = new Map<number, { mati: number; afkir: number; panen: number }>();
mortalityRecords.value.forEach(
(record: {
day?: number | null;
mortalityCount?: number;
afkir?: number;
panen?: number;
}) => {
matiTotal += record.mortalityCount || 0;
afkirTotal += record.afkir || 0;
panenTotal += record.panen || 0;
if (typeof record.day !== 'number' || !Number.isFinite(record.day)) return;
const bucket = byDay.get(record.day) ?? { mati: 0, afkir: 0, panen: 0 };
bucket.mati += record.mortalityCount || 0;
bucket.afkir += record.afkir || 0;
bucket.panen += record.panen || 0;
byDay.set(record.day, bucket);
}
);
// Counts only — the rate is left to the backend, which resolves the
// flock size from the enriched pack. Computing it here would have to use
// `initialPopulation`, and that falls back to a hardcoded 20000 whenever
// `docInCount` is null (it is, on this cycle), producing a rate that
// contradicts the one the rest of the card reports.
let running = 0;
for (const day of [...byDay.keys()].sort((a, b) => a - b)) {
const bucket = byDay.get(day)!;
running += bucket.mati + bucket.afkir;
mortalityHistory.push({
day,
mati: bucket.mati,
afkir: bucket.afkir,
panen: bucket.panen,
kumulatifMatiAfkir: running,
});
}
} else if (mortalityRecords.status === 'rejected') {
console.error('❌ Failed to fetch mortality breakdown:', mortalityRecords.reason);
}
const weightSection = {
stats: {
averageWeight: avgWeight,
targetWeight,
deviation: deviation.absolute,
status: weightStatus,
dailyGain,
dailyGainStatus,
uniformity,
uniformityStatus,
fcr: kpis.fcr?.value || 0,
fcrCobbStandard: cobbFcr,
fcrStatus: kpis.fcr?.status || 'ok',
fcrTrend: analyzeTrend(kpis.fcr?.trend || []),
},
weightHistory: weightHistory || [],
dailyWeightData: dailyWeightData || [],
dailyWeightGainData: dailyWeightGainData || [],
deviceWeightData: deviceWeightData || [],
distributionStats: distributionStats || null,
sensorWeightSummary: sensorWeightSummary || [],
multiCoopSummaryData: multiCoopSummaryData || [],
fcrComparisonData: fcrComparisonData || [],
ckaleData: ckaleData || [],
};
// Same cross-domain bundle the page cards send, so the dashboard's causal
// reasoning is computed by the same backend code and cannot contradict
// them. Failure is tolerated: the pack is still valid without it.
const selectedCageUuid =
selectedKandangId === null
? null
: ((kandangs ?? []).find((item) => item?.id === selectedKandangId)?.cageUuid ?? null);
const diagnostik = await getDiagnostikBundle({
cycleId: cycleData.id,
cageUuid: selectedCageUuid,
kandangId: selectedKandangId,
startDate: cycleData.startDate,
currentDay,
totalDays,
// Deliberately NOT `initialPopulation`: that falls back to a hardcoded
// 20000 when `docInCount` is null, and a fabricated denominator turns
// every mortality rate in the causal analysis into fiction.
populasiAwal: cycleData.docInCount ?? null,
keseragaman: uniformity || null,
apiMode: 'LIVE',
mortalityRows:
mortalityRecords.status === 'fulfilled' && Array.isArray(mortalityRecords.value)
? mortalityRecords.value
: null,
});
const contextPack = buildContextPack({
kandangId,
kandangName,
currentDay,
totalDays,
phase,
initialPopulation,
docInCount: cycleData.docInCount ?? null,
liveCounts: liveCounts || [],
aggregatedCounts: aggregatedCounts || [],
populationHistory: populationHistory || [],
mortality: {
mortalityCount: mortalityRate,
status: mortalityStatus,
trend: mortalityTrend,
mati: matiTotal,
afkir: afkirTotal,
panen: panenTotal,
},
mortalityHistory,
weight: weightSection,
iotPanel: iotPanel.status === 'fulfilled' ? iotPanel.value : null,
feedSack: {
karungDituangToday: kpis.karungDituang?.value ?? null,
trend: kpis.karungDituang?.trend ?? [],
trendDates: kpis.karungDituang?.trendDates ?? [],
history: feedSackHistory || [],
},
});
return {
currentDay,
totalDays,
phase,
kandangName,
initialPopulation,
// Attached beside the pack, not inside `buildContextPack`: the backend
// reads it, computes the evidence block, then strips it before the pack
// is pruned and serialised.
contextPack: diagnostik ? { ...contextPack, diagnostik } : contextPack,
};
} catch (err) {
console.error('Error preparing insight data:', err);
return null;
}
}, [context, kandangId]);
// Generate insight
const generateInsight = useCallback(
async (forceRefresh = false) => {
if (insightInFlightRef.current) {
return;
}
insightInFlightRef.current = true;
// Check cache first unless force refresh
try {
setLoading(true);
setError(null);
const insightData = await prepareInsightData();
if (!insightData) {
throw new Error('Tidak dapat mempersiapkan data untuk analisis');
}
const cycleId = context.cycleData?.id;
if (!cycleId) {
throw new Error('Data siklus tidak tersedia. Pastikan ada siklus aktif.');
}
// Query the backend server to generate/fetch the insight.
// The backend server will call the local LM Studio instance.
const result = await apiClient.getOrGenerateDashboardInsight(
context.cycleData?.id || '',
kandangId,
insightData.contextPack,
CACHE_VERSION,
forceRefresh,
reportType,
reportPeriod
);
if (!result || !result.success || !result.data?.insightText) {
throw new Error(result?.message || 'Gagal mengambil insight AI dari server');
}
const insightTextResponse = result.data.insightText;
applyInsightText(insightTextResponse);
setLastUpdated(new Date());
setDetailsOpen(false);
await saveToCache(insightTextResponse);
} catch (err) {
console.error('❌ Error generating insight:', err);
const errorMessageRaw = err instanceof Error ? err.message : 'unknown';
const isQuotaLimitError = errorMessageRaw.startsWith(QUOTA_ERROR_PREFIX);
const displayErrorMessage = isQuotaLimitError
? errorMessageRaw.replace(/^QUOTA_LIMIT_EXCEEDED:\s*/, '')
: errorMessageRaw;
applyInsightText('');
setLastUpdated(null);
setError(displayErrorMessage);
setDetailsOpen(false);
} finally {
setLoading(false);
insightInFlightRef.current = false;
}
},
[
applyInsightText,
context.cycleData,
kandangId,
prepareInsightData,
saveToCache,
reportType,
reportPeriod,
]
);
// Monitor when KPIs become available
const kpisReady = context.kpis && Object.keys(context.kpis).length > 0;
/**
* Shows a report that was generated earlier, WITHOUT generating one.
*
* Generation is manual now, but a report already produced for this scope must
* still appear when the user comes back to the page — otherwise every
* navigation would look like the card had never been run.
*/
const loadStoredInsight = useCallback(async () => {
const cycleIdForLookup = context.cycleData?.id;
if (!cycleIdForLookup) return;
try {
const stored = await apiClient.getAiInsight(
cycleIdForLookup,
kandangId,
reportType,
reportPeriod
);
// A row written by an older prompt version would show retired figures
// under the current card, so it counts as "nothing stored".
if (stored?.success && stored?.data?.insightText && stored.data.version === CACHE_VERSION) {
applyInsightText(stored.data.insightText);
setLastUpdated(stored.data.generatedAt ? new Date(stored.data.generatedAt) : new Date());
setError(null);
return;
}
} catch (err) {
console.error('❌ Error reading stored insight:', err);
}
// Nothing stored for this scope: clear whatever the previous scope showed,
// so a "Hari 12" report is never left on screen under a "Hari 13" heading.
applyInsightText('');
setLastUpdated(null);
setError(null);
}, [applyInsightText, context.cycleData?.id, kandangId, reportType, reportPeriod]);
// Scope changed (cycle, coop, report type/period): show what is stored for it.
// Deliberately does NOT generate — the user asked for generation to happen
// only on an explicit click, and a generate here costs minutes of LLM time
// for a card nobody may be looking at.
useEffect(() => {
void loadStoredInsight();
}, [loadStoredInsight]);
// Manual generate/refresh handler — the only path that calls the model.
const handleRefresh = () => {
generateInsight(true);
};
// Format timestamp
const formatLastUpdated = () => {
if (!lastUpdated) return '';
const now = new Date();
const diff = now.getTime() - lastUpdated.getTime();
const minutes = Math.floor(diff / 60000);
const hours = Math.floor(minutes / 60);
if (hours > 0) {
return `${hours} jam yang lalu`;
} else if (minutes > 0) {
return `${minutes} menit yang lalu`;
} else {
return 'Baru saja';
}
};
// Convert markdown to HTML
const getInsightHtml = async () => {
if (!insightText) return '';
try {
return await marked.parse(insightText);
} catch (err) {
console.error('Error parsing markdown:', err);
return insightText;
}
};
const [insightHtml, setInsightHtml] = useState('');
useEffect(() => {
const convertMarkdown = async () => {
if (insightText) {
const html = await getInsightHtml();
setInsightHtml(html);
}
};
convertMarkdown();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [insightText]);
const sectionBadgeClasses: Record<InsightStatus, string> = {
ok: 'border-emerald-200 bg-emerald-50 text-emerald-700',
warning: 'border-amber-200 bg-amber-50 text-amber-700',
critical: 'border-red-200 bg-red-50 text-red-700',
unknown: 'border-slate-200 bg-slate-50 text-slate-600',
};
const renderBulletList = (items: string[], emptyLabel = 'data belum tersedia') => {
if (!items.length) {
return <p className="text-sm text-gray-500">{emptyLabel}</p>;
}
return (
<ul className="space-y-2">
{items.map((item, index) => (
<li key={`${item}-${index}`} className="flex gap-2 text-sm text-gray-700">
<span className="mt-1.5 h-1.5 w-1.5 shrink-0 rounded-full bg-purple-500" />
<span>{item}</span>
</li>
))}
</ul>
);
};
const renderDetailSection = (
title: string,
section: StructuredInsightSection,
accentClass: string
) => (
<section className="rounded-2xl border border-gray-200 bg-white p-4 shadow-sm">
<div className="flex items-center justify-between gap-3">
<div>
<p className="text-xs font-semibold uppercase tracking-[0.16em] text-gray-500">{title}</p>
<p className="mt-1 text-sm text-gray-600">Ringkasan operasional yang sudah difilter.</p>
</div>
<span
className={`rounded-full border px-2.5 py-1 text-xs font-semibold uppercase tracking-wide ${accentClass}`}
>
{section.status}
</span>
</div>
<div className="mt-4 grid gap-4 md:grid-cols-3">
<div>
<p className="text-xs font-semibold uppercase tracking-wide text-gray-500">Poin</p>
<div className="mt-2">{renderBulletList(section.bullets)}</div>
</div>
<div>
<p className="text-xs font-semibold uppercase tracking-wide text-gray-500">Bukti</p>
<div className="mt-2">{renderBulletList(section.evidence)}</div>
</div>
<div>
<p className="text-xs font-semibold uppercase tracking-wide text-gray-500">Aksi</p>
<div className="mt-2">{renderBulletList(section.actions)}</div>
</div>
</div>
</section>
);
const renderSingleSectionInsight = (
pageType: Exclude<AiInsightCardProps['page'], undefined | 'dashboard'>
) => {
if (!structuredInsight) return null;
const section = structuredInsight.detailed[pageType];
if (!section)
return (
<div className="text-gray-500 text-sm italic">Insight untuk bagian ini tidak tersedia</div>
);
const titleMap: Record<string, string> = {
hitung_ayam: '🐔 Analisis Populasi & Hitung Ayam',
berat_ayam: '⚖️ Analisis Berat & Distribusi Ayam',
fcr: '🌾 Analisis Feed Conversion Ratio (FCR)',
eef: '📊 Analisis European Efficiency Factor (EEF)',
panel_iot: '🌡️ Analisis Suhu & Kondisi Kandang (IoT)',
data_quality: '📋 Analisis Kualitas & Konsistensi Data',
};
return (
<div className="space-y-4">
<div className="rounded-2xl border border-purple-100 bg-white/90 p-4 shadow-sm">
<div className="flex items-center justify-between gap-3 mb-3">
<h3 className="text-md font-bold text-purple-900">{titleMap[pageType]}</h3>
<span
className={`rounded-full border px-2.5 py-0.5 text-xs font-semibold uppercase tracking-wide ${sectionBadgeClasses[section.status]}`}
>
{section.status}
</span>
</div>
<div className="grid gap-4 md:grid-cols-3">
<div>
<p className="text-xs font-semibold uppercase tracking-wide text-gray-500">
Poin Analisis
</p>
<div className="mt-2">{renderBulletList(section.bullets)}</div>
</div>
<div>
<p className="text-xs font-semibold uppercase tracking-wide text-gray-500">
Bukti Data
</p>
<div className="mt-2">{renderBulletList(section.evidence)}</div>
</div>
<div>
<p className="text-xs font-semibold uppercase tracking-wide text-gray-500">
Rekomendasi Tindakan
</p>
<div className="mt-2">{renderBulletList(section.actions)}</div>
</div>
</div>
</div>
</div>
);
};
const renderStructuredInsight = () => {
if (!structuredInsight) return null;
const kpis = context.kpis;
const weightStats = context.weightStats;
// The per-coop DOC intake lives in `kandang_cycles`, which
// /api/kandangs/by-cycle already surfaces into `context.kandangs`.
// `cycles.doc_in_count` is NULL on the active cycle, so the old
// `|| 25000` fallback used ONE coop's intake as the whole-farm figure:
// with both coops in scope the balance became max(0, 25000 - 49.966) = 0,
// which is why "Saldo Akhir Ayam" read 0 no matter what.
// Scoped to the same coop selection as `mortalityRows`, or every coop when
// none is selected, so numerator and denominator always describe one flock.
const scopedKandangs = (
(context.kandangs || []) as Array<{ id?: number; docInCount?: number }>
).filter((k) => !kandangId || k.id?.toString() === kandangId.toString());
const docFromKandangs = scopedKandangs.reduce((sum, k) => sum + (Number(k.docInCount) || 0), 0);
// No invented fallback: an unknown intake has to read as unknown, or the
// balance silently becomes a confident wrong number again.
const docInCount = docFromKandangs || Number(context.cycleData?.docInCount) || 0;
// Deaths are a FLOW — count only what happened inside the window.
const {
window: periodRows,
lastDay,
label: periodLabel,
} = sliceMortalityByPeriod(mortalityRows, reportType, reportPeriod);
const hasMortalityData = mortalityRows.length > 0;
const kematianPeriode = sumField(periodRows, 'mortalityCount') + sumField(periodRows, 'afkir');
// Same window as the deaths beside them: both are flows, so both follow the
// selected period rather than the whole cycle.
const panenPeriode = sumField(periodRows, 'panen');
const tonasePeriode = sumField(periodRows, 'beratPanen');
// Saldo is a STOCK — the birds still in the coop at the close of the window,
// so it counts every departure up to `lastDay`, not just this window's.
// The old formula was `docInCount - <today's deaths>`, which ignored both
// earlier deaths and every bird harvested: it printed 25.000 for a coop that
// had already shipped its entire flock.
//
// NOTE: `panen` here is the locally recorded harvest column, which is also
// what "Jumlah terpanen" now displays. If Pak Sugi's API later turns out to
// be authoritative over this column, both the tile and this balance have to
// follow it together.
const rowsUpToLastDay =
lastDay === null
? mortalityRows
: mortalityRows.filter(
(row) => typeof row.day === 'number' && Number.isFinite(row.day) && row.day <= lastDay
);
const keluarKumulatif =
sumField(rowsUpToLastDay, 'mortalityCount') +
sumField(rowsUpToLastDay, 'afkir') +
sumField(rowsUpToLastDay, 'panen');
const fmt = (value: number) => value.toLocaleString('id-ID');
const mortality = hasMortalityData ? fmt(kematianPeriode) : '-';
const panen = hasMortalityData ? fmt(panenPeriode) : '-';
const tonase = hasMortalityData && tonasePeriode > 0 ? `${fmt(tonasePeriode)} kg` : '-';
const population =
hasMortalityData && docInCount > 0 ? fmt(Math.max(0, docInCount - keluarKumulatif)) : '-';
const rawFcr = kpis?.fcr?.value;
const rawEef = kpis?.eef?.value;
const eefVal = rawEef ? (typeof rawEef === 'number' ? rawEef.toFixed(2) : rawEef) : 'N/A';
// EEF naik jadi angka utama di samping FCR: keduanya adalah indeks performa
// siklus, dan supervisor membacanya berpasangan. Status dan trend-nya sudah
// dihitung di `kpis.eef`, jadi tidak ada angka baru yang diciptakan di sini.
const hasEef = eefVal !== 'N/A';
const eefStatus: InsightStatus = hasEef ? asInsightStatus(kpis?.eef?.status) : 'unknown';
// Ambang mengikuti `getEefStatus` di AppContext (>=350 ok, >=300 warning).
const eefDelta = !hasEef
? null
: eefStatus === 'ok'
? '✓ ≥350, sangat baik'
: eefStatus === 'warning'
? '300–350, di bawah target 350'
: '<300, perlu perhatian';
const eefSpark = Array.isArray(kpis?.eef?.trend)
? (kpis.eef.trend as unknown[]).filter(
(v): v is number => typeof v === 'number' && Number.isFinite(v)
)
: [];
// ── Headline figures ──────────────────────────────────────────────────
// Everything below is derived from values already computed above; nothing
// new is fetched and no figure is invented when its source is missing.
const cycleDay = context.cycleData?.currentDay ?? null;
const standard = cycleDay ? getCobbStandardForDay(cycleDay) : null;
const fcrNumber = typeof rawFcr === 'number' ? rawFcr : Number(rawFcr);
const hasFcr = Number.isFinite(fcrNumber) && fcrNumber > 0;
// Lower FCR is better, so the comparison is inverted against the standard.
const fcrStatus: InsightStatus =
!hasFcr || !standard?.fcr
? 'unknown'
: fcrNumber <= standard.fcr
? 'ok'
: fcrNumber <= standard.fcr * 1.1
? 'warning'
: 'critical';
const fcrDelta =
hasFcr && standard?.fcr
? // 3 desimal agar sebanding dengan nilai FCR di atasnya; dibulatkan ke 2
// desimal, selisih 0,004 tampil sebagai 0,00 alias "tidak ada selisih".
`${fcrNumber > standard.fcr ? '+' : ''}${formatTruncatedRatio(fcrNumber - standard.fcr, 3)} vs standar`
: null;
const weightRows = (context.weightHistory ?? []) as Array<{
day?: number;
actual?: number;
target?: number;
}>;
const weightSpark = weightRows
.map((row) => row.actual)
.filter((value): value is number => typeof value === 'number' && Number.isFinite(value));
// The scale has written 0 every day since it stopped reporting, so the last
// REAL reading is the last non-zero one — same rule the FCR page uses.
const lastWeight = [...weightSpark].reverse().find((value) => value > 0) ?? null;
const lastWeightRow = [...weightRows]
.reverse()
.find((row) => typeof row.actual === 'number' && row.actual > 0);
const weightTarget =
typeof lastWeightRow?.target === 'number' && lastWeightRow.target > 0
? lastWeightRow.target
: null;
const weightGapPct =
lastWeight !== null && weightTarget
? ((lastWeight - weightTarget) / weightTarget) * 100
: null;
const weightStatus: InsightStatus =
weightGapPct === null
? 'unknown'
: weightGapPct >= -5
? 'ok'
: weightGapPct >= -15
? 'warning'
: 'critical';
const mortalityPct =
hasMortalityData && docInCount > 0
? ((sumField(rowsUpToLastDay, 'mortalityCount') + sumField(rowsUpToLastDay, 'afkir')) /
docInCount) *
100
: null;
const mortalityStatus: InsightStatus =
mortalityPct === null
? 'unknown'
: mortalityPct < 5
? 'ok'
: mortalityPct <= 7
? 'warning'
: 'critical';
// Band geometry for the gap chart: a transparent base up to the lower of
// the two series, then the gap itself stacked on top. Recharts has no
// between-two-series area, so the band is built from two stacked areas.
const gapChartRows = weightRows
.filter((row) => typeof row.actual === 'number' && row.actual > 0)
.map((row) => {
const actual = row.actual as number;
const target = typeof row.target === 'number' && row.target > 0 ? row.target : null;
return {
day: row.day,
actual,
target,
bandBase: target === null ? 0 : Math.min(actual, target),
bandSize: target === null ? 0 : Math.abs(actual - target),
};
});
// Status hue, kept translucent so the lines stay readable through it.
const gapFill =
weightStatus === 'critical'
? 'rgba(208, 59, 59, 0.14)'
: weightStatus === 'warning'
? 'rgba(250, 178, 25, 0.18)'
: 'rgba(12, 163, 12, 0.12)';
// Where the flock went, per week. Deliberately NOT one stacked bar with all
// three: harvest reaches 13.933 in a week while deaths run 85-890, so a
// single stack would render mortality as an invisible sliver — the one
// figure an operator most needs to see. Two charts on a shared week axis
// instead, which is the standard answer to two measures of different scale.
const weeklyDeparture = (() => {
const byWeek = new Map<
number,
{ minggu: number; mati: number; afkir: number; panen: number }
>();
for (const row of mortalityRows) {
if (typeof row.day !== 'number' || !Number.isFinite(row.day) || row.day <= 0) continue;
const minggu = Math.ceil(row.day / 7);
const bucket = byWeek.get(minggu) ?? { minggu, mati: 0, afkir: 0, panen: 0 };
bucket.mati += row.mortalityCount || 0;
bucket.afkir += row.afkir || 0;
bucket.panen += row.panen || 0;
byWeek.set(minggu, bucket);
}
return [...byWeek.values()].sort((a, b) => a.minggu - b.minggu);
})();
const hasHarvest = weeklyDeparture.some((row) => row.panen > 0);
const karungVal =
kpis?.karungDituang?.value !== undefined
? kpis.karungDituang.value.toLocaleString('id-ID')
: 'N/A';
// Rounded for display: the figure arrives at full float precision from the
// API and would otherwise print as "51.391368269062724%".
// Hari tanpa penimbangan keluar 0%, bukan "N/A" -- 0 adalah pembacaan yang
// sah di sini, dan angka ini harus sama dengan yang dipegang user.
const uniformityVal =
typeof weightStats?.uniformity?.value === 'number' &&
Number.isFinite(weightStats.uniformity.value)
? `${weightStats.uniformity.value.toFixed(1)}%`
: '0.0%';
const { summary, detailed } = structuredInsight;
return (
<div className="space-y-4">
<div className="rounded-2xl border border-purple-100 bg-white/90 p-5 shadow-sm">
{/* Hero + tiles: the card leads with the metric it is really about,
and the remaining figures stay available but visibly secondary. */}
<div className="grid grid-cols-1 gap-3 md:grid-cols-2">
<HeroFigure
label="FCR Aktual"
// 3 desimal, sama seperti kartu KPI FCR. `toFixed(2)` membulatkan
// 1,704 menjadi "1.70" — digit terakhirnya hilang, padahal FCR
// dibaca sampai ribuan dan selisih 0,004 itu berarti.
value={hasFcr ? formatTruncatedRatio(fcrNumber, 3) : 'N/A'}
context={
standard?.fcr && cycleDay
? `Standar CP 707 hari ke-${cycleDay}: ${formatTruncatedRatio(standard.fcr, 3)}`
: null
}
status={fcrStatus}
deltaLabel={fcrDelta}
/>
<HeroFigure
label="EEF"
value={eefVal}
context={hasEef ? 'Target ≥350' : 'belum tersedia'}
status={eefStatus}
deltaLabel={eefDelta}
sparkline={eefSpark}
/>
</div>
<div className="mt-3 grid grid-cols-2 gap-3 lg:grid-cols-3">
<StatTile
label="Populasi Hidup"
value={population}
unit={population === '-' ? undefined : 'ekor'}
hint="s/d kini"
/>
<StatTile
label="Mortalitas Kumulatif"
value={mortalityPct === null ? '-' : `${mortalityPct.toFixed(2)}%`}
status={mortalityStatus}
deltaLabel={
mortalityPct === null
? null
: mortalityStatus === 'ok'
? '✓ normal <5%'
: mortalityStatus === 'warning'
? '↑ melebihi standar <5%'
: '↑ tinggi, standar <5%'
}
/>
<StatTile
label="Bobot Rata-rata"
value={lastWeight === null ? '-' : fmt(Math.round(lastWeight))}
unit={lastWeight === null ? undefined : 'g'}
status={weightStatus}
deltaLabel={weightGapPct === null ? null : `${weightGapPct.toFixed(0)}% vs target`}
sparkline={weightSpark}
/>
</div>
<div className="mt-4 grid grid-cols-1 gap-x-6 md:grid-cols-2">
<MutedStatRow
label="Jumlah Populasi (Jumlah DOC)"
value={docInCount > 0 ? docInCount.toLocaleString('id-ID') : '-'}
/>
<MutedStatRow
label="Jumlah Kematian (Kematian + Afkir)"
hint={`— ${periodLabel}`}
value={mortality}
/>
<MutedStatRow label="Jumlah terpanen" hint={`— ${periodLabel}`} value={panen} />
<MutedStatRow label="Jumlah tonase panen" hint={`— ${periodLabel}`} value={tonase} />
<MutedStatRow label="Uniformity (AI Scale)" value={uniformityVal} />
<MutedStatRow label="Konsumsi pakan (Sack Counting)" value={karungVal} />
</div>
{weightRows.length > 0 && (
<div
className="mt-6 pt-4 border-t border-purple-100"
data-html2canvas-ignore="false"
data-pdf-block
>
<div className="mb-3 flex items-baseline justify-between gap-3">
<h4 className="text-sm font-bold text-purple-700">Bobot Aktual vs Target CP 707</h4>
{weightGapPct !== null && (
<span className="text-xs text-gray-500">
Selisih terakhir{' '}
<span className="font-semibold text-gray-700">{weightGapPct.toFixed(0)}%</span>
</span>
)}
</div>
<div className="h-80 rounded-xl border border-gray-100 bg-white p-4 shadow-sm">
<ResponsiveContainer width="100%" height="100%">
<ComposedChart
data={gapChartRows}
margin={{ top: 8, right: 44, bottom: 4, left: 0 }}
>
{/* Solid hairline grid: dashes read as a threshold when they
are only a grid. */}
<CartesianGrid vertical={false} stroke="#f1f1f0" />
<XAxis
dataKey="day"
tickFormatter={(val) => `H${val}`}
tick={{ fontSize: 11, fill: '#6b7280' }}
axisLine={false}
tickLine={false}
minTickGap={16}
/>
<YAxis
tick={{ fontSize: 11, fill: '#6b7280' }}
axisLine={false}
tickLine={false}
width={48}
label={{
value: 'gram',
angle: -90,
position: 'insideLeft',
style: { fontSize: 11, fill: '#9ca3af' },
}}
/>
<Tooltip
cursor={{ stroke: '#c4b5fd', strokeWidth: 1 }}
contentStyle={{
borderRadius: '10px',
border: '1px solid #ede9fe',
boxShadow: '0 8px 20px -8px rgb(0 0 0 / 0.25)',
fontSize: '12px',
}}
labelFormatter={(val) => `Hari ke-${val}`}
formatter={(value: number | string, name: string) => {
if (name === 'bandBase' || name === 'bandSize') return [];
return [`${Math.round(Number(value)).toLocaleString('id-ID')} g`, name];
}}
/>
<Legend
iconType="plainline"
wrapperStyle={{ fontSize: '12px', paddingTop: '8px' }}
/>
{/* The gap IS the story. Two stacked areas draw the band
between actual and target: an invisible base, then the
shortfall itself in the status colour. */}
<Area
dataKey="bandBase"
stackId="band"
stroke="none"
fill="none"
legendType="none"
isAnimationActive={false}
/>
<Area
dataKey="bandSize"
stackId="band"
stroke="none"
fill={gapFill}
fillOpacity={1}
legendType="none"
isAnimationActive={false}
/>
<Line
type="monotone"
dataKey="target"
name="Target CP 707"
stroke="#9ca3af"
strokeWidth={2}
strokeDasharray="5 4"
dot={false}
isAnimationActive={false}
/>
<Line
type="monotone"
dataKey="actual"
name="Bobot aktual"
stroke="#7c3aed"
strokeWidth={2.5}
dot={false}
activeDot={{ r: 5, strokeWidth: 2, stroke: '#ffffff' }}
isAnimationActive={false}
label={<WeightEndLabel rows={gapChartRows} />}
/>
</ComposedChart>
</ResponsiveContainer>
</div>
<p className="mt-2 text-xs text-gray-500">
Area terarsir menunjukkan jarak bobot aktual terhadap target CP 707.
</p>
</div>
)}
{weeklyDeparture.length > 0 && (
<div className="mt-6 pt-4 border-t border-purple-100" data-pdf-block>
<div className="mb-3 flex items-baseline justify-between gap-3">
<h4 className="text-sm font-bold text-purple-700">Ke Mana Ayam Keluar Kandang</h4>
<span className="text-xs text-gray-500">per minggu siklus</span>
</div>
{/* Small multiples on a shared week axis. Harvest dwarfs
mortality by two orders of magnitude, so they get their own
scales rather than one stack that hides the smaller series. */}
<div className={`grid gap-4 ${hasHarvest ? 'lg:grid-cols-2' : ''}`} data-pdf-stack>
<div
className="rounded-xl border border-gray-100 bg-white p-4 shadow-sm"
data-pdf-block
>
<div className="mb-1 text-xs font-semibold text-gray-700">
Deplesi — mati &amp; afkir
</div>
<div className="h-56">
<ResponsiveContainer width="100%" height="100%">
<ComposedChart
data={weeklyDeparture}
margin={{ top: 12, right: 8, bottom: 4, left: 0 }}
>
<CartesianGrid vertical={false} stroke="#f1f1f0" />
<XAxis
dataKey="minggu"
tickFormatter={(val) => `M${val}`}
tick={{ fontSize: 11, fill: '#6b7280' }}
axisLine={false}
tickLine={false}
/>
<YAxis
tick={{ fontSize: 11, fill: '#6b7280' }}
axisLine={false}
tickLine={false}
width={44}
/>
<Tooltip
cursor={{ fill: 'rgba(124, 58, 237, 0.06)' }}
contentStyle={{
borderRadius: '10px',
border: '1px solid #ede9fe',
boxShadow: '0 8px 20px -8px rgb(0 0 0 / 0.25)',
fontSize: '12px',
}}
labelFormatter={(val) => `Minggu ${val}`}
formatter={(value: number | string, name: string) => [
`${Number(value).toLocaleString('id-ID')} ekor`,
name,
]}
/>
<Legend
iconType="square"
wrapperStyle={{ fontSize: '12px', paddingTop: '6px' }}
/>
{/* 2px surface gap between stacked segments — a gap, not
a stroke around the marks. */}
<Bar
dataKey="mati"
name="Mati"
stackId="deplesi"
fill="#2a78d6"
radius={[0, 0, 0, 0]}
isAnimationActive={false}
/>
<Bar
dataKey="afkir"
name="Afkir"
stackId="deplesi"
fill="#eb6834"
radius={[4, 4, 0, 0]}
stroke="#ffffff"
strokeWidth={2}
isAnimationActive={false}
/>
</ComposedChart>
</ResponsiveContainer>
</div>
</div>
{hasHarvest && (
<div
className="mt-4 rounded-xl border border-gray-100 bg-white p-4 shadow-sm lg:mt-0"
data-pdf-block
>
<div className="mb-1 text-xs font-semibold text-gray-700">
Panen — keluar hidup
</div>
<div className="h-56">
<ResponsiveContainer width="100%" height="100%">
<ComposedChart
data={weeklyDeparture}
margin={{ top: 12, right: 8, bottom: 4, left: 0 }}
>
<CartesianGrid vertical={false} stroke="#f1f1f0" />
<XAxis
dataKey="minggu"
tickFormatter={(val) => `M${val}`}
tick={{ fontSize: 11, fill: '#6b7280' }}
axisLine={false}
tickLine={false}
/>
<YAxis
tick={{ fontSize: 11, fill: '#6b7280' }}
axisLine={false}
tickLine={false}
width={52}
tickFormatter={(val) =>
val >= 1000 ? `${Math.round(Number(val) / 1000)}rb` : String(val)
}
/>
<Tooltip
cursor={{ fill: 'rgba(124, 58, 237, 0.06)' }}
contentStyle={{
borderRadius: '10px',
border: '1px solid #ede9fe',
boxShadow: '0 8px 20px -8px rgb(0 0 0 / 0.25)',
fontSize: '12px',
}}
labelFormatter={(val) => `Minggu ${val}`}
formatter={(value: number | string) => [
`${Number(value).toLocaleString('id-ID')} ekor`,
'Panen',
]}
/>
<Bar
dataKey="panen"
name="Panen"
fill="#1baf7a"
radius={[4, 4, 0, 0]}
isAnimationActive={false}
/>
</ComposedChart>
</ResponsiveContainer>
</div>
</div>
)}
</div>
<p className="mt-2 text-xs text-gray-500">
Skalanya sengaja dipisah: panen mencapai belasan ribu ekor sementara deplesi
ratusan, jadi menumpuknya jadi satu batang akan menyembunyikan mortalitas.
</p>
</div>
)}
<div className="mt-6 pt-4 border-t border-purple-100">
<h4 className="text-sm font-bold text-purple-700 mb-2 flex items-center gap-2">
<span className="w-4 h-4 rounded-full bg-purple-100 flex items-center justify-center text-purple-600 text-xs">
✓
</span>
Kesimpulan
</h4>
<p className="text-sm text-gray-700 bg-purple-50/50 p-3 rounded-lg border border-purple-100">
{summary.headline}
</p>
</div>
<div className="mt-4">
<h4 className="text-sm font-bold text-purple-700 mb-2 flex items-center gap-2">
<span className="w-4 h-4 rounded-full bg-purple-100 flex items-center justify-center text-purple-600 text-xs">
✨
</span>
AI Insight
</h4>
<div className="text-sm text-gray-700 space-y-2 leading-relaxed">
{renderBulletList([...summary.bullets, ...summary.risks, ...summary.actions])}
</div>
</div>
</div>
<button
onClick={() => setDetailsOpen((value) => !value)}
className="inline-flex items-center gap-2 rounded-full border border-purple-200 bg-white px-4 py-2 text-sm font-medium text-purple-700 shadow-sm transition hover:bg-purple-50"
>
<span>{detailsOpen ? 'Sembunyikan detail' : 'Lihat detail per metrik'}</span>
</button>
{detailsOpen && (
<div className="space-y-3">
{renderDetailSection(
'🐔 Hitung Ayam',
detailed.hitung_ayam,
sectionBadgeClasses[detailed.hitung_ayam.status]
)}
{renderDetailSection(
'⚖️ Berat Ayam',
detailed.berat_ayam,
sectionBadgeClasses[detailed.berat_ayam.status]
)}
{detailed.fcr &&
renderDetailSection(
'🌾 FCR (Feed Conversion Ratio)',
detailed.fcr,
sectionBadgeClasses[detailed.fcr.status]
)}
{detailed.eef &&
renderDetailSection(
'📊 EEF (European Efficiency Factor)',
detailed.eef,
sectionBadgeClasses[detailed.eef.status]
)}
{renderDetailSection(
'🌡️ Panel IoT',
detailed.panel_iot,
sectionBadgeClasses[detailed.panel_iot.status]
)}
{renderDetailSection(
'📋 Kualitas Data',
detailed.data_quality,
sectionBadgeClasses[detailed.data_quality.status]
)}
</div>
)}
</div>
);
};
return (
<div
ref={pdfRef}
className="bg-gradient-to-br from-blue-50 to-purple-50 border border-blue-100 rounded-2xl shadow-lg overflow-hidden"
>
<div className="p-6">
<PdfReportHeader
title="AI Insight — Ringkasan Dashboard"
area={context.selectedArea || 'Sukawarna'}
kandangLabel={describeKandangScope(context.kandangs, kandangId)}
periodLabel={describeReportPeriod(reportType, reportPeriod)}
cycleId={context.cycleData?.id}
dataDateLabel={dashboardDataDateLabel}
/>
{/* Header */}
<div className="flex flex-col md:flex-row md:items-center justify-between mb-4 gap-4">
<div className="flex items-center gap-2">
<Sparkles className="w-6 h-6 text-purple-600" />
<div>
<h2 className="text-xl font-bold text-gray-900">AI Insight</h2>
<p className="text-[11px] text-gray-400" title={DATA_UPDATE_NOTICE_DETAIL}>
{DATA_UPDATE_NOTICE}
</p>
</div>
</div>
<div className="flex flex-wrap items-center gap-2" data-html2canvas-ignore="true">
{/* Filter controls only visible on dashboard overview */}
{(page === 'dashboard' || !page) && (
<>
<select
value={reportType}
onChange={(e) => setReportType(e.target.value as any)}
className="text-sm border-gray-300 rounded-lg shadow-sm focus:border-purple-500 focus:ring-purple-500"
>
<option value="daily">Harian</option>
{((context.kpis?.umur?.value || context.cycleData?.currentDay || 0) >= 35 ||
context.cycleData?.status === 'Completed') && (
<option value="end_cycle">Akhir Siklus</option>
)}
</select>
{/* Day picker: the cycle only ever reaches `currentDayVal`, so
later days are not offered. */}
{reportType === 'daily' && currentDayVal > 0 && (
<select
value={reportPeriod ?? `Hari ${currentDayVal}`}
onChange={(e) => setDayPeriod(e.target.value)}
className="text-sm border-gray-300 rounded-lg shadow-sm focus:border-purple-500 focus:ring-purple-500"
>
{Array.from({ length: currentDayVal }, (_, i) => i + 1).map((d) => (
<option key={d} value={`Hari ${d}`}>
Hari {d}
</option>
))}
</select>
)}
</>
)}
{structuredInsight && (
<button
onClick={downloadPdf}
disabled={loading}
title="Unduh PDF"
className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg border border-slate-800 bg-slate-900 text-white hover:bg-slate-800 active:scale-95 disabled:opacity-50 disabled:cursor-not-allowed transition-all text-xs font-semibold shadow-sm"
>
<Download className="w-4 h-4" />
<span className="hidden sm:inline">Unduh PDF</span>
</button>
)}
<button
onClick={handleRefresh}
disabled={loading}
className={`p-2 rounded-lg transition-all ${
loading
? 'bg-gray-200 cursor-not-allowed'
: 'bg-white hover:bg-gray-50 active:scale-95'
} shadow-sm border border-gray-200`}
title="Refresh insight"
>
<RefreshCw className={`w-5 h-5 text-gray-700 ${loading ? 'animate-spin' : ''}`} />
</button>
</div>
</div>
{/* Content */}
<div className="min-h-[120px]">
{!kpisReady && !loading && !insightText ? (
<div className="flex items-center justify-center py-8">
<div className="flex flex-col items-center gap-3">
<div className="animate-pulse rounded-full h-10 w-10 bg-purple-200"></div>
<p className="text-sm text-gray-600">Menunggu data dashboard dimuat...</p>
</div>
</div>
) : loading && !insightText ? (
<div className="flex items-center justify-center py-8">
<div className="flex flex-col items-center gap-3">
<div className="animate-spin rounded-full h-10 w-10 border-b-2 border-purple-600"></div>
<p className="text-sm text-gray-600">Menganalisis data peternakan...</p>
</div>
</div>
) : error && !insightText ? (
<div className="bg-red-50 border border-red-200 rounded-lg p-4">
<p className="text-red-700 text-sm font-semibold mb-2">Error:</p>
<p className="text-red-600 text-sm">{error}</p>
<p className="text-gray-600 text-xs mt-3">
💡 Tip: Buka browser console (F12) untuk melihat detail error
</p>
</div>
) : structuredInsight ? (
page && page !== 'dashboard' ? (
renderSingleSectionInsight(page)
) : (
renderStructuredInsight()
)
) : insightText ? (
<div className="prose prose-sm max-w-none">
<div
className="text-gray-800 leading-relaxed"
dangerouslySetInnerHTML={{ __html: insightHtml }}
/>
</div>
) : (
/* Idle: nothing stored for this scope and nothing running. The card
waits for an explicit click instead of generating on its own. */
<div className="flex flex-col items-center justify-center gap-3 py-8 text-center">
<p className="text-sm text-gray-500">
Belum ada AI Insight untuk periode ini. Klik tombol di bawah untuk membuatnya.
</p>
<button
onClick={handleRefresh}
disabled={loading || !kpisReady}
className="flex items-center gap-2 px-4 py-2 rounded-lg bg-purple-600 text-white text-sm font-semibold shadow-sm hover:bg-purple-700 active:scale-95 disabled:opacity-50 disabled:cursor-not-allowed transition-all"
>
<Sparkles className="w-4 h-4" />
<span>Buat AI Insight</span>
</button>
</div>
)}
</div>
{/* Footer */}
{lastUpdated && (
<div className="mt-4 pt-4 border-t border-gray-200">
<p className="text-xs text-gray-500">Terakhir diperbarui: {formatLastUpdated()}</p>
</div>
)}
</div>
</div>
);
};