import { useState, useEffect, useCallback, useContext, useRef } from "react";
import { AuthContext } from "./AuthContext";
import { Search } from "lucide-react";

// Import pages/views
import Login from "./pages/Login";
import Register from "./pages/Register";
import ProfilePage from "./pages/ProfilePage";

// Import refactored components
import CreateModal from "./components/CreateModal";
import BeanForm from "./components/BeanForm";
import BrewForm from "./components/BrewForm";
import BeanDetail from "./components/BeanDetail";
import BrewCard from "./components/BrewCard";
import BottomNav from "./components/BottomNav";
import IosPromptModal from "./components/IosPromptModal";
import UpdatePrompt from "./components/UpdatePrompt";
import SyncIndicator from "./components/SyncIndicator";


// Import constants
import { METHODS, METHOD_LABELS, METHOD_ICONS, METHOD_COLORS, getRoastAgingInfo } from "./constants";

// ─── Storage helpers ───
const STORAGE_KEY = "coffee-logbook-data";
const defaultData = { beans: [], brewLogs: [], lastSyncedAt: null };

const storage = {
  get: async (key) => {
    try {
      const val = localStorage.getItem(key);
      return val ? { value: val } : null;
    } catch { return null; }
  },
  set: async (key, val) => {
    try { localStorage.setItem(key, val); } catch (e) { console.error("Storage set failed:", e); }
  }
};

async function loadData() {
  try {
    const result = await storage.get(STORAGE_KEY);
    if (result) {
      const parsed = JSON.parse(result.value);
      return { beans: parsed.beans || [], brewLogs: parsed.brewLogs || [], lastSyncedAt: parsed.lastSyncedAt || null };
    }
    return defaultData;
  } catch { return defaultData; }
}

async function saveData(data) {
  try { await storage.set(STORAGE_KEY, JSON.stringify(data)); }
  catch (e) { console.error("Save failed:", e); }
}

const uid = () => Date.now().toString(36) + Math.random().toString(36).slice(2, 7);

const LoadingScreen = () => (
  <div className="w-full max-w-[480px] mx-auto min-h-screen border-x border-[#E8DFD3] dark:border-[#3B2217] bg-[#FAF6F1] dark:bg-[#150B07] max-sm:border-x-0 flex items-center justify-center transition-colors duration-200">
    <div className="text-center text-[#9C8B7A] dark:text-[#C8B9A6]"><div className="text-4xl">☕</div><div className="mt-2 text-sm">Loading…</div></div>
  </div>
);

