// Creek's Caffé — Admin backend v3 — premium design

// ─── DATA LAYER ─────────────────────────────────────────────────────────────
const STORAGE = {
  reservations: "creeks_reservations",
  cake_orders: "creeks_cake_orders",
  catering_requests: "creeks_catering_requests",
};

const makeId = () =>
  typeof crypto !== "undefined" && "randomUUID" in crypto
    ? crypto.randomUUID()
    : `${Date.now()}-${Math.random().toString(16).slice(2)}`;

const getStored = (t) => { try { return JSON.parse(localStorage.getItem(STORAGE[t]) || "[]"); } catch { return []; } };
const setStored = (t, rows) => localStorage.setItem(STORAGE[t], JSON.stringify(rows));
const addStored = (t, payload) => {
  const now = new Date().toISOString();
  const r = { ...payload, id: makeId(), created_at: now, updated_at: now };
  setStored(t, [r, ...getStored(t)]);
  return r;
};
const updateStored = (t, id, changes) => {
  setStored(t, getStored(t).map(r => r.id === id ? { ...r, ...changes, updated_at: new Date().toISOString() } : r));
};

// ─── NOTIFICATIONS ───────────────────────────────────────────────────────────
const NOTIF_KEY = "creeks_notifications";
const getNotifsRaw = () => { try { return JSON.parse(localStorage.getItem(NOTIF_KEY)||"[]"); } catch { return []; } };
const addNotif = (n) => {
  const notif = { ...n, id: makeId(), created_at: new Date().toISOString(), read: false };
  localStorage.setItem(NOTIF_KEY, JSON.stringify([notif, ...getNotifsRaw()].slice(0,50)));
};
const markAllRead = () => localStorage.setItem(NOTIF_KEY, JSON.stringify(getNotifsRaw().map(n=>({...n,read:true}))));
const getUnreadCount = () => getNotifsRaw().filter(n=>!n.read).length;

window.creeksData = {
  createReservation: (input) => {
    const r = addStored("reservations", { ...input, status: "pending", source: "website" });
    addNotif({ type:"reservation", title:`Nova reserva — ${input.name}`, body:`${input.guests} pessoa(s) · ${input.reservation_date} às ${input.reservation_time||"--:--"}` });
    return r;
  },
  createCakeOrder: (input) => {
    const r = addStored("cake_orders", { ...input, status: "new" });
    addNotif({ type:"cake", title:`Pedido de bolo — ${input.name}`, body:`${input.cake_theme||"Sem tema"} · ${input.event_date||"Sem data"}` });
    return r;
  },
  createCateringRequest: (input) => {
    const r = addStored("catering_requests", { ...input, status: "new" });
    addNotif({ type:"catering", title:`Pedido de catering — ${input.name}`, body:`${input.number_of_people||"?"} pax · ${input.event_date||"Sem data"}` });
    return r;
  },
  getReservations: () => getStored("reservations"),
};

// ─── AUTH ────────────────────────────────────────────────────────────────────
const ADMIN_PIN = "creeks2026";
const adminSignIn = (pin) => { if (pin !== ADMIN_PIN) throw new Error("PIN inválido."); localStorage.setItem("creeks_admin_demo","true"); };
const adminSignOut = () => localStorage.removeItem("creeks_admin_demo");
const getAdminSession = () => localStorage.getItem("creeks_admin_demo") === "true";

// ─── CONFIG ──────────────────────────────────────────────────────────────────
const REVENUE_AVG = { reservations: 25, cake_orders: 65, catering_requests: 280 };

const CONFIGS = {
  reservations: {
    title: "Reservas de mesa", intro: "Pedidos pendentes até confirmação da equipa.",
    dateField: "reservation_date", icon: "calendar", color: "#3b82f6",
    statuses: [
      { value:"pending",label:"Pendente" },{ value:"confirmed",label:"Confirmada" },
      { value:"cancelled",label:"Cancelada" },{ value:"completed",label:"Concluída" },{ value:"no_show",label:"No-show" },
    ],
  },
  cake_orders: {
    title: "Pedidos de bolos", intro: "Orçamentos, datas, temas e imagens de referência.",
    dateField: "event_date", icon: "cake", color: "#ec4899",
    statuses: [
      { value:"new",label:"Novo" },{ value:"quoted",label:"Orçamentado" },{ value:"confirmed",label:"Confirmado" },
      { value:"in_production",label:"Em produção" },{ value:"ready",label:"Pronto" },
      { value:"delivered",label:"Entregue" },{ value:"cancelled",label:"Cancelado" },
    ],
  },
  catering_requests: {
    title: "Pedidos de catering", intro: "Eventos, quantidades e tipo de pedido.",
    dateField: "event_date", icon: "catering", color: "#8b5cf6",
    statuses: [
      { value:"new",label:"Novo" },{ value:"reviewing",label:"Em análise" },{ value:"quoted",label:"Orçamentado" },
      { value:"confirmed",label:"Confirmado" },{ value:"completed",label:"Concluído" },{ value:"cancelled",label:"Cancelado" },
    ],
  },
};

const STATUS_COLORS = {
  pending:"#f59e0b",new:"#f59e0b",confirmed:"#10b981",quoted:"#3b82f6",in_production:"#8b5cf6",
  completed:"#10b981",delivered:"#10b981",cancelled:"#ef4444",no_show:"#ef4444",reviewing:"#6366f1",ready:"#06b6d4",
};

// ─── MENU DATA ───────────────────────────────────────────────────────────────
const MENU_LS_KEY = "creeks_menu_v1";
function loadMenu() { try { const s = localStorage.getItem(MENU_LS_KEY); if(s) return JSON.parse(s); } catch(e){} return MENU_SEED; }
function saveMenu(m) { try { localStorage.setItem(MENU_LS_KEY, JSON.stringify(m)); } catch(e){} }

