"use client";

import { useState, useEffect, useRef } from "react";
import Link from "next/link";
import { useTheme } from "@/app/ThemeProvider";
import { useFamily } from "@/app/FamilyProvider";
import { useStageCheck, type BabyStage } from "@/hooks/useStageCheck";
import { LogModal, type LogType } from "@/components/LogModal";
import { getOfflineQueue, processOfflineQueue } from "@/lib/offline-queue";
import { calculateAge, formatTimeAgo } from "@/lib/formatting";
import { hourIST, isTodayIST, fmtTime } from "@/lib/date-ist";
import type { Log, AIChat, ChatSession } from "@/types";

/** Some Android cameras return file.type = "" — detect from extension as fallback. */
function resolveContentType(file: File): string {
  if (file.type && file.type !== "application/octet-stream") return file.type;
  const ext = file.name.split(".").pop()?.toLowerCase() ?? "";
  const map: Record<string, string> = {
    jpg: "image/jpeg", jpeg: "image/jpeg",
    png: "image/png", webp: "image/webp",
    heic: "image/heic", heif: "image/heic",
  };
  return map[ext] || "image/jpeg";
}

async function getSessions(cid: string): Promise<ChatSession[]> {
  try {
    const res = await fetch(`/api/chat?childId=${cid}`);
    const data = await res.json();
    return data.sessions || [];
  } catch { return []; }
}

async function createSession(cid: string): Promise<ChatSession | null> {
  try {
    const res = await fetch("/api/chat", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ childId: cid, title: "New conversation" }),
    });
    const data = await res.json();
    return data.session || null;
  } catch { return null; }
}


function getGreeting() {
  const hour = hourIST();
  if (hour < 12) return "Good morning";
  if (hour < 18) return "Good afternoon";
  return "Good evening";
}

function TodaySummary({ logs }: { logs: Log[] }) {
  const today = logs.filter(l => isTodayIST(l.loggedAt));
  const counts   = {
    feed:   today.filter(l => l.type === "feed").length,
    diaper: today.filter(l => l.type === "diaper").length,
    sleep:  today.filter(l => l.type === "sleep").length,
  };
  const lastFeed   = today.find(l => l.type === "feed");
  const lastDiaper = today.find(l => l.type === "diaper");
  const lastSleep  = today.find(l => l.type === "sleep");

  if (!lastFeed && !lastDiaper && !lastSleep) return null;

  return (
    <div className="mx-4 mb-3 bg-white dark:bg-gray-800 rounded-2xl shadow-sm overflow-hidden">
      <div className="grid grid-cols-3 divide-x divide-gray-100 dark:divide-gray-700">
        {[
          { icon: "🍼", label: "Feeds",   count: counts.feed,   last: lastFeed?.loggedAt },
          { icon: "🚼", label: "Diapers", count: counts.diaper, last: lastDiaper?.loggedAt },
          { icon: "😴", label: "Sleep",   count: counts.sleep,  last: lastSleep?.loggedAt },
        ].map(item => (
          <div key={item.label} className="flex flex-col items-center py-2 px-1">
            <span className="text-xl mb-0.5">{item.icon}</span>
            <span className="text-xl font-bold text-gray-800 dark:text-white leading-tight">{item.count}</span>
            <span className="text-xs text-gray-400 dark:text-gray-500">{item.label}</span>
            {item.last && (
              <span className="text-xs text-rose-400 mt-0.5">{formatTimeAgo(item.last)}</span>
            )}
          </div>
        ))}
      </div>
    </div>
  );
}

const AI_CHIP_FALLBACK = ["How much should baby eat?", "Sleep schedule tips?", "Development milestones?"];