function MethodIcon({ method, className }) {
  const props = {
    className: className || "w-8 h-8",
    viewBox: "0 0 24 24",
    fill: "none",
    stroke: "currentColor",
    strokeWidth: "1.5",
    strokeLinecap: "round",
    strokeLinejoin: "round"
  };

  switch (method) {
    case "pourover":
      return (
        <svg {...props}>
          <path d="M5 5h14l-4 7H9l-4-7z" />
          <path d="M7 12h10" />
          <path d="M9.5 12L7.5 19.5h9l-2-7.5" />
          <path d="M10 2.5a.5.5 0 01.5-.5h3a.5.5 0 01.5.5" />
        </svg>
      );
    case "espresso":
      return (
        <svg {...props}>
          <path d="M5 8h10v5c0 2.5-2 4.5-5 4.5S5 15.5 5 13V8z" />
          <path d="M15 10.5h6v1.5h-6z" />
          <path d="M3 18.5c4.5 2 13.5 2 18 0" />
          <path d="M10 17.5v2" />
        </svg>
      );
    case "coldbrew":
      return (
        <svg {...props}>
          <path d="M7 4h10l-1.5 16.5c0 1-1.5 1.5-3.5 1.5s-3.5-.5-3.5-1.5L7 4z" />
          <path d="M9.5 12h3v3h-3z" />
          <path d="M11.5 8h3v3h-3z" />
          <path d="M12 2l-2 4" />
        </svg>
      );
    case "aeropress":
      return (
        <svg {...props}>
          <path d="M8 8h8v12H8z" />
          <path d="M6 20h12" />
          <path d="M10 8V3h4v5" />
          <path d="M9 3h6" />
          <path d="M9 7.5h6" />
        </svg>
      );
    case "frenchpress":
      return (
        <svg {...props}>
          <path d="M8 6h8v14c0 1-1 2-3 2h-2c-2 0-3-1-3-2V6z" />
          <path d="M7 6h10" />
          <circle cx="12" cy="2.5" r="1.5" />
          <path d="M12 4v8" />
          <path d="M9 12h6" />
          <path d="M8 8H5v10h3" />
        </svg>
      );
    case "chemex":
      return (
        <svg {...props}>
          <path d="M8 4h8c-1 3.5-1.5 5-1.5 8s.5 4.5 1.5 8H8c1-3.5 1.5-5 1.5-8s-.5-4.5-1.5-8z" />
          <path d="M9.5 10.5h5" />
          <path d="M9.5 12.5h5" />
          <circle cx="12" cy="11.5" r="1.2" fill="currentColor" />
        </svg>
      );
    case "mokapot":
      return (
        <svg {...props}>
          <path d="M9 5h6l-1 7H10z" />
          <path d="M10 12.5h4l1.2 7H8.8z" />
          <path d="M9 5l3-2 3 2" />
          <circle cx="12" cy="3" r="1" />
          <path d="M9 6.2l-2 1.5 2 1" />
          <path d="M14 7.5h3.5v7H14" />
        </svg>
      );
    case "v60":
      return (
        <svg {...props}>
          <path d="M6 5h12l-4.5 7h-3z" />
          <path d="M8 12h8" />
          <path d="M9.5 12L8.5 19h7l-1-7" />
          <path d="M16.5 5a2 2 0 010 4" />
        </svg>
      );
    case "syphon":
      return (
        <svg {...props}>
          <path d="M9.5 4h5v5h-5z" />
          <path d="M12 9v4" />
          <circle cx="12" cy="16" r="3.2" />
          <path d="M7 21h10" />
          <path d="M8.5 16H6v5h3v-2" />
        </svg>
      );
    case "dripbrew":
      return (
        <svg {...props}>
          <path d="M6 21h12" />
          <path d="M7 21V5c0-1 6-1 6 0v2" />
          <path d="M8.5 5h8v3h-8z" />
          <path d="M9.5 12h5v7h-5z" />
          <path d="M14.5 14h2v3h-2" />
          <path d="M11.5 8v2.5" />
        </svg>
      );
    default:
      return <span>☕</span>;
  }
}