const MENU_SEED = {
  brunch:{ label:"Brunch", icon:"coffee", items:[
    {id:1,name:"Beethoven",desc:"",price:0,available:true},{id:2,name:"Dama e Vagabundo",desc:"",price:0,available:true},
    {id:3,name:"101 Dálmatas",desc:"",price:0,available:true},{id:4,name:"Pluto",desc:"",price:0,available:true},
    {id:5,name:"Iogurte natural",desc:"",price:0,available:true},{id:6,name:"Molletes da manhã",desc:"",price:0,available:true},
  ]},
  hamburgers:{ label:"Hambúrgueres Gourmet", icon:"flame", items:[
    {id:10,name:"Rafeiro",desc:"",price:0,available:true},{id:11,name:"Boxer",desc:"",price:0,available:true},
    {id:12,name:"Dálmata",desc:"",price:0,available:true},{id:13,name:"Rottweiler",desc:"",price:0,available:true},
    {id:14,name:"Labrador",desc:"",price:0,available:true},{id:15,name:"Husky",desc:"",price:0,available:true},
    {id:16,name:"Serra da Estrela",desc:"",price:0,available:true},{id:17,name:"Cocker",desc:"",price:0,available:true},
    {id:18,name:"Pastor Belga",desc:"",price:0,available:true},{id:19,name:"Veggie I",desc:"",price:0,available:true},
    {id:20,name:"Veggie II",desc:"",price:0,available:true},{id:21,name:"Shar-Pei",desc:"",price:0,available:true},
    {id:22,name:"S. Bernardo",desc:"",price:0,available:true},
  ]},
  pizzas:{ label:"Pizzas na tábua", icon:"leaf", items:[
    {id:30,name:"Edição limitada de verão",desc:"",price:0,available:true},{id:31,name:"Edição limitada de inverno",desc:"",price:0,available:true},
    {id:32,name:"Bacon, azeitonas, tomate e mozarella",desc:"",price:0,available:true},
    {id:33,name:"Camarão, ananás, azeitonas, tomate e mozarella",desc:"",price:0,available:true},
    {id:34,name:"Queijo chèvre, doce de frutos vermelhos, rúcula e tomate",desc:"",price:0,available:true},
  ]},
  saladas:{ label:"Saladas", icon:"leaf", items:[
    {id:40,name:"Salada de Camarão",desc:"",price:0,available:true},{id:41,name:"Salada de Águas Frias",desc:"",price:0,available:true},
    {id:42,name:"Salada Muuu",desc:"",price:0,available:true},{id:43,name:"Grega",desc:"",price:0,available:true},
    {id:44,name:"Marselhesa",desc:"",price:0,available:true},{id:45,name:"Tenório",desc:"",price:0,available:true},
  ]},
  bowls:{ label:"Bowls", icon:"utensils", items:[
    {id:50,name:"Açaí bowl",desc:"",price:0,available:true},{id:51,name:"Poké de salmão",desc:"",price:0,available:true},
    {id:52,name:"Bowl de camarão e bulgur",desc:"",price:0,available:true},
    {id:53,name:"Bowl de camarão, arroz e legumes",desc:"",price:0,available:true},
    {id:54,name:"Bowl quente Creek's",desc:"",price:0,available:true},
  ]},
  tradicoes:{ label:"Tradições & pratos do dia", icon:"coffee", items:[
    {id:60,name:"Sopa do dia",desc:"",price:0,available:true},{id:61,name:"Prego de vitela no bolo do caco",desc:"",price:0,available:true},
    {id:62,name:"Strips de vitela",desc:"",price:0,available:true},{id:63,name:"Pastéis de massa muito tenra",desc:"",price:0,available:true},
    {id:64,name:"Pratos de bacalhau",desc:"",price:0,available:true},{id:65,name:"Sugestões de almoço",desc:"",price:0,available:true},
  ]},
  tartes:{ label:"Tartes e bolos", icon:"cookie", items:[
    {id:70,name:"Vedeta",desc:"",price:1.80,available:true},{id:71,name:"Brownie de chocolate",desc:"",price:2.80,available:true},
    {id:72,name:"Limão merengada",desc:"",price:0,available:true},{id:73,name:"Doce de leite e lima",desc:"",price:0,available:true},
    {id:74,name:"Noz e ovos moles",desc:"",price:0,available:true},{id:75,name:"Cheesecake brownie",desc:"",price:0,available:true},
    {id:76,name:"Pavlova XS",desc:"",price:0,available:true},{id:77,name:"Tarte de amêndoa",desc:"",price:0,available:true},
  ]},
  bebidas:{ label:"Café & bebidas", icon:"coffee", items:[
    {id:80,name:"Café",desc:"",price:0.90,available:true},{id:81,name:"Galão",desc:"",price:1.20,available:true},
    {id:82,name:"Cappuccino",desc:"",price:1.60,available:true},{id:83,name:"Sumo de laranja",desc:"",price:2.50,available:true},
    {id:84,name:"Limonada",desc:"",price:2.50,available:true},{id:85,name:"Bebidas frescas",desc:"",price:0,available:true},
  ]},
};

// ─── HELPERS ─────────────────────────────────────────────────────────────────
function fmtDate(iso) {
  if (!iso) return "—";
  return new Date(iso).toLocaleDateString("pt-PT",{day:"2-digit",month:"short",year:"numeric"});
}
function fmtCurrency(v) { return v.toLocaleString("pt-PT",{minimumFractionDigits:0,maximumFractionDigits:0}) + "€"; }
function timeAgo(iso) {
  if (!iso) return "";
  const diff = (Date.now() - new Date(iso).getTime()) / 1000;
  if (diff < 60) return "agora";
  if (diff < 3600) return Math.floor(diff/60) + " min atrás";
  if (diff < 86400) return Math.floor(diff/3600) + "h atrás";
  return Math.floor(diff/86400) + "d atrás";
}

// ─── STATUS BADGE ─────────────────────────────────────────────────────────────
const StatusBadge = ({ status, label }) => {
  const c = STATUS_COLORS[status] || "#94a3b8";
  return (
    <span style={{
      background: c+"18", color: c, border: `1px solid ${c}33`,
      padding: "4px 12px", borderRadius: 999, fontSize: "0.76rem", fontWeight: 800,
      letterSpacing: "0.04em", whiteSpace: "nowrap",
    }}>{label}</span>
  );
};

// ─── SVG DONUT CHART ─────────────────────────────────────────────────────────
const DonutChart = ({ segments, size = 160, thickness = 32 }) => {
  const r = (size - thickness) / 2;
  const cx = size / 2, cy = size / 2;
  const circ = 2 * Math.PI * r;
  const total = segments.reduce((s, seg) => s + seg.value, 0) || 1;
  let offset = 0;
  return (
    <svg width={size} height={size} style={{ transform: "rotate(-90deg)" }}>
      {segments.map((seg, i) => {
        const len = (seg.value / total) * circ;
        const dash = `${len - 3} ${circ - len + 3}`;
        const el = (
          <circle key={i} cx={cx} cy={cy} r={r}
            fill="none" stroke={seg.color} strokeWidth={thickness}
            strokeDasharray={dash} strokeDashoffset={-offset}
            strokeLinecap="round"
            style={{ transition: "stroke-dasharray 0.6s ease" }}
          />
        );
        offset += len;
        return el;
      })}
      <circle cx={cx} cy={cy} r={r} fill="none" stroke="#0e3a4a0a" strokeWidth={thickness} />
    </svg>
  );
};

// ─── SVG BAR CHART ───────────────────────────────────────────────────────────
const MiniBarChart = ({ data, color = "#d7b85a", height = 80 }) => {
  if (!data.length) return null;
  const max = Math.max(...data.map(d => d.value), 1);
  const w = 100 / data.length;
  return (
    <svg width="100%" height={height} style={{ overflow: "visible" }}>
      {data.map((d, i) => {
        const barH = Math.max((d.value / max) * (height - 20), d.value > 0 ? 4 : 0);
        const x = i * w + w * 0.15;
        const barW = w * 0.7;
        return (
          <g key={i}>
            <rect x={`${x}%`} y={height - 20 - barH} width={`${barW}%`} height={barH}
              rx={3} fill={color} opacity="0.85" />
            <text x={`${x + barW/2}%`} y={height - 4} textAnchor="middle"
              fontSize="9" fill="#6d7475" fontFamily="Nunito Sans, sans-serif" fontWeight="700">
              {d.label}
            </text>
          </g>
        );
      })}
    </svg>
  );
};

// ─── NOTIFICATION BELL ───────────────────────────────────────────────────────
const NOTIF_ICONS = { reservation:"📅", cake:"🎂", catering:"🍽️" };