export default function HomePage() {
  const [modalType, setModalType] = useState<"feed" | "diaper" | "sleep" | null>(null);
  const [aiOpen, setAiOpen] = useState(false);
  const [aiInput, setAiInput] = useState("");
  const [aiChats, setAiChats] = useState<AIChat[]>([]);
  const [aiLoading, setAiLoading] = useState(false);
  const [homeSessionId, setHomeSessionId] = useState<string | null>(null);
  const [pendingCount, setPendingCount] = useState(0);
  const [recentLogs, setRecentLogs] = useState<Log[]>([]);
  const [logsLoading, setLogsLoading] = useState(true);
  const [vaccineReminders, setVaccineReminders] = useState<any[]>([]);
  const [showPhoneNudge, setShowPhoneNudge] = useState(false);
  const [aiChips, setAiChips] = useState<string[]>([]);
  const [uploadingPhoto, setUploadingPhoto] = useState(false);
  const [photoError, setPhotoError]         = useState(false);
  const [showPhotoMenu, setShowPhotoMenu]   = useState(false);
  const photoInputRef = useRef<HTMLInputElement>(null);
  const { theme, toggle: toggleTheme } = useTheme();
  const { childId, child, familyId, loading, updateChildImage } = useFamily();
  const stage = useStageCheck(child?.birthDate ?? null);

  useEffect(() => {
    if (!childId) return;
    getSessions(childId).then(sessions => {
      if (sessions.length > 0) {
        setAiChats(sessions[0].messages);
      }
    });
  }, [childId]);

  useEffect(() => {
    if (!childId) return;
    const queue = getOfflineQueue();
    setPendingCount(queue.length);
    const handleOnline = () => processOfflineQueue();
    window.addEventListener("online", handleOnline);
    fetch(`/api/notifications?childId=${childId}`)
      .then(res => res.json())
      // Only vaccine notifications belong in the "Vaccine Reminder" banner —
      // the API also returns log/memory/garment nudges.
      .then(data => setVaccineReminders(
        (data.notifications || []).filter((n: { type?: string }) => n.type?.startsWith("vaccine_"))
      ))
      .catch(console.error);
    return () => window.removeEventListener("online", handleOnline);
  }, [childId]);

  // One-time nudge for existing users who have no phone number on file.
  // Dismissable; remembered in localStorage so it never nags repeatedly.
  useEffect(() => {
    if (!childId) return;
    if (localStorage.getItem("tia_phone_nudge_dismissed") === "1") return;
    fetch("/api/auth/profile")
      .then(r => r.json())
      .then(data => {
        if (data.user && !data.user.phone) setShowPhoneNudge(true);
      })
      .catch(() => {});
  }, [childId]);

  const dismissPhoneNudge = () => {
    setShowPhoneNudge(false);
    localStorage.setItem("tia_phone_nudge_dismissed", "1");
  };

  const fetchRecentLogs = async () => {
    if (!childId) return;
    try {
      const res  = await fetch(`/api/logs?childId=${childId}&limit=50`);
      const data = await res.json();
      setRecentLogs(data.entries || []);
    } catch {}
    setLogsLoading(false);
  };

  useEffect(() => {
    if (!childId) return;
    setLogsLoading(true);
    fetchRecentLogs();
  }, [childId]);

  useEffect(() => {
    if (!childId || !child) return;
    const age = calculateAge(child.birthDate);
    fetch("/api/ai", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        childId,
        messages: [{
          role: "user",
          content: `Generate exactly 3 short question chips (max 7 words each) a parent might want to ask right now about their baby ${child.name}, age ${age}. Reply ONLY with a JSON array of 3 strings, no other text.`,
        }],
      }),
    })
      .then(r => r.json())
      .then(d => {
        const chips = JSON.parse(d.reply);
        if (Array.isArray(chips) && chips.length > 0) setAiChips(chips.slice(0, 3));
        else setAiChips(AI_CHIP_FALLBACK);
      })
      .catch(() => setAiChips(AI_CHIP_FALLBACK));
  }, [childId, child?.id]);

  if (loading) {
    return (
      <div className="min-h-screen flex flex-col items-center justify-center gap-4 bg-gradient-to-br from-rose-50 to-amber-50 dark:from-gray-900 dark:to-gray-800">
        <div className="flex gap-3 text-4xl">
          {["🍼", "😴", "🚼", "👶"].map((e, i) => (
            <span key={i} className="animate-bounce" style={{ animationDelay: `${i * 120}ms` }}>{e}</span>
          ))}
        </div>
        <p className="text-sm text-gray-400">Loading Tia…</p>
      </div>
    );
  }

  if (!familyId) {
    if (typeof window !== "undefined") {
      window.location.href = "/login";
    }
    return <div className="min-h-screen flex items-center justify-center">Redirecting...</div>;
  }

  if (!childId) {
    return <div className="min-h-screen flex items-center justify-center">No child found. Add a child in Family settings.</div>;
  }

  const toggleDarkMode = () => {
    toggleTheme();
  };

  const handlePhotoChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file || !childId) return;
    const contentType = resolveContentType(file);
    setUploadingPhoto(true);
    setShowPhotoMenu(false);

    try {
      const initData = await fetch(`/api/children/${childId}`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ contentType, filename: file.name }),
      }).then(r => r.json());
      if (!initData.key) throw new Error(initData.error || "Upload failed");
      const { key, publicUrl } = initData;

      const putRes = await fetch(`/api/upload?${new URLSearchParams({ key, contentType })}`, {
        method: "PUT", body: file, headers: { "Content-Type": contentType },
      });
      if (!putRes.ok) throw new Error(`Upload failed (${putRes.status})`);

      await fetch(`/api/children/${childId}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ imageUrl: publicUrl }),
      });

      setPhotoError(false);
      updateChildImage(childId, `/api/img?key=${encodeURIComponent(key)}`);
    } catch (err) {
      console.error("Photo upload failed:", err);
    } finally {
      setUploadingPhoto(false);
      if (photoInputRef.current) photoInputRef.current.value = "";
    }
  };

  const handleRemovePhoto = async () => {
    setShowPhotoMenu(false);
    if (!childId) return;
    setUploadingPhoto(true);
    try {
      await fetch(`/api/children/${childId}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ imageUrl: null }),
      });
      updateChildImage(childId, null);
    } catch (err) {
      console.error("Remove photo failed:", err);
      alert("Failed to remove photo.");
    }
    setUploadingPhoto(false);
  };

  const handleAiChat = async (question?: string) => {
    const q = question || aiInput;
    if (!q.trim() || aiLoading) return;
    setAiLoading(true);
    setAiOpen(true);

    const inputVal = q.trim();
    if (!question) setAiInput("");

    let sessionId = homeSessionId;
    if (!sessionId) {
      const newSession = await createSession(childId);
      if (!newSession) { setAiLoading(false); return; }
      sessionId = newSession.id;
      setHomeSessionId(sessionId);
      setAiChats([]);
    }

    const userMsg: AIChat = { id: "tmp-" + Date.now(), role: "user", content: inputVal, createdAt: new Date().toISOString() };
    setAiChats(prev => [...prev, userMsg]);

    try {
      await fetch("/api/chat", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ sessionId, role: "user", content: inputVal }),
      });

      const res = await fetch("/api/ai", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ messages: [{ role: "user", content: inputVal }] }),
      });
      const data = await res.json();
      const reply = data.reply || "Sorry, I'm having trouble connecting. Please try again.";

      await fetch("/api/chat", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ sessionId, role: "assistant", content: reply }),
      });

      setAiChats(prev => [...prev, { id: "ai-" + Date.now(), role: "assistant", content: reply, createdAt: new Date().toISOString() }]);
    } catch (err) {
      console.error("AI chat error:", err);
    }
    setAiLoading(false);
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-rose-50 to-amber-50 dark:from-gray-900 dark:to-gray-800 pb-24">