// ─── Main App ───
export default function CoffeeLogbook() {
  const { token, user, loading, logout } = useContext(AuthContext);
  const [authView, setAuthView] = useState("login");
  const [data, setData] = useState(null);
  const [view, setView] = useState("dashboard");
  const [modal, setModal] = useState(null);
  const [createOpen, setCreateOpen] = useState(false);
  const [selectedBean, setSelectedBean] = useState(null);
  const [brewFilter, setBrewFilter] = useState("all");
  const [editingBean, setEditingBean] = useState(null);
  const [brewSearchQuery, setBrewSearchQuery] = useState("");

  const [isOnline, setIsOnline] = useState(navigator.onLine);
  const [syncing, setSyncing] = useState(false);
  const [showSyncedStatus, setShowSyncedStatus] = useState(false);

  const [prepActivePage, setPrepActivePage] = useState(0);

  useEffect(() => { loadData().then(setData); }, []);
  useEffect(() => {
    setBrewSearchQuery("");
    setPrepActivePage(0);
  }, [view]);

  const dataRef = useRef(data);
  dataRef.current = data;

  const syncData = useCallback(async (currentData = dataRef.current) => {
    if (!token || !currentData) return;
    if (!navigator.onLine) { setIsOnline(false); setShowSyncedStatus(true); return; }
    setIsOnline(true); setSyncing(true); setShowSyncedStatus(true);
    try {
      const { beans = [], brewLogs = [], lastSyncedAt = null } = currentData;
      const res = await fetch('/api/sync', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` },
        body: JSON.stringify({ lastSyncedAt, beans, brewLogs })
      });
      if (!res.ok) throw new Error('Sync failed');
      const { serverTime, beans: serverBeans, brewLogs: serverLogs } = await res.json();
      const mergedBeans = [...beans];
      serverBeans.forEach(sb => { const i = mergedBeans.findIndex(b => b.id === sb.id); i >= 0 ? (new Date(sb.updatedAt) > new Date(mergedBeans[i].updatedAt || 0) && (mergedBeans[i] = sb)) : mergedBeans.push(sb); });
      const mergedLogs = [...brewLogs];
      serverLogs.forEach(sl => { const i = mergedLogs.findIndex(l => l.id === sl.id); i >= 0 ? (new Date(sl.updatedAt) > new Date(mergedLogs[i].updatedAt || 0) && (mergedLogs[i] = sl)) : mergedLogs.push(sl); });
      const nextData = {
        beans: mergedBeans.filter(b => !(b.isDeleted && new Date(b.updatedAt) <= new Date(serverTime))),
        brewLogs: mergedLogs.filter(l => !(l.isDeleted && new Date(l.updatedAt) <= new Date(serverTime))),
        lastSyncedAt: serverTime
      };
      setData(nextData); await saveData(nextData);
    } catch (err) { console.error('Failed to sync data:', err); }
    finally {
      setSyncing(false);
      if (navigator.onLine) setTimeout(() => setShowSyncedStatus(false), 2500);
      else setShowSyncedStatus(true);
    }
  }, [token]);

  useEffect(() => {
    const handleOnline = () => { setIsOnline(true); syncData(); };
    const handleOffline = () => { setIsOnline(false); setShowSyncedStatus(true); };
    window.addEventListener('online', handleOnline);
    window.addEventListener('offline', handleOffline);
    if (token && data) syncData();
    const interval = setInterval(() => { if (token && data) syncData(); }, 30000);
    return () => { window.removeEventListener('online', handleOnline); window.removeEventListener('offline', handleOffline); clearInterval(interval); };
  }, [token, data === null, syncData]);

  const persist = useCallback(async (newData) => {
    setData(newData); await saveData(newData); syncData(newData);
  }, [syncData]);


  if (loading) return <LoadingScreen />;

  if (!token || !user) {
    return (
      <div className="w-full max-w-[480px] mx-auto min-h-screen border-x border-[#E8DFD3] dark:border-[#3B2217] bg-[#FAF6F1] dark:bg-[#150B07] max-sm:border-x-0 transition-colors duration-200">
        {authView === "login" ? (
          <>
            <Login onLoginSuccess={() => {}} />
            <div className="text-center mt-5 px-5">
              <p className="text-[#9C8B7A] dark:text-[#C8B9A6] text-sm">Don't have an account?{' '}
                <button onClick={() => setAuthView("register")} className="border-none bg-transparent text-[#8B6914] dark:text-[#D4A325] cursor-pointer underline text-sm">Register</button>
              </p>
            </div>
          </>
        ) : (
          <>
            <Register onRegisterSuccess={() => setAuthView("login")} />
            <div className="text-center mt-5 px-5">
              <p className="text-[#9C8B7A] dark:text-[#C8B9A6] text-sm">Already have an account?{' '}
                <button onClick={() => setAuthView("login")} className="border-none bg-transparent text-[#8B6914] dark:text-[#D4A325] cursor-pointer underline text-sm">Login</button>
              </p>
            </div>
          </>
        )}
      </div>
    );
  }

  if (!data) return <LoadingScreen />;

  const allBeans = data.beans || [];
  const allLogs = data.brewLogs || [];
  const beans = allBeans.filter(b => !b.isDeleted);
  const brewLogs = allLogs.filter(l => !l.isDeleted);

  const addBean = (form) => { persist({ ...data, beans: [...allBeans, { id: uid(), ...form, updatedAt: new Date().toISOString(), isDeleted: false }] }); setModal(null); };
  const updateBean = (form) => {
    const now = new Date().toISOString();
    persist({ ...data, beans: allBeans.map(b => b.id === editingBean.id ? { ...b, ...form, updatedAt: now } : b) });
    setModal(null); setEditingBean(null);
    if (selectedBean?.id === editingBean.id) setSelectedBean({ ...selectedBean, ...form, updatedAt: now });
  };
  const deleteBean = (id) => {
    const now = new Date().toISOString();
    persist({ ...data, beans: allBeans.map(b => b.id === id ? { ...b, isDeleted: true, updatedAt: now } : b), brewLogs: allLogs.map(l => l.beanId === id ? { ...l, isDeleted: true, updatedAt: now } : l) });
    setSelectedBean(null);
  };
  const addBrew = (form) => { persist({ ...data, brewLogs: [...allLogs, { id: uid(), createdAt: Date.now(), ...form, updatedAt: new Date().toISOString(), isDeleted: false }] }); setModal(null); };

  const getBeanName = (id) => allBeans.find(b => b.id === id)?.name || "Unknown Bean";
  const filteredLogs = (brewFilter === "all" ? brewLogs : brewLogs.filter(l => l.method === brewFilter))
    .filter(log => {
      if (!brewSearchQuery) return true;
      const dateObj = new Date(log.createdAt);
      const weekday = dateObj.toLocaleDateString("en-US", { weekday: "long" }).toLowerCase();
      const month = dateObj.toLocaleDateString("en-US", { month: "long" }).toLowerCase();
      const monthShort = dateObj.toLocaleDateString("en-US", { month: "short" }).toLowerCase();
      const dateNum = dateObj.getDate().toString();
      const year = dateObj.getFullYear().toString();

      const searchableText = [
        getBeanName(log.beanId).toLowerCase(),
        METHOD_LABELS[log.method]?.toLowerCase() || "",
        log.recipeDetails?.toLowerCase() || "",
        log.tasteNotes?.toLowerCase() || "",
        log.notes?.toLowerCase() || "",
        log.grindSize?.toLowerCase() || log.grind?.toLowerCase() || "",
        log.waterTemp?.toLowerCase() || "",
        log.brewRatio?.toLowerCase() || log.ratio?.toLowerCase() || "",
        log.brewTime?.toLowerCase() || log.time?.toLowerCase() || "",
        weekday,
        month,
        monthShort,
        dateNum,
        year
      ].join(" ");

      const queryWords = brewSearchQuery.trim().toLowerCase().split(/\s+/);
      return queryWords.every(word => searchableText.includes(word));
    })
    .sort((a, b) => b.createdAt - a.createdAt);
  const methodCounts = {};
  METHODS.forEach(m => methodCounts[m] = 0);
  brewLogs.forEach(l => { if (methodCounts[l.method] !== undefined) methodCounts[l.method]++; });

  const filterPillCls = (active) => `px-3.5 py-1.5 rounded-full border text-xs font-medium whitespace-nowrap cursor-pointer transition-all ${active ? "bg-[#2C1810] text-[#FAF6F1] border-[#2C1810] dark:bg-[#FAF6F1] dark:text-[#2C1810] dark:border-[#FAF6F1]" : "bg-white border-[#E8DFD3] text-[#6B5744] dark:bg-[#22120B] dark:border-[#3B2217] dark:text-[#C8B9A6]"}`;

  // Page title per view
  const pageTitles = { dashboard: "Brew Journal", beans: "Bean Recipes", brews: "Brew Logs", profile: "Profile" };
  const pageSubtitles = { dashboard: "Coffee Logbook", beans: "Your Collection", brews: "All Sessions", profile: "Account" };

  return (
    <div className="w-full max-w-[480px] mx-auto min-h-screen bg-[#FAF6F1] dark:bg-[#150B07] border-x border-[#E8DFD3] dark:border-[#3B2217] shadow-[0_0_30px_rgba(44,24,16,0.05)] dark:shadow-none max-sm:border-x-0 max-sm:shadow-none font-sans relative text-[#2C1810] dark:text-[#FAF6F1] transition-colors duration-200">

      {/* Header */}
      <div className="px-5 pt-6 pb-4 flex items-center justify-between sticky top-0 bg-[#FAF6F1]/95 dark:bg-[#150B07]/95 backdrop-blur-sm z-50 border-b border-[#E8DFD3] dark:border-[#3B2217] transition-colors duration-200">
        <div>
          <div className="text-[10px] text-[#9C8B7A] dark:text-[#C8B9A6] font-semibold tracking-[1.5px] uppercase">{pageSubtitles[view] || "Coffee Logbook"}</div>
          <h1 className="font-serif text-[21px] font-semibold tracking-tight text-[#2C1810] dark:text-[#FAF6F1] mt-0.5">{pageTitles[view] || "Brew Journal"}</h1>
        </div>
        <SyncIndicator isOnline={isOnline} syncing={syncing} showSyncedStatus={showSyncedStatus} />
      </div>

      {/* Content */}
      <div className="px-5 pt-4 pb-36">

        {/* ── Dashboard ── */}
        {/* ── Dashboard ── */}
        {view === "dashboard" && (
          <div className="animate-page-enter">
            {/* Preparation Methods */}
            <div className="text-[13px] font-semibold text-[#6B5744] dark:text-[#C8B9A6] uppercase tracking-widest mb-3">Preparation Methods</div>
            <div 
              className="flex overflow-x-auto pb-4 scrollbar-none snap-x snap-mandatory -mx-5"
              onScroll={(e) => {
                const scrollLeft = e.target.scrollLeft;
                const width = e.target.clientWidth;
                const page = Math.round(scrollLeft / width);
                setPrepActivePage(page);
              }}
            >
              {(() => {
                const chunks = [];
                for (let i = 0; i < METHODS.length; i += 8) {
                  chunks.push(METHODS.slice(i, i + 8));
                }
                return chunks.map((pageMethods, pageIdx) => (
                  <div key={pageIdx} className="w-full flex-shrink-0 snap-start grid grid-cols-4 gap-x-4 gap-y-5 px-5">
                    {pageMethods.map(m => (
                      <div key={m}
                        className="flex flex-col items-center cursor-pointer group"
                        onClick={() => { setBrewFilter(m); setView("brews"); }}>
                        <div className="w-full aspect-square flex items-center justify-center rounded-2xl bg-white dark:bg-[#22120B] border border-[#E8DFD3] dark:border-[#3B2217] transition-all group-hover:scale-[1.03] group-active:scale-[0.98] shadow-[0_1px_3px_rgba(44,24,16,0.04)] dark:shadow-none"
                          style={{ borderTop: `3px solid ${METHOD_COLORS[m]}` }}>
                          <MethodIcon method={m} className="w-9 h-9 text-[#6B5744] dark:text-[#C8B9A6] group-hover:text-[#2C1810] dark:group-hover:text-[#FAF6F1] transition-colors" />
                        </div>
                        <div className="text-[10px] text-[#9C8B7A] dark:text-[#C8B9A6] uppercase tracking-wider mt-2 text-center font-medium group-hover:text-[#2C1810] dark:group-hover:text-[#FAF6F1] transition-colors">
                          {METHOD_LABELS[m]}
                        </div>
                      </div>
                    ))}
                  </div>
                ));
              })()}
            </div>
            {(() => {
              const pagesCount = Math.ceil(METHODS.length / 8);
              return pagesCount > 1 ? (
                <div className="flex justify-center gap-1.5 mt-1 mb-6">
                  {Array.from({ length: pagesCount }).map((_, idx) => (
                    <div key={idx} className={`w-1.5 h-1.5 rounded-full transition-all duration-300 ${prepActivePage === idx ? "bg-[#2C1810] dark:bg-[#FAF6F1] w-3" : "bg-[#E8DFD3] dark:bg-[#3B2217]"}`} />
                  ))}
                </div>
              ) : <div className="mb-6" />;
            })()}

            {/* Statistics */}
            <div className="flex gap-2 mb-5">
              {[{ num: beans.length, label: "Beans" }, { num: brewLogs.length, label: "Brews" }, { num: new Set(brewLogs.map(l => l.beanId)).size, label: "Tried" }].map(s => (
                <div key={s.label} className="flex-1 bg-white dark:bg-[#22120B] border border-[#E8DFD3] dark:border-[#3B2217] rounded-2xl p-3.5 text-center transition-colors duration-200">
                  <div className="font-serif text-2xl font-bold text-[#2C1810] dark:text-[#FAF6F1]">{s.num}</div>
                  <div className="text-[10px] text-[#9C8B7A] dark:text-[#C8B9A6] uppercase tracking-widest mt-0.5">{s.label}</div>
                </div>
              ))}
            </div>

            {/* Recent Brews */}
            <div className="text-[13px] font-semibold text-[#6B5744] dark:text-[#C8B9A6] uppercase tracking-widest mb-3">Recent Brews</div>
            {brewLogs.length === 0 ? (
              <div className="text-center py-12 text-[#9C8B7A] dark:text-[#C8B9A6]">
                <div className="text-4xl mb-3 opacity-50 dark:opacity-80">📝</div>
                <h3 className="text-base mb-1.5 font-serif text-[#6B5744] dark:text-[#FAF6F1]">No brews yet</h3>
                <p className="text-[13px] leading-relaxed">Tap the + button to log your first brew.</p>
              </div>
            ) : brewLogs.sort((a, b) => b.createdAt - a.createdAt).slice(0, 5).map(log => (
              <BrewCard key={log.id} log={log} beanName={getBeanName(log.beanId)} />
            ))}
          </div>
        )}

        {/* ── Bean Library ── */}
        {view === "beans" && !selectedBean && (
          <div className="animate-page-enter">
            <div className="text-[13px] font-semibold text-[#6B5744] dark:text-[#C8B9A6] uppercase tracking-widest mb-3">Your Beans ({beans.length})</div>
            {beans.length === 0 ? (
              <div className="text-center py-12 text-[#9C8B7A] dark:text-[#C8B9A6]">
                <div className="text-4xl mb-3 opacity-50 dark:opacity-80">🫘</div>
                <h3 className="text-base mb-1.5 font-serif text-[#6B5744] dark:text-[#FAF6F1]">Library is empty</h3>
                <p className="text-[13px] leading-relaxed">Tap + to add your first coffee bean.</p>
              </div>
            ) : beans.map(bean => {
              const count = brewLogs.filter(l => l.beanId === bean.id).length;
              const roastTagCls = bean.roastType?.toLowerCase().includes("dark") 
                ? "bg-[#E0D0BD] text-[#4A3520] dark:bg-[#2F1E12] dark:text-[#BCA38A]" 
                : bean.roastType?.toLowerCase().includes("medium") 
                  ? "bg-[#F0E0C8] text-[#6B4E2A] dark:bg-[#402A14] dark:text-[#D9AC7B]" 
                  : "bg-[#FFF3D6] text-[#8B6914] dark:bg-[#4A3912] dark:text-[#E6B640]";
              return (
                <div key={bean.id}
                  className="bg-white dark:bg-[#22120B] rounded-2xl shadow-[0_1px_3px_rgba(44,24,16,0.06),0_4px_12px_rgba(44,24,16,0.04)] dark:shadow-[0_4px_12px_rgba(0,0,0,0.2)] p-[18px] mb-3 border border-[#E8DFD3] dark:border-[#3B2217] cursor-pointer transition-all hover:shadow-[0_4px_16px_rgba(44,24,16,0.08)] dark:hover:shadow-[0_4px_16px_rgba(0,0,0,0.35)] active:scale-[0.99]"
                  onClick={() => setSelectedBean(bean)}>
                  <div className="flex justify-between items-start gap-3 mb-2">
                    {bean.image && <img src={bean.image} alt="" className="w-14 h-14 rounded-xl object-cover flex-shrink-0" />}
                    <div className="flex-1 min-w-0">
                      <div className="font-serif text-[17px] font-semibold text-[#2C1810] dark:text-[#FAF6F1]">{bean.name}</div>
                      {bean.roastery && <div className="text-[13px] text-[#6B5744] dark:text-[#C8B9A6] mt-0.5">{bean.roastery}</div>}
                    </div>
                    <span className="text-[11px] px-2.5 py-1 rounded-full bg-[#F3EDE4] dark:bg-[#2C1810] text-[#6B5744] dark:text-[#C8B9A6] font-medium flex-shrink-0">{count} brew{count !== 1 ? "s" : ""}</span>
                  </div>
                  {bean.tastingNotes && <div className="text-[13px] text-[#6B5744] dark:text-[#C8B9A6] italic mt-1.5 leading-snug">👅 {bean.tastingNotes}</div>}
                  <div className="flex gap-2 mt-2.5 flex-wrap">
                    {bean.roastType && <span className={`text-[11px] px-2.5 py-1 rounded-full font-medium ${roastTagCls}`}>{bean.roastType}</span>}
                    {bean.roastDate && <span className="text-[11px] px-2.5 py-1 rounded-full bg-[#F3EDE4] dark:bg-[#2C1810] text-[#6B5744] dark:text-[#C8B9A6] font-medium">Roasted {bean.roastDate}</span>}
                    {(() => {
                      const ageInfo = getRoastAgingInfo(bean.roastDate);
                      return ageInfo ? (
                        <span className={`text-[11px] px-2.5 py-1 rounded-full font-medium ${ageInfo.style}`}>
                          {ageInfo.label}
                        </span>
                      ) : null;
                    })()}
                  </div>
                </div>
              );
            })}
          </div>
        )}

        {/* ── Bean Detail ── */}
        {view === "beans" && selectedBean && (
          <div className="animate-page-enter">
            <BeanDetail bean={selectedBean} logs={brewLogs}
              onBack={() => setSelectedBean(null)}
              onEdit={() => { setEditingBean(selectedBean); setModal("editBean"); }}
              onDelete={() => { if (confirm("Delete this bean and all its brew logs?")) deleteBean(selectedBean.id); }}
            />
          </div>
        )}

        {/* ── Brew Logs ── */}
        {view === "brews" && (
          <div className="animate-page-enter">
            {/* Search Bar */}
            <div className="mb-4 relative">
              <input
                type="text"
                value={brewSearchQuery}
                onChange={(e) => setBrewSearchQuery(e.target.value)}
                placeholder="Search brews (e.g. June, espresso, floral...)"
                className="w-full pl-10 pr-10 py-3.5 bg-white dark:bg-[#22120B] border border-[#E8DFD3] dark:border-[#3B2217] rounded-2xl text-xs placeholder-[#9C8B7A] dark:placeholder-[#C8B9A6] text-[#2C1810] dark:text-[#FAF6F1] shadow-[0_1px_3px_rgba(44,24,16,0.04)] dark:shadow-none focus:outline-none focus:border-[#8B6914] dark:focus:border-[#D4A325] transition-all"
              />
              {/* Search Icon */}
              <div className="absolute left-3.5 top-1/2 -translate-y-1/2 text-[#9C8B7A] dark:text-[#C8B9A6] flex items-center pointer-events-none">
                <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" className="opacity-70">
                  <circle cx="11" cy="11" r="8" />
                  <line x1="21" y1="21" x2="16.65" y2="16.65" />
                </svg>
              </div>
              {/* Clear button */}
              {brewSearchQuery && (
                <button
                  onClick={() => setBrewSearchQuery("")}
                  className="absolute right-3.5 top-1/2 -translate-y-1/2 w-6 h-6 flex items-center justify-center rounded-full text-[#9C8B7A] dark:text-[#C8B9A6] hover:text-[#2C1810] dark:hover:text-[#FAF6F1] border-none bg-transparent cursor-pointer text-base font-bold transition-colors"
                >
                  &times;
                </button>
              )}
            </div>

            <div className="flex gap-1.5 mb-4 overflow-x-auto pb-1">
              <button className={filterPillCls(brewFilter === "all")} onClick={() => setBrewFilter("all")}>All</button>
              {METHODS.map(m => (
                <button key={m} className={filterPillCls(brewFilter === m)} onClick={() => setBrewFilter(m)}>
                  {METHOD_ICONS[m]} {METHOD_LABELS[m]}
                </button>
              ))}
            </div>
            {filteredLogs.length === 0 ? (
              <div className="text-center py-12 text-[#9C8B7A] dark:text-[#C8B9A6]">
                <div className="flex justify-center mb-3 text-[#9C8B7A] dark:text-[#C8B9A6] opacity-60">
                  {brewSearchQuery ? <Search size={36} strokeWidth={2} /> : <span className="text-4xl">📋</span>}
                </div>
                <h3 className="text-base mb-1.5 font-serif text-[#6B5744] dark:text-[#FAF6F1]">
                  {brewSearchQuery ? "No search results" : `No logs ${brewFilter !== "all" ? `for ${METHOD_LABELS[brewFilter]}` : "yet"}`}
                </h3>
                <p className="text-[13px] leading-relaxed">
                  {brewSearchQuery ? "Try refining your search terms or filters." : "Start brewing and log your recipes here."}
                </p>
              </div>
            ) : filteredLogs.map(log => (
              <BrewCard key={log.id} log={log} beanName={getBeanName(log.beanId)} />
            ))}
          </div>
        )}

        {/* ── Profile ── */}
        {view === "profile" && (
          <div className="animate-page-enter">
            <ProfilePage user={user} isOnline={isOnline} syncing={syncing} showSyncedStatus={showSyncedStatus} />
          </div>
        )}
      </div>

      {/* Floating Bottom Navigation */}
      <BottomNav
        view={view}
        setView={setView}
        setSelectedBean={setSelectedBean}
        onCreatePress={() => setCreateOpen(true)}
      />

      {/* Create Modal */}
      {createOpen && (
        <CreateModal
          onClose={() => setCreateOpen(false)}
          onAddBean={() => setModal("addBean")}
          onAddBrew={() => setModal("addBrew")}
        />
      )}

      {/* Modals */}
      {modal === "addBean" && <BeanForm onSave={addBean} onClose={() => setModal(null)} />}
      {modal === "editBean" && editingBean && <BeanForm initial={editingBean} onSave={updateBean} onClose={() => { setModal(null); setEditingBean(null); }} />}
      {modal === "addBrew" && <BrewForm beans={beans} onSave={addBrew} onClose={() => setModal(null)} />}
      
      {/* iOS/iPadOS PWA Install Prompt */}
      <IosPromptModal />

      {/* PWA Update Prompt */}
      <UpdatePrompt />
    </div>
  );
}