const NotificationBell = () => {
  const [open, setOpen] = React.useState(false);
  const [notifs, setNotifs] = React.useState(getNotifsRaw);
  const unread = notifs.filter(n=>!n.read).length;

  const toggle = () => {
    const next = !open;
    setOpen(next);
    if (next) { markAllRead(); setNotifs(getNotifsRaw()); }
  };

  React.useEffect(() => {
    if (!open) return;
    const close = (e) => { if (!e.target.closest(".notif-panel")) setOpen(false); };
    document.addEventListener("mousedown", close);
    return () => document.removeEventListener("mousedown", close);
  }, [open]);

  return (
    <div style={{ position:"relative" }} className="notif-panel">
      <button onClick={toggle} style={{
        width:38, height:38, borderRadius:10, border:"1px solid #fffdf520",
        background: open ? "#fffdf514" : "transparent",
        cursor:"pointer", display:"grid", placeItems:"center",
        position:"relative", color:"var(--warm-white)", fontSize:"1.1rem",
        transition:"background 0.15s",
      }}>
        🔔
        {unread > 0 && (
          <span style={{
            position:"absolute", top:4, right:4, width:16, height:16, borderRadius:"50%",
            background:"var(--coral)", color:"#fff", fontSize:"0.62rem", fontWeight:900,
            display:"grid", placeItems:"center", border:"2px solid #082a38",
          }}>{unread > 9 ? "9+" : unread}</span>
        )}
      </button>

      {open && (
        <div style={{
          position:"absolute", top:"calc(100% + 10px)", right:0,
          width:320, background:"#fff", borderRadius:16, zIndex:100,
          boxShadow:"0 20px 60px #082a3844", border:"1px solid #0e3a4a14",
          overflow:"hidden",
        }}>
          <div style={{ padding:"14px 18px", borderBottom:"1px solid #0e3a4a0e", display:"flex", justifyContent:"space-between", alignItems:"center", background:"var(--warm-white)" }}>
            <div>
              <strong style={{ fontSize:"0.92rem", color:"var(--navy-deep)" }}>Notificações</strong>
              {unread > 0 && <span style={{ marginLeft:8, background:"var(--coral)", color:"#fff", borderRadius:999, padding:"1px 7px", fontSize:"0.72rem", fontWeight:900 }}>{unread}</span>}
            </div>
            <button onClick={()=>{ markAllRead(); setNotifs(getNotifsRaw()); }} style={{ fontSize:"0.76rem", color:"var(--muted)", fontWeight:700, background:"transparent", border:0, cursor:"pointer" }}>
              Marcar lidas
            </button>
          </div>
          <div style={{ maxHeight:380, overflowY:"auto" }}>
            {notifs.length === 0 ? (
              <div style={{ padding:"36px 16px", textAlign:"center", color:"var(--muted)" }}>
                <p style={{ fontSize:"2rem", marginBottom:8 }}>🔔</p>
                <p style={{ fontSize:"0.86rem" }}>Sem notificações ainda</p>
                <p style={{ fontSize:"0.78rem", marginTop:4, opacity:0.7 }}>Os pedidos do site aparecem aqui</p>
              </div>
            ) : notifs.slice(0,20).map(n=>(
              <div key={n.id} style={{
                padding:"12px 16px", borderBottom:"1px solid #0e3a4a06",
                background: n.read ? "transparent" : "#3b82f608",
                display:"flex", gap:12, alignItems:"flex-start",
              }}>
                <span style={{ fontSize:"1.3rem", flexShrink:0, lineHeight:1.2 }}>{NOTIF_ICONS[n.type]||"📌"}</span>
                <div style={{ flex:1, minWidth:0 }}>
                  <div style={{ fontSize:"0.86rem", fontWeight:800, color:"var(--navy-deep)", marginBottom:2 }}>{n.title}</div>
                  <div style={{ fontSize:"0.78rem", color:"var(--muted)" }}>{n.body}</div>
                  <div style={{ fontSize:"0.71rem", color:"var(--muted)", marginTop:4, opacity:0.65 }}>{timeAgo(n.created_at)}</div>
                </div>
                {!n.read && <span style={{ width:8, height:8, borderRadius:"50%", background:"#3b82f6", flexShrink:0, marginTop:5 }}/>}
              </div>
            ))}
          </div>
          {notifs.length > 0 && (
            <div style={{ padding:"10px 16px", borderTop:"1px solid #0e3a4a0a", textAlign:"center" }}>
              <button onClick={()=>{ localStorage.removeItem(NOTIF_KEY); setNotifs([]); }} style={{ fontSize:"0.76rem", color:"var(--muted)", background:"transparent", border:0, cursor:"pointer", fontWeight:700 }}>
                Limpar todas
              </button>
            </div>
          )}
        </div>
      )}
    </div>
  );
};

// ─── ADMIN LOGIN ─────────────────────────────────────────────────────────────
const AdminLogin = ({ onLogin }) => {
  const [pin, setPin] = React.useState("");
  const [error, setError] = React.useState("");
  const [loading, setLoading] = React.useState(false);
  const submit = (e) => {
    e.preventDefault(); setError(""); setLoading(true);
    try { adminSignIn(pin); onLogin(); }
    catch(err) { setError(err.message); }
    finally { setLoading(false); }
  };
  return (
    <div style={{
      minHeight:"100svh", display:"grid", placeItems:"center",
      background:"radial-gradient(circle at 30% 20%, #d7b85a18, transparent 40%), linear-gradient(135deg, #082a38, #0e3a4a)",
    }}>
      <form onSubmit={submit} style={{
        background:"var(--warm-white)", borderRadius:20, padding:"48px 44px",
        width:"min(400px,100% - 40px)", display:"grid", gap:22,
        boxShadow:"0 40px 100px #082a3866, 0 0 0 1px #d7b85a22",
      }}>
        <div style={{ textAlign:"center" }}>
          <div style={{ position:"relative", display:"inline-block", marginBottom:18 }}>
            <img src="assets/creeks-logo.jpg" alt="Creek's" style={{
              width:80, height:80, borderRadius:"50%", objectFit:"cover",
              border:"3px solid var(--gold)", boxShadow:"0 8px 24px #082a3830",
            }}/>
            <span style={{
              position:"absolute", bottom:0, right:0, width:26, height:26,
              background:"var(--green)", borderRadius:"50%", border:"3px solid var(--warm-white)",
              display:"grid", placeItems:"center", fontSize:12,
            }}>🔐</span>
          </div>
          <p className="eyebrow" style={{ color:"var(--gold-deep)", marginBottom:6 }}>Painel interno</p>
          <h2 style={{ fontSize:"1.8rem" }}>Creek's Admin</h2>
          <p style={{ color:"var(--muted)", fontSize:"0.9rem", marginTop:8 }}>Acesso privado · Modo local</p>
        </div>
        <label className="field">
          <span>PIN de acesso</span>
          <input required type="password" value={pin} onChange={e=>setPin(e.target.value)} placeholder="••••••••••" autoFocus
            style={{ letterSpacing:"0.3em", fontSize:"1.1rem" }} />
        </label>
        {error && <p style={{ color:"var(--coral)", fontWeight:700, fontSize:"0.88rem", margin:0, textAlign:"center" }}>{error}</p>}
        <button className="btn primary full lg" disabled={loading} type="submit">
          {loading ? "A entrar…" : "Entrar no painel"}
        </button>
        <p style={{ color:"var(--muted)", fontSize:"0.78rem", textAlign:"center", margin:0 }}>PIN: creeks2026</p>
      </form>
    </div>
  );
};