<div className="p-4 flex justify-between items-center">
        <button className="p-2"><Link href="/menu"><svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 12h16M4 18h16" /></svg></Link></button>
        <div className="flex items-center gap-1">
          <Link href="/medical/emergency" className="p-2 text-red-500 hover:text-red-600" title="Emergency Guide">🆘</Link>
          <button onClick={toggleDarkMode} className="p-2">{theme === "dark" ? "☀️" : "🌙"}</button>
        </div>
      </div>

      <div className="px-6 pb-4">
        <h1 className="text-2xl font-bold">{getGreeting()} 👋</h1>
        <p className="text-gray-600 dark:text-gray-300">How is {child?.name || "your baby"} doing today?</p>
      </div>

      <div className="mx-4 mb-4 p-4 bg-white dark:bg-gray-800 rounded-2xl shadow-md flex items-center gap-4">
        {/* Avatar — tap to change/remove photo */}
        <div className="relative flex-shrink-0">
          <button
            onClick={() => {
              if (child?.imageUrl) setShowPhotoMenu(m => !m);
              else photoInputRef.current?.click();
            }}
            disabled={uploadingPhoto}
            className="relative group"
            title={child?.imageUrl ? "Photo options" : "Add photo"}
          >
            {child?.imageUrl && !photoError
              ? <img src={child.imageUrl} alt={child?.name} className="w-16 h-16 rounded-full object-cover" onError={() => setPhotoError(true)} />
              : <div className="w-16 h-16 bg-rose-100 dark:bg-rose-900 rounded-full flex items-center justify-center text-2xl">👶</div>
            }
            {/* Camera / upload overlay */}
            <div className={`absolute inset-0 rounded-full flex items-center justify-center transition-opacity ${
              uploadingPhoto ? "bg-black/40 opacity-100" : "bg-black/0 opacity-0 group-hover:opacity-100 group-active:opacity-100"
            }`}>
              {uploadingPhoto
                ? <div className="w-6 h-6 border-2 border-white border-t-transparent rounded-full animate-spin" />
                : <span className="text-white text-lg">📷</span>
              }
            </div>
          </button>

          {/* Photo options menu */}
          {showPhotoMenu && (
            <>
              <div className="fixed inset-0 z-40" onClick={() => setShowPhotoMenu(false)} />
              <div className="absolute left-0 top-[68px] z-50 bg-white dark:bg-gray-800 rounded-xl shadow-xl border border-gray-100 dark:border-gray-700 overflow-hidden w-44">
                <button
                  onClick={() => { setShowPhotoMenu(false); photoInputRef.current?.click(); }}
                  className="w-full flex items-center gap-2.5 px-3 py-2.5 text-sm text-gray-700 dark:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-700"
                >
                  <span>📷</span> Change photo
                </button>
                <button
                  onClick={handleRemovePhoto}
                  className="w-full flex items-center gap-2.5 px-3 py-2.5 text-sm text-red-500 hover:bg-red-50 dark:hover:bg-red-900/20 border-t border-gray-100 dark:border-gray-700"
                >
                  <span>🗑️</span> Remove photo
                </button>
              </div>
            </>
          )}
        </div>

        {/* Hidden file input */}
        <input
          ref={photoInputRef}
          type="file"
          accept="image/jpeg,image/jpg,image/png,image/webp,image/heic"
          className="hidden"
          onChange={handlePhotoChange}
        />

        {/* Name + age — tap to go to growth */}
        <Link href="/growth" className="flex-1 flex items-center gap-2">
          <div className="flex-1">
            <div className="text-lg font-semibold">{child?.name || "Baby"}</div>
            <div className="text-sm text-gray-500 dark:text-gray-400">{calculateAge(child?.birthDate || "")}</div>
          </div>
          <div className="text-2xl text-gray-400">→</div>
        </Link>
      </div>

      {pendingCount > 0 && (
        <button
          onClick={() => { processOfflineQueue(); setPendingCount(0); }}
          className="mx-4 mb-3 w-[calc(100%-2rem)] bg-amber-100 text-amber-800 px-4 py-2 rounded-xl flex items-center justify-between"
        >
          <span>⚠️ {pendingCount} pending log{pendingCount > 1 ? "s" : ""}</span>
          <span className="text-sm font-medium">Retry now →</span>
        </button>
      )}

      {vaccineReminders.length > 0 && (
        <div className="mx-4 mb-4 bg-red-50 border border-red-200 px-4 py-3 rounded-xl">
          <Link href="/medical" className="flex items-center justify-between">
            <div>
              <div className="font-semibold text-red-700">💊 Vaccine Reminder</div>
              <div className="text-sm text-red-600">
                {vaccineReminders[0].message}
              </div>
            </div>
            <span className="text-red-400">→</span>
          </Link>
        </div>
      )}

      {showPhoneNudge && (
        <div className="mx-4 mb-4 bg-rose-50 dark:bg-rose-900/20 border border-rose-200 dark:border-rose-800/40 px-4 py-3 rounded-xl flex items-center gap-3">
          <span className="text-xl flex-shrink-0">📱</span>
          <div className="flex-1 min-w-0">
            <div className="font-semibold text-rose-700 dark:text-rose-300 text-sm">Add your phone number</div>
            <div className="text-xs text-rose-600 dark:text-rose-400">Get important reminders &amp; updates about your baby</div>
          </div>
          <Link
            href="/profile"
            className="flex-shrink-0 text-xs font-semibold text-white bg-rose-400 px-3 py-1.5 rounded-lg active:scale-95 transition-transform"
          >
            Add
          </Link>
          <button
            onClick={dismissPhoneNudge}
            className="flex-shrink-0 text-rose-300 dark:text-rose-500 text-lg leading-none px-1"
            aria-label="Dismiss"
          >
            ✕
          </button>
        </div>
      )}

      <TodaySummary logs={recentLogs} />

      {stage && (() => {
        const h = hourIST();
        type Suggestion = { label: string; type: "feed" | "sleep" | "diaper" };
        const matrix: Record<BabyStage, Suggestion> =
          h >= 5  && h < 9  ? { newborn: { label: "Feed", type: "feed" }, infant: { label: "Feed", type: "feed" }, sitter: { label: "Feed", type: "feed" }, crawler: { label: "Feed", type: "feed" }, toddler: { label: "Feed", type: "feed" }, walker: { label: "Feed", type: "feed" } } :
          h >= 9  && h < 12 ? { newborn: { label: "Feed", type: "feed" }, infant: { label: "Feed + Diaper", type: "feed" }, sitter: { label: "Solids", type: "feed" }, crawler: { label: "Solids", type: "feed" }, toddler: { label: "Solids", type: "feed" }, walker: { label: "Solids", type: "feed" } } :
          h >= 12 && h < 15 ? { newborn: { label: "Nap time", type: "sleep" }, infant: { label: "Nap time", type: "sleep" }, sitter: { label: "Nap time", type: "sleep" }, crawler: { label: "Nap time", type: "sleep" }, toddler: { label: "Nap time", type: "sleep" }, walker: { label: "Rest time", type: "sleep" } } :
          h >= 15 && h < 18 ? { newborn: { label: "Feed", type: "feed" }, infant: { label: "Feed", type: "feed" }, sitter: { label: "Snack time", type: "feed" }, crawler: { label: "Snack time", type: "feed" }, toddler: { label: "Snack time", type: "feed" }, walker: { label: "Snack time", type: "feed" } } :
          h >= 18 && h < 21 ? { newborn: { label: "Evening feed", type: "feed" }, infant: { label: "Evening feed", type: "feed" }, sitter: { label: "Dinner feed", type: "feed" }, crawler: { label: "Dinner feed", type: "feed" }, toddler: { label: "Dinner feed", type: "feed" }, walker: { label: "Dinner feed", type: "feed" } } :
                              { newborn: { label: "Night feed", type: "feed" }, infant: { label: "Night feed", type: "feed" }, sitter: { label: "Bedtime", type: "sleep" }, crawler: { label: "Bedtime", type: "sleep" }, toddler: { label: "Bedtime", type: "sleep" }, walker: { label: "Bedtime", type: "sleep" } };
        const s = matrix[stage.stage];
        return (
          <div className="mx-4 mb-3 bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-700 rounded-2xl px-4 py-3 flex items-center justify-between">
            <div>
              <p className="text-xs font-semibold text-amber-600 dark:text-amber-400 uppercase tracking-wide">Suggested now</p>
              <p className="text-base font-bold text-amber-900 dark:text-amber-100">{s.label}</p>
            </div>
            <button
              onClick={() => setModalType(s.type)}
              className="px-4 py-2 bg-amber-400 text-white rounded-xl text-sm font-semibold"
            >
              Log it →
            </button>
          </div>
        );
      })()}

      <div className="px-4 mb-4">
        <h2 className="font-semibold mb-3 ml-1">Quick Log</h2>
        <div className="flex gap-3 overflow-x-auto scrollbar-hide pb-1 -mx-4 px-4">
          <button onClick={() => setModalType("feed")} className="flex-shrink-0 flex flex-col items-center p-4 bg-white dark:bg-gray-800 rounded-xl shadow-sm w-[72px]"><span className="text-3xl">🍼</span><span className="text-sm mt-1">Feed</span></button>
          <button onClick={() => setModalType("sleep")} className="flex-shrink-0 flex flex-col items-center p-4 bg-white dark:bg-gray-800 rounded-xl shadow-sm w-[72px]"><span className="text-3xl">😴</span><span className="text-sm mt-1">Sleep</span></button>
          <button onClick={() => setModalType("diaper")} className="flex-shrink-0 flex flex-col items-center p-4 bg-white dark:bg-gray-800 rounded-xl shadow-sm w-[72px]"><span className="text-3xl">🚼</span><span className="text-sm mt-1">Diaper</span></button>
          <Link href="/medical" className="flex-shrink-0 flex flex-col items-center p-4 bg-white dark:bg-gray-800 rounded-xl shadow-sm w-[72px]"><span className="text-3xl">💊</span><span className="text-sm mt-1">Medical</span></Link>
          <Link href="/wardrobe/add" className="flex-shrink-0 flex flex-col items-center p-4 bg-white dark:bg-gray-800 rounded-xl shadow-sm w-[72px]"><span className="text-3xl">👗</span><span className="text-sm mt-1">Wardrobe</span></Link>
        </div>
      </div>

      <div className="px-4">
        <div className="flex justify-between items-center mb-3">
          <h2 className="font-semibold ml-1">Ask AI</h2>
          <Link href="/ai" className="text-rose-500 text-sm">View all chats →</Link>
        </div>
        <div className="p-4 bg-white dark:bg-gray-800 rounded-2xl shadow-md">
          <div className="flex gap-2 mb-3">
            <input type="text" value={aiInput} onChange={e => setAiInput(e.target.value)} onKeyDown={e => e.key === "Enter" && handleAiChat()} placeholder="Ask anything..." className="flex-1 p-2 border dark:border-gray-600 rounded-xl text-sm bg-white dark:bg-gray-700 dark:text-white dark:placeholder-gray-400" disabled={aiLoading} />
            <button onClick={() => handleAiChat()} disabled={aiLoading || !aiInput.trim()} className="px-4 bg-rose-400 text-white rounded-xl text-sm">{aiLoading ? "..." : "Ask"}</button>
          </div>
          <div className="flex gap-2 overflow-x-auto scrollbar-hide">
            {(aiChips.length > 0 ? aiChips : AI_CHIP_FALLBACK).map((q, i) => (
              <button key={i} onClick={() => handleAiChat(q)} className="flex-shrink-0 px-3 py-1.5 bg-rose-50 dark:bg-gray-700 text-rose-600 dark:text-rose-400 rounded-full text-sm whitespace-nowrap">{q}</button>
            ))}
          </div>
        </div>
      </div>

      <div className="px-4 mt-4">
        <div className="flex justify-between items-center mb-3">
          <h2 className="font-semibold ml-1">Recent Activity</h2>
          <Link href="/activity" className="text-rose-500 text-sm">See all →</Link>
        </div>
        <div className="space-y-2">
          {logsLoading ? <p className="text-gray-400 text-sm">Loading...</p> : recentLogs.length === 0 ? <p className="text-gray-400 text-sm">No logs yet today</p> : recentLogs.slice(0, 3).map(log => (
            <div key={log.id} className="flex items-center justify-between p-3 bg-white dark:bg-gray-800 rounded-xl">
              <div className="flex items-center gap-3">
                <span className="text-xl">{log.type === "feed" && "🍼"}{log.type === "sleep" && "😴"}{log.type === "diaper" && "🚼"}</span>
                <div><div className="font-medium capitalize">{log.type}</div><div className="text-xs text-gray-500 dark:text-gray-400">{fmtTime(log.loggedAt)}</div></div>
              </div>
              {log.amount && <span className="text-sm text-gray-500 dark:text-gray-400">{log.amount}ml</span>}
            </div>
          ))}
        </div>
      </div>

      <LogModal
        type={modalType}
        childId={childId}
        onClose={() => setModalType(null)}
        onSaved={fetchRecentLogs}
        smartDefault={modalType ? (() => {
          const last = recentLogs.find(l => l.type === modalType);
          return last?.subType ? { subType: last.subType, amountMl: last.amount ?? undefined } : null;
        })() : null}
      />

      {aiOpen && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50" onClick={() => { setAiOpen(false); setHomeSessionId(null); }}>
          <div className="bg-white dark:bg-gray-800 rounded-2xl p-4 w-full max-w-sm mx-4 max-h-[80vh] flex flex-col" onClick={e => e.stopPropagation()}>
            <div className="flex justify-between items-center mb-3"><h2 className="font-bold">Ask AI</h2><button onClick={() => { setAiOpen(false); setHomeSessionId(null); }}>✕</button></div>
            <div className="flex-1 overflow-y-auto space-y-3 mb-3 min-h-[250px]">
              {aiChats.map((chat) => (<div key={chat.id} className={`max-w-[85%] p-3 rounded-xl text-sm ${chat.role === "user" ? "ml-auto bg-rose-400 text-white" : "bg-rose-50 dark:bg-gray-700"}`}>{chat.content}</div>))}
              {aiLoading && <div className="bg-rose-50 dark:bg-gray-700 p-3 rounded-xl text-sm animate-pulse">Thinking...</div>}
            </div>
            <div className="flex gap-2">
              <input type="text" value={aiInput} onChange={e => setAiInput(e.target.value)} onKeyDown={e => e.key === "Enter" && handleAiChat()} placeholder="Ask a question..." className="flex-1 p-2 border dark:border-gray-600 rounded-xl text-sm dark:bg-gray-700 dark:text-white dark:placeholder-gray-400" disabled={aiLoading} />
              <button onClick={() => handleAiChat()} disabled={aiLoading || !aiInput.trim()} className="px-3 bg-rose-400 text-white rounded-xl">➤</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}