// ─── SIDEBAR ─────────────────────────────────────────────────────────────────
const AdminSidebar = ({ section, setSection, onLogout }) => {
  const res = getStored("reservations");
  const cakes = getStored("cake_orders");
  const catering = getStored("catering_requests");
  const badges = {
    reservations: res.filter(r=>r.status==="pending").length,
    cake_orders: cakes.filter(r=>r.status==="new").length,
    catering_requests: catering.filter(r=>r.status==="new").length,
  };
  const navItems = [
    { id:"dashboard", label:"Dashboard", icon:"dashboard" },
    { id:"reservations", label:"Reservas", icon:"calendar", badge:badges.reservations },
    { id:"cake_orders", label:"Bolos", icon:"cake", badge:badges.cake_orders },
    { id:"catering_requests", label:"Catering", icon:"catering", badge:badges.catering_requests },
    { id:"menu", label:"Menu & Stock", icon:"menu" },
  ];
  return (
    <aside className="admin-sidebar" style={{ display:"flex", flexDirection:"column", height:"100svh", position:"sticky", top:0, overflowY:"auto" }}>
      <div style={{ padding:"20px 16px 18px", borderBottom:"1px solid #fffdf514" }}>
        <div style={{ display:"flex", alignItems:"center", gap:10 }}>
          <img src="assets/creeks-logo.jpg" alt="Creek's" style={{ width:42, height:42, borderRadius:"50%", border:"2px solid var(--gold)", objectFit:"cover", flexShrink:0 }} />
          <div style={{ flex:1, minWidth:0 }}>
            <strong style={{ color:"var(--warm-white)", fontSize:"0.96rem", display:"block" }}>Creek's Admin</strong>
            <span style={{ color:"var(--gold)", fontSize:"0.7rem", fontWeight:800, textTransform:"uppercase", letterSpacing:"0.08em" }}>Modo local</span>
          </div>
          <NotificationBell />
        </div>
      </div>
      <nav style={{ flex:1, padding:"12px 10px", display:"grid", gap:2, alignContent:"start" }}>
        {navItems.map(n => (
          <button key={n.id} className={section===n.id?"active":""} onClick={()=>setSection(n.id)}
            style={{ display:"flex", alignItems:"center", gap:10, padding:"11px 14px", borderRadius:10, width:"100%",
              background:section===n.id?"linear-gradient(90deg,#d7b85a20,#d7b85a08)":"transparent",
              border:section===n.id?"1px solid #d7b85a22":"1px solid transparent",
              color:section===n.id?"var(--warm-white)":"#fffdf5aa",
              fontWeight:section===n.id?800:600, fontSize:"0.92rem", cursor:"pointer", transition:"all 0.15s", textAlign:"left",
            }}>
            <Icon name={n.icon} size={17} />
            <span style={{ flex:1 }}>{n.label}</span>
            {n.badge > 0 && (
              <span style={{ background:"var(--coral)", color:"#fff", borderRadius:999, padding:"1px 7px", fontSize:"0.72rem", fontWeight:900 }}>{n.badge}</span>
            )}
          </button>
        ))}
      </nav>
      <div style={{ padding:"12px 10px 20px", borderTop:"1px solid #fffdf510" }}>
        <button className="btn outline-light sm" style={{ width:"100%" }} onClick={onLogout}>
          <Icon name="logout" size={14} /> Sair do painel
        </button>
      </div>
    </aside>
  );
};

// ─── DASHBOARD OVERVIEW ───────────────────────────────────────────────────────
const DashboardOverview = ({ setSection }) => {
  const res   = getStored("reservations");
  const cakes = getStored("cake_orders");
  const catering = getStored("catering_requests");

  const active = (rows) => rows.filter(r => r.status !== "cancelled" && r.status !== "no_show");
  const revRes  = active(res).length   * REVENUE_AVG.reservations;
  const revCake = active(cakes).length * REVENUE_AVG.cake_orders;
  const revCat  = active(catering).length * REVENUE_AVG.catering_requests;
  const revTotal = revRes + revCake + revCat;

  const pct = (v) => revTotal > 0 ? Math.round(v / revTotal * 100) : 0;

  const donutSegs = [
    { color:"#3b82f6", value:revRes,  label:"Reservas" },
    { color:"#ec4899", value:revCake, label:"Bolos" },
    { color:"#8b5cf6", value:revCat,  label:"Catering" },
  ];

  // Last 7 days bar chart
  const last7 = Array.from({length:7},(_,i)=>{
    const d = new Date(); d.setDate(d.getDate()-6+i);
    const key = d.toISOString().slice(0,10);
    const label = ["Dom","Seg","Ter","Qua","Qui","Sex","Sáb"][d.getDay()];
    const value = [...res,...cakes,...catering].filter(r=>r.created_at?.slice(0,10)===key).length;
    return { label, value, key };
  });

  const statCards = [
    { label:"Novos pedidos",   value: res.filter(r=>r.status==="pending").length + cakes.filter(r=>r.status==="new").length + catering.filter(r=>r.status==="new").length,
      sub:"aguardam resposta", color:"#f59e0b", icon:"bell", section:null },
    { label:"Reservas totais", value:res.length, sub:`${res.filter(r=>r.status==="pending").length} pendentes`, color:"#3b82f6", icon:"calendar", section:"reservations" },
    { label:"Bolos",           value:cakes.length, sub:`${cakes.filter(r=>r.status==="new").length} novos`, color:"#ec4899", icon:"cake", section:"cake_orders" },
    { label:"Catering",        value:catering.length, sub:`${catering.filter(r=>r.status==="new").length} novos`, color:"#8b5cf6", icon:"catering", section:"catering_requests" },
  ];

  const recent = [
    ...res.map(r=>({...r,_type:"Reserva",_conf:"reservations"})),
    ...cakes.map(r=>({...r,_type:"Bolo",_conf:"cake_orders"})),
    ...catering.map(r=>({...r,_type:"Catering",_conf:"catering_requests"})),
  ].sort((a,b)=>new Date(b.created_at)-new Date(a.created_at)).slice(0,6);

  return (
    <div style={{ padding:"0 0 40px" }}>
      {/* TOP BAR */}
      <div style={{ padding:"28px 32px 24px", borderBottom:"1px solid #0e3a4a0c", display:"flex", alignItems:"flex-end", justifyContent:"space-between" }}>
        <div>
          <p className="eyebrow">Painel interno</p>
          <h1 style={{ fontSize:"2rem", marginTop:4 }}>Dashboard</h1>
        </div>
        <span style={{ color:"var(--muted)", fontSize:"0.86rem", fontWeight:700 }}>
          {new Date().toLocaleDateString("pt-PT",{weekday:"long",day:"numeric",month:"long"})}
        </span>
      </div>

      <div style={{ padding:"24px 32px", display:"grid", gap:24 }}>

        {/* STAT CARDS */}
        <div style={{ display:"grid", gridTemplateColumns:"repeat(auto-fit,minmax(180px,1fr))", gap:14 }}>
          {statCards.map(s => (
            <div key={s.label}
              onClick={()=>s.section&&setSection(s.section)}
              style={{
                background:"var(--warm-white)", border:"1.5px solid #0e3a4a0e",
                borderRadius:16, padding:"20px 22px", cursor:s.section?"pointer":"default",
                boxShadow:"0 2px 12px #082a380a", transition:"all 0.2s",
                position:"relative", overflow:"hidden",
              }}
              onMouseOver={e=>{if(s.section){e.currentTarget.style.transform="translateY(-3px)";e.currentTarget.style.boxShadow="0 12px 32px #082a3818";}}}
              onMouseOut={e=>{e.currentTarget.style.transform="";e.currentTarget.style.boxShadow="0 2px 12px #082a380a";}}>
              <div style={{ position:"absolute", top:0, right:0, width:80, height:80, borderRadius:"0 16px 0 80px", background:s.color+"0c" }} />
              <div style={{ display:"flex", alignItems:"center", gap:8, marginBottom:14 }}>
                <span style={{ width:34, height:34, borderRadius:10, background:s.color+"18", display:"grid", placeItems:"center" }}>
                  <Icon name={s.icon} size={16} style={{ color:s.color }} />
                </span>
                <span style={{ fontSize:"0.74rem", fontWeight:800, color:"var(--muted)", textTransform:"uppercase", letterSpacing:"0.07em" }}>{s.label}</span>
              </div>
              <div style={{ fontSize:"2.4rem", fontWeight:900, color:"var(--navy-deep)", lineHeight:1, letterSpacing:"-0.02em" }}>{s.value}</div>
              <div style={{ fontSize:"0.78rem", color:"var(--muted)", marginTop:5 }}>{s.sub}</div>
            </div>
          ))}
        </div>

        {/* CHARTS ROW */}
        <div style={{ display:"grid", gridTemplateColumns:"1fr 1.4fr", gap:16 }}>

          {/* REVENUE DONUT */}
          <div style={{ background:"var(--warm-white)", border:"1.5px solid #0e3a4a0e", borderRadius:16, padding:"22px 24px", boxShadow:"0 2px 12px #082a380a" }}>
            <p className="eyebrow" style={{ marginBottom:4 }}>Revenue estimado</p>
            <h2 style={{ fontSize:"1.5rem", marginBottom:20 }}>{fmtCurrency(revTotal)}</h2>
            <div style={{ display:"flex", alignItems:"center", gap:24 }}>
              <div style={{ position:"relative", flexShrink:0 }}>
                <DonutChart segments={donutSegs} size={140} thickness={28} />
                <div style={{
                  position:"absolute", inset:0, display:"grid", placeItems:"center",
                  pointerEvents:"none",
                }}>
                  <div style={{ textAlign:"center" }}>
                    <div style={{ fontSize:"0.68rem", fontWeight:800, color:"var(--muted)", textTransform:"uppercase", letterSpacing:"0.06em" }}>Total</div>
                    <div style={{ fontSize:"1.1rem", fontWeight:900, color:"var(--navy-deep)" }}>{fmtCurrency(revTotal)}</div>
                  </div>
                </div>
              </div>
              <div style={{ display:"grid", gap:10, flex:1 }}>
                {donutSegs.map((s, i) => (
                  <div key={s.label} style={{ display:"flex", alignItems:"center", gap:10 }}>
                    <span style={{ width:10, height:10, borderRadius:3, background:s.color, flexShrink:0 }} />
                    <span style={{ flex:1, fontSize:"0.88rem", fontWeight:700, color:"var(--navy-deep)" }}>{s.label}</span>
                    <span style={{ fontSize:"0.88rem", fontWeight:800, color:s.color }}>{pct(s.value)}%</span>
                    <span style={{ fontSize:"0.82rem", color:"var(--muted)", minWidth:52, textAlign:"right" }}>{fmtCurrency(s.value)}</span>
                  </div>
                ))}
                <p style={{ fontSize:"0.72rem", color:"var(--muted)", marginTop:4, borderTop:"1px dashed #0e3a4a14", paddingTop:8 }}>
                  Estimativa: reservas ×{REVENUE_AVG.reservations}€ · bolos ×{REVENUE_AVG.cake_orders}€ · catering ×{REVENUE_AVG.catering_requests}€
                </p>
              </div>
            </div>
          </div>

          {/* BAR CHART — last 7 days */}
          <div style={{ background:"var(--warm-white)", border:"1.5px solid #0e3a4a0e", borderRadius:16, padding:"22px 24px", boxShadow:"0 2px 12px #082a380a" }}>
            <div style={{ display:"flex", justifyContent:"space-between", alignItems:"flex-start", marginBottom:20 }}>
              <div>
                <p className="eyebrow" style={{ marginBottom:4 }}>Pedidos recebidos</p>
                <h3 style={{ fontSize:"1.2rem" }}>Últimos 7 dias</h3>
              </div>
              <span style={{ background:"var(--cream)", border:"1px solid var(--line)", borderRadius:8, padding:"4px 12px", fontSize:"0.78rem", fontWeight:800, color:"var(--navy)" }}>
                {last7.reduce((s,d)=>s+d.value,0)} total
              </span>
            </div>
            <MiniBarChart data={last7} color="#d7b85a" height={100} />

            {/* Breakdown by type this week */}
            <div style={{ display:"flex", gap:16, marginTop:16, paddingTop:16, borderTop:"1px dashed #0e3a4a10" }}>
              {[
                {label:"Reservas",value:res.filter(r=>r.created_at?.slice(0,10)>=last7[0].key).length,color:"#3b82f6"},
                {label:"Bolos",value:cakes.filter(r=>r.created_at?.slice(0,10)>=last7[0].key).length,color:"#ec4899"},
                {label:"Catering",value:catering.filter(r=>r.created_at?.slice(0,10)>=last7[0].key).length,color:"#8b5cf6"},
              ].map(t => (
                <div key={t.label} style={{ display:"flex", alignItems:"center", gap:6, fontSize:"0.82rem" }}>
                  <span style={{ width:8, height:8, borderRadius:2, background:t.color }} />
                  <span style={{ color:"var(--muted)" }}>{t.label}</span>
                  <strong style={{ color:"var(--navy-deep)" }}>{t.value}</strong>
                </div>
              ))}
            </div>
          </div>
        </div>

        {/* PIPELINE + UPCOMING ROW */}
        <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:16 }}>

          {/* PIPELINE HEALTH */}
          <div style={{ background:"var(--warm-white)", border:"1.5px solid #0e3a4a0e", borderRadius:16, padding:"22px 24px", boxShadow:"0 2px 12px #082a380a" }}>
            <p className="eyebrow" style={{ marginBottom:4 }}>Pipeline</p>
            <h3 style={{ fontSize:"1.2rem", marginBottom:20 }}>Estado dos pedidos</h3>
            <div style={{ display:"grid", gap:16 }}>
              {[
                { label:"Reservas", total:res.length, pending:res.filter(r=>r.status==="pending").length, confirmed:res.filter(r=>r.status==="confirmed").length, cancelled:res.filter(r=>r.status==="cancelled").length, color:"#3b82f6" },
                { label:"Bolos", total:cakes.length, pending:cakes.filter(r=>r.status==="new").length, confirmed:cakes.filter(r=>["confirmed","in_production","ready"].includes(r.status)).length, cancelled:cakes.filter(r=>r.status==="cancelled").length, color:"#ec4899" },
                { label:"Catering", total:catering.length, pending:catering.filter(r=>["new","reviewing"].includes(r.status)).length, confirmed:catering.filter(r=>["confirmed","completed"].includes(r.status)).length, cancelled:catering.filter(r=>r.status==="cancelled").length, color:"#8b5cf6" },
              ].map(p => {
                const t = p.total || 1;
                return (
                  <div key={p.label}>
                    <div style={{ display:"flex", justifyContent:"space-between", marginBottom:6 }}>
                      <span style={{ fontSize:"0.86rem", fontWeight:800, color:"var(--navy-deep)" }}>{p.label}</span>
                      <span style={{ fontSize:"0.78rem", color:"var(--muted)" }}>{p.total} total</span>
                    </div>
                    <div style={{ height:8, borderRadius:999, background:"#0e3a4a08", overflow:"hidden", display:"flex", gap:1 }}>
                      <div style={{ width:`${p.pending/t*100}%`, background:"#f59e0b", borderRadius:999, transition:"width 0.6s ease" }}/>
                      <div style={{ width:`${p.confirmed/t*100}%`, background:"#10b981", borderRadius:999, transition:"width 0.6s ease" }}/>
                      <div style={{ width:`${p.cancelled/t*100}%`, background:"#ef444466", borderRadius:999, transition:"width 0.6s ease" }}/>
                    </div>
                    <div style={{ display:"flex", gap:14, marginTop:6 }}>
                      {[{label:"Pendente",v:p.pending,c:"#f59e0b"},{label:"Confirmado",v:p.confirmed,c:"#10b981"},{label:"Cancelado",v:p.cancelled,c:"#ef4444"}].map(s=>(
                        <span key={s.label} style={{ display:"flex", alignItems:"center", gap:4, fontSize:"0.74rem", color:"var(--muted)" }}>
                          <span style={{ width:7, height:7, borderRadius:2, background:s.c }}/>
                          {s.label} <strong style={{ color:"var(--navy-deep)" }}>{s.v}</strong>
                        </span>
                      ))}
                    </div>
                  </div>
                );
              })}
            </div>
          </div>

          {/* UPCOMING RESERVATIONS */}
          <div style={{ background:"var(--warm-white)", border:"1.5px solid #0e3a4a0e", borderRadius:16, padding:"22px 24px", boxShadow:"0 2px 12px #082a380a" }}>
            <p className="eyebrow" style={{ marginBottom:4 }}>Próximas reservas</p>
            <h3 style={{ fontSize:"1.2rem", marginBottom:20 }}>Confirmadas e pendentes</h3>
            {(() => {
              const today = new Date().toISOString().slice(0,10);
              const upcoming = res
                .filter(r => r.reservation_date >= today && r.status !== "cancelled" && r.status !== "no_show")
                .sort((a,b) => (a.reservation_date||"").localeCompare(b.reservation_date||"") || (a.reservation_time||"").localeCompare(b.reservation_time||""))
                .slice(0,5);
              if (upcoming.length === 0) return (
                <div style={{ textAlign:"center", padding:"24px 0", color:"var(--muted)" }}>
                  <p style={{ fontSize:"1.8rem" }}>📅</p>
                  <p style={{ fontSize:"0.86rem", marginTop:8 }}>Sem reservas futuras</p>
                </div>
              );
              return (
                <div style={{ display:"grid", gap:10 }}>
                  {upcoming.map(r => {
                    const isToday = r.reservation_date === today;
                    const statusLabel = CONFIGS.reservations.statuses.find(s=>s.value===r.status)?.label ?? r.status;
                    return (
                      <div key={r.id} style={{
                        display:"grid", gridTemplateColumns:"48px 1fr auto",
                        gap:12, alignItems:"center", padding:"10px 14px",
                        background: isToday ? "#3b82f60c" : "var(--cream)",
                        borderRadius:12, border:`1px solid ${isToday ? "#3b82f620" : "#0e3a4a0a"}`,
                      }}>
                        <div style={{ textAlign:"center" }}>
                          <div style={{ fontSize:"1.1rem", fontWeight:900, color: isToday ? "#3b82f6" : "var(--navy-deep)", lineHeight:1 }}>
                            {r.reservation_date?.slice(8)}
                          </div>
                          <div style={{ fontSize:"0.66rem", fontWeight:800, color:"var(--muted)", textTransform:"uppercase", letterSpacing:"0.06em" }}>
                            {r.reservation_date ? new Date(r.reservation_date+"T12:00:00").toLocaleDateString("pt-PT",{month:"short"}) : "—"}
                          </div>
                        </div>
                        <div>
                          <div style={{ fontWeight:800, fontSize:"0.9rem", color:"var(--navy-deep)" }}>{r.name??""}</div>
                          <div style={{ fontSize:"0.76rem", color:"var(--muted)", marginTop:2 }}>
                            {r.reservation_time||"--:--"} · {r.guests??"?"} pessoa(s) · {r.area||"indiferente"}
                          </div>
                        </div>
                        <StatusBadge status={r.status} label={statusLabel} />
                      </div>
                    );
                  })}
                </div>
              );
            })()}
          </div>
        </div>

        {/* RECENT RECORDS */}
        <div style={{ background:"var(--warm-white)", border:"1.5px solid #0e3a4a0e", borderRadius:16, padding:"22px 24px", boxShadow:"0 2px 12px #082a380a" }}>
          <div style={{ display:"flex", justifyContent:"space-between", alignItems:"center", marginBottom:20 }}>
            <div>
              <p className="eyebrow" style={{ marginBottom:4 }}>Actividade recente</p>
              <h3 style={{ fontSize:"1.2rem" }}>Últimos pedidos</h3>
            </div>
          </div>
          {recent.length === 0 ? (
            <div style={{ textAlign:"center", padding:"40px 0", color:"var(--muted)" }}>
              <p style={{ fontSize:"2rem", marginBottom:8 }}>📭</p>
              <p>Sem pedidos ainda. Os pedidos do site aparecem aqui.</p>
            </div>
          ) : (
            <div style={{ display:"grid", gap:0 }}>
              {recent.map((r,i) => {
                const conf = CONFIGS[r._conf];
                const statusLabel = conf?.statuses.find(s=>s.value===r.status)?.label ?? r.status;
                const colors = {Reserva:"#3b82f6",Bolo:"#ec4899",Catering:"#8b5cf6"};
                return (
                  <div key={r.id} style={{
                    display:"grid", gridTemplateColumns:"44px 1fr auto auto",
                    gap:14, padding:"14px 0", alignItems:"center",
                    borderBottom: i < recent.length-1 ? "1px solid #0e3a4a08" : "none",
                  }}>
                    <span style={{ width:44, height:44, borderRadius:12, background:(colors[r._type]||"#94a3b8")+"18", display:"grid", placeItems:"center", flexShrink:0 }}>
                      <Icon name={r._type==="Reserva"?"calendar":r._type==="Bolo"?"cake":"catering"} size={18} style={{ color:colors[r._type] }} />
                    </span>
                    <div>
                      <strong style={{ color:"var(--navy-deep)", fontSize:"0.96rem" }}>{String(r.name??"—")}</strong>
                      <div style={{ display:"flex", gap:8, marginTop:3, alignItems:"center" }}>
                        <span style={{ fontSize:"0.76rem", color:"var(--muted)" }}>{r._type}</span>
                        <span style={{ width:3, height:3, borderRadius:"50%", background:"var(--muted)", opacity:0.5 }} />
                        <span style={{ fontSize:"0.76rem", color:"var(--muted)" }}>{timeAgo(r.created_at)}</span>
                      </div>
                    </div>
                    <StatusBadge status={r.status} label={statusLabel} />
                  </div>
                );
              })}
            </div>
          )}
        </div>

      </div>
    </div>
  );
};

// ─── MODULE VIEW ─────────────────────────────────────────────────────────────
const AdminModuleView = ({ module }) => {
  const config = CONFIGS[module];
  const [records, setRecords] = React.useState(()=>getStored(module));
  const [statusFilter, setStatusFilter] = React.useState("all");
  const [dateFilter, setDateFilter] = React.useState("");
  const [budgetDraft, setBudgetDraft] = React.useState({});
  const [expanded, setExpanded] = React.useState(null);

  const load = () => setRecords(getStored(module));
  const updateStatus = (id, status) => { updateStored(module,id,{status}); load(); };
  const updateBudget = (id) => { updateStored(module,id,{estimated_budget:budgetDraft[id]??""}); load(); };

  const visible = records.filter(r =>
    (statusFilter==="all"||r.status===statusFilter) &&
    (!dateFilter||r[config.dateField]===dateFilter)
  );

  const waLink = (r) => {
    const raw = String(r.phone??"").replace(/\D/g,"");
    const phone = raw.startsWith("351")?raw:`351${raw}`;
    const msg = module==="reservations"
      ?`Olá ${r.name??""}, somos o Creek's Caffé. Recebemos o seu pedido de reserva e vamos confirmar disponibilidade.`
      :module==="cake_orders"
        ?`Olá ${r.name??""}, somos o Creek's Caffé. Recebemos o seu pedido de bolo personalizado e vamos enviar proposta.`
        :`Olá ${r.name??""}, somos o Creek's Caffé. Recebemos o seu pedido de catering e vamos analisar disponibilidade.`;
    return `https://wa.me/${phone}?text=${encodeURIComponent(msg)}`;
  };

  const mainLine = (r) => {
    if (module==="reservations") return `${r.reservation_date??"Sem data"} às ${r.reservation_time??"--:--"} · ${r.guests??"?"} pessoa(s)`;
    if (module==="cake_orders") return `${r.event_date??"Sem data"} · ${r.number_of_people??"?"} pax · ${r.cake_theme??"Sem tema"}`;
    return `${r.event_date??"Sem data"} · ${r.number_of_people??"?"} pax · ${r.event_type??"Evento"}`;
  };

  const newCount = records.filter(r=>r.status==="pending"||r.status==="new").length;

  return (
    <div style={{ padding:"0 0 40px" }}>
      <div style={{ padding:"28px 32px 24px", borderBottom:"1px solid #0e3a4a0c", display:"flex", alignItems:"flex-end", justifyContent:"space-between", gap:16 }}>
        <div>
          <p className="eyebrow">Painel interno</p>
          <h1 style={{ fontSize:"2rem", marginTop:4 }}>{config.title}</h1>
          <p style={{ color:"var(--muted)", marginTop:4 }}>{config.intro}</p>
        </div>
        <div style={{ display:"flex", gap:10, alignItems:"center", flexShrink:0 }}>
          {newCount > 0 && (
            <span style={{ background:"#f59e0b18", color:"#f59e0b", border:"1px solid #f59e0b30", padding:"6px 14px", borderRadius:999, fontSize:"0.82rem", fontWeight:800 }}>
              {newCount} novos
            </span>
          )}
          <button className="btn secondary sm" onClick={load}><Icon name="refresh" size={16}/> Atualizar</button>
        </div>
      </div>

      {/* FILTERS */}
      <div style={{ padding:"16px 32px", display:"flex", gap:12, flexWrap:"wrap", alignItems:"flex-end", borderBottom:"1px solid #0e3a4a08", background:"#fafaf800" }}>
        <label className="field" style={{ minWidth:150 }}>
          <span style={{ fontSize:"0.76rem" }}>Data</span>
          <input type="date" value={dateFilter} onChange={e=>setDateFilter(e.target.value)}
            style={{ padding:"8px 12px", borderRadius:8, border:"1.5px solid #0e3a4a18", fontSize:"0.88rem" }} />
        </label>
        <label className="field" style={{ minWidth:170 }}>
          <span style={{ fontSize:"0.76rem" }}>Estado</span>
          <select value={statusFilter} onChange={e=>setStatusFilter(e.target.value)}
            style={{ padding:"8px 12px", borderRadius:8, border:"1.5px solid #0e3a4a18", fontSize:"0.88rem", background:"var(--warm-white)" }}>
            <option value="all">Todos ({records.length})</option>
            {config.statuses.map(s=>(
              <option key={s.value} value={s.value}>{s.label} ({records.filter(r=>r.status===s.value).length})</option>
            ))}
          </select>
        </label>
        <span style={{ color:"var(--muted)", fontSize:"0.84rem", fontWeight:700, paddingBottom:10 }}>{visible.length} resultado(s)</span>
        {(statusFilter!=="all"||dateFilter) && (
          <button className="btn ghost sm" onClick={()=>{setStatusFilter("all");setDateFilter("");}}>Limpar filtros</button>
        )}
      </div>

      {/* RECORDS */}
      <div style={{ padding:"20px 32px", display:"grid", gap:12 }}>
        {visible.length === 0 && (
          <div style={{ textAlign:"center", padding:"60px 20px", color:"var(--muted)" }}>
            <p style={{ fontSize:"2.5rem", marginBottom:12 }}>📭</p>
            <h3>Sem pedidos nesta vista</h3>
            <p style={{ fontSize:"0.9rem", marginTop:6 }}>Tenta ajustar os filtros ou aguarda novos pedidos.</p>
          </div>
        )}
        {visible.map(r => {
          const statusLabel = config.statuses.find(s=>s.value===r.status)?.label??r.status;
          const isExpanded = expanded===r.id;
          return (
            <article key={r.id} style={{
              background:"var(--warm-white)", border:"1.5px solid #0e3a4a0e",
              borderRadius:16, overflow:"hidden", boxShadow:"0 2px 12px #082a380a",
              transition:"box-shadow 0.18s",
            }}>
              {/* HEADER ROW */}
              <div style={{
                display:"grid", gridTemplateColumns:"auto 1fr auto auto",
                gap:16, padding:"18px 22px", alignItems:"center", cursor:"pointer",
              }} onClick={()=>setExpanded(isExpanded?null:r.id)}>
                <span style={{
                  width:46, height:46, borderRadius:12,
                  background:(config.color||"#94a3b8")+"18",
                  display:"grid", placeItems:"center", flexShrink:0,
                }}>
                  <Icon name={config.icon} size={20} style={{ color:config.color }} />
                </span>
                <div>
                  <div style={{ display:"flex", alignItems:"center", gap:10, marginBottom:4 }}>
                    <strong style={{ fontSize:"1.05rem", color:"var(--navy-deep)" }}>{String(r.name??"Sem nome")}</strong>
                    <StatusBadge status={r.status} label={statusLabel} />
                  </div>
                  <p style={{ color:"var(--muted)", fontSize:"0.86rem" }}>{mainLine(r)}</p>
                  <p style={{ color:"var(--muted)", fontSize:"0.76rem", marginTop:3 }}>{fmtDate(r.created_at)} · {timeAgo(r.created_at)}</p>
                </div>
                <select value={r.status} onChange={e=>{e.stopPropagation();updateStatus(r.id,e.target.value);}}
                  onClick={e=>e.stopPropagation()}
                  style={{
                    padding:"8px 12px", borderRadius:10, border:`1.5px solid ${config.color}44`,
                    fontSize:"0.84rem", fontWeight:800, cursor:"pointer", background:"var(--cream)",
                    color:config.color,
                  }}>
                  {config.statuses.map(s=><option key={s.value} value={s.value}>{s.label}</option>)}
                </select>
                <span style={{ color:"var(--muted)", fontSize:"1.2rem", userSelect:"none" }}>{isExpanded?"▲":"▼"}</span>
              </div>

              {/* EXPANDED DETAILS */}
              {isExpanded && (
                <div style={{ borderTop:"1px solid #0e3a4a08", padding:"18px 22px", background:"#fafdf800" }}>
                  <div style={{ display:"grid", gridTemplateColumns:"repeat(auto-fill,minmax(200px,1fr))", gap:10, marginBottom:16 }}>
                    {[
                      ["Telefone", r.phone],
                      ["Email", r.email],
                      module==="reservations"&&["Mensagem",r.message],
                      module==="reservations"&&["Preferência",r.area],
                      module==="cake_orders"&&["Levantamento",r.pickup_date],
                      module==="cake_orders"&&["Sabor",r.cake_flavour],
                      module==="cake_orders"&&["Texto no bolo",r.cake_text],
                      module==="cake_orders"&&["Observações",r.message],
                      module==="catering_requests"&&["Tipo",r.request_type],
                      module==="catering_requests"&&["Observações",r.message],
                    ].filter(Boolean).map(([label,value])=>value&&(
                      <div key={label} style={{ background:"var(--cream)", borderRadius:10, padding:"10px 14px", border:"1px solid #0e3a4a0a" }}>
                        <span style={{ fontSize:"0.7rem", fontWeight:900, textTransform:"uppercase", letterSpacing:"0.08em", color:"var(--muted)", display:"block", marginBottom:3 }}>{label}</span>
                        <span style={{ fontSize:"0.9rem", color:"var(--navy-deep)", fontWeight:600 }}>{String(value)}</span>
                      </div>
                    ))}
                  </div>

                  {module==="cake_orders" && (
                    <div style={{ display:"flex", gap:10, marginBottom:14 }}>
                      <input value={budgetDraft[r.id]??(r.estimated_budget??"")}
                        onChange={e=>setBudgetDraft(d=>({...d,[r.id]:e.target.value}))}
                        placeholder="Orçamento estimado (ex: 45€)"
                        style={{ flex:1, padding:"10px 14px", border:"1.5px solid #0e3a4a18", borderRadius:10, fontSize:"0.9rem", background:"var(--warm-white)" }} />
                      <button className="btn secondary sm" onClick={()=>updateBudget(r.id)}>Guardar</button>
                    </div>
                  )}

                  <div style={{ display:"flex", gap:8, flexWrap:"wrap" }}>
                    <a className="btn ghost sm" href={waLink(r)} target="_blank" rel="noreferrer">
                      💬 WhatsApp
                    </a>
                    <a className="btn ghost sm" href={`tel:${String(r.phone??"").replace(/\s/g,"")}`}>
                      📞 Ligar
                    </a>
                    {module==="cake_orders"&&r.reference_image_url&&(
                      <a className="btn ghost sm" href={String(r.reference_image_url)} target="_blank" rel="noreferrer">
                        🖼 Ver imagem
                      </a>
                    )}
                  </div>
                </div>
              )}
            </article>
          );
        })}
      </div>
    </div>
  );
};

// ─── MENU EDITOR ─────────────────────────────────────────────────────────────
const MenuEditorView = () => {
  const [menu, setMenu] = React.useState(()=>loadMenu());
  const [activeCat, setActiveCat] = React.useState("brunch");
  const [saved, setSaved] = React.useState(false);
  const cat = menu[activeCat];

  const updateItem = (id,field,val) => setMenu(m=>({...m,[activeCat]:{...m[activeCat],items:m[activeCat].items.map(i=>i.id===id?{...i,[field]:val}:i)}}));
  const deleteItem = (id) => setMenu(m=>({...m,[activeCat]:{...m[activeCat],items:m[activeCat].items.filter(i=>i.id!==id)}}));
  const addItem = () => { const id=Date.now(); setMenu(m=>({...m,[activeCat]:{...m[activeCat],items:[...m[activeCat].items,{id,name:"Novo item",desc:"",price:0,available:true}]}})); };

  const total = Object.values(menu).reduce((s,c)=>s+c.items.length,0);
  const unavailable = Object.values(menu).flatMap(c=>c.items.filter(i=>!i.available)).length;

  return (
    <div style={{ padding:"0 0 40px" }}>
      <div style={{ padding:"28px 32px 24px", borderBottom:"1px solid #0e3a4a0c", display:"flex", alignItems:"flex-end", justifyContent:"space-between" }}>
        <div>
          <p className="eyebrow">Painel interno</p>
          <h1 style={{ fontSize:"2rem", marginTop:4 }}>Menu & Stock</h1>
          <p style={{ color:"var(--muted)", marginTop:4 }}>{total} itens · {unavailable} indisponíveis</p>
        </div>
        <button className="btn primary sm" onClick={()=>{saveMenu(menu);setSaved(true);setTimeout(()=>setSaved(false),2000);}}>
          <Icon name="check" size={14}/> {saved?"✓ Publicado!":"Publicar alterações"}
        </button>
      </div>
      <div style={{ padding:"24px 32px", display:"grid", gridTemplateColumns:"220px 1fr", gap:20 }}>
        <aside style={{ display:"grid", gap:4, alignContent:"start" }}>
          {Object.entries(menu).map(([id,c])=>(
            <button key={id} onClick={()=>setActiveCat(id)} style={{
              display:"flex", justifyContent:"space-between", alignItems:"center",
              padding:"10px 14px", borderRadius:10, border:"1.5px solid",
              background:activeCat===id?"var(--navy)":"var(--warm-white)",
              color:activeCat===id?"var(--warm-white)":"var(--navy-deep)",
              borderColor:activeCat===id?"var(--navy)":"#0e3a4a12",
              fontWeight:700, fontSize:"0.88rem", cursor:"pointer", transition:"all 0.15s",
            }}>
              <span>{c.label}</span>
              <span style={{ fontSize:"0.76rem", opacity:0.7, background:activeCat===id?"#ffffff22":"var(--cream)", borderRadius:999, padding:"2px 8px" }}>{c.items.length}</span>
            </button>
          ))}
        </aside>
        <div style={{ background:"var(--warm-white)", border:"1.5px solid #0e3a4a0e", borderRadius:16, padding:"22px 24px" }}>
          <div style={{ display:"flex", justifyContent:"space-between", alignItems:"center", marginBottom:18 }}>
            <h3>{cat.label}</h3>
            <button className="btn ghost sm" onClick={addItem}><Icon name="plus" size={14}/> Adicionar</button>
          </div>
          <div style={{ display:"grid", gap:8 }}>
            {cat.items.map(item=>(
              <div key={item.id} style={{
                display:"grid", gridTemplateColumns:"1fr 130px 90px auto auto",
                gap:8, alignItems:"center", padding:"10px 12px",
                background:item.available?"var(--cream)":"#ef444408",
                borderRadius:10, border:`1px solid ${item.available?"#0e3a4a0c":"#ef444420"}`,
              }}>
                <input value={item.name} onChange={e=>updateItem(item.id,"name",e.target.value)}
                  style={{ padding:"8px 10px", border:"1.5px solid #0e3a4a12", borderRadius:8, fontSize:"0.9rem", fontWeight:700, background:"var(--warm-white)" }}/>
                <div style={{ display:"flex", alignItems:"center", gap:4 }}>
                  <input type="number" min="0" step="0.1" value={item.price} onChange={e=>updateItem(item.id,"price",parseFloat(e.target.value)||0)}
                    style={{ width:"100%", padding:"8px 10px", border:"1.5px solid #0e3a4a12", borderRadius:8, fontSize:"0.9rem", background:"var(--warm-white)" }}/>
                  <span style={{ color:"var(--muted)", fontSize:"0.9rem" }}>€</span>
                </div>
                <span style={{ fontSize:"0.78rem", fontWeight:800, color:item.available?"var(--green)":"var(--coral)", textAlign:"center" }}>
                  {item.available?"✓ Ativo":"✗ Off"}
                </span>
                <button onClick={()=>updateItem(item.id,"available",!item.available)} style={{
                  padding:"6px 10px", borderRadius:8, border:"1.5px solid #0e3a4a14",
                  background:"transparent", cursor:"pointer", fontSize:"0.76rem", fontWeight:800, whiteSpace:"nowrap",
                }}>
                  {item.available?"Desativar":"Ativar"}
                </button>
                <button onClick={()=>deleteItem(item.id)} style={{
                  width:30, height:30, borderRadius:8, border:"1.5px solid #ef444430",
                  background:"transparent", cursor:"pointer", color:"var(--coral)", fontSize:"1rem",
                }}>✕</button>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
};

// ─── MAIN ────────────────────────────────────────────────────────────────────
const DashboardPage = ({ go }) => {
  const [auth, setAuth] = React.useState(null);
  const [section, setSection] = React.useState("dashboard");

  React.useEffect(()=>{ setAuth(getAdminSession()); },[]);

  if (auth===null) return (
    <div style={{ minHeight:"100svh", display:"grid", placeItems:"center" }}>
      <p style={{ color:"var(--muted)" }}>A carregar…</p>
    </div>
  );
  if (!auth) return <AdminLogin onLogin={()=>setAuth(true)} />;

  return (
    <div className="admin-shell">
      <AdminSidebar section={section} setSection={setSection} onLogout={()=>{ adminSignOut(); setAuth(false); }} />
      <main className="admin-main" style={{ overflowY:"auto", height:"100svh" }}>
        {section==="dashboard" && <DashboardOverview setSection={setSection} />}
        {["reservations","cake_orders","catering_requests"].includes(section) && <AdminModuleView module={section} key={section} />}
        {section==="menu" && <MenuEditorView />}
      </main>
    </div>
  );
};

window.DashboardPage = DashboardPage;
