/* === Mobile staff view === */

const MobileApp = ({ tasks, user, role, onUpdate, onCreate, compras, setCompras }) => {
  const [activeTaskId, setActiveTaskId] = React.useState(null);
  const [tab, setTab] = React.useState("hoy");
  const [view, setView] = React.useState("tareas"); // "tareas" | "huespedes" | "compras"
  const [activeGuestId, setActiveGuestId] = React.useState(null);
  const [guestsRev, setGuestsRev] = React.useState(0);

  React.useEffect(() => {
    const h = () => setGuestsRev(r => r + 1);
    window.addEventListener("guests-changed", h);
    return () => window.removeEventListener("guests-changed", h);
  }, []);

  const isJefe = role === "jefe";
  const userTitle = user.title || (role === "staff" ? "Staff" : "Jefe");

  const allGuests = window.__allGuests || (typeof HUESPEDES_INIT !== "undefined" ? HUESPEDES_INIT : []);

  // Build dynamic bottom nav based on user's permissions
  const sidebarAreas = SIDEBAR_BY_ROLE(role, user);
  const hasCompras = sidebarAreas.includes("compras");
  const hasYate = sidebarAreas.includes("yate");

  // Trust the tasks array passed by App — already scoped by role/permissions.
  const myTasks = tasks;
  const todayTasks = myTasks.filter(t => t.due === TODAY_ISO || t.status === "vencida" || t.status === "urgente" || t.status === "progreso");
  // Week range: Monday → Sunday containing TODAY
  const todayDate = TODAY;
  const dow = todayDate.getDay(); // 0=Sun 1=Mon ... 6=Sat
  const offsetToMonday = dow === 0 ? -6 : 1 - dow;
  const weekStart = addDays(todayDate, offsetToMonday);
  const weekEnd   = addDays(weekStart, 6);

  const weekTasks = myTasks.filter(t => {
    const d = parseISO(t.due);
    return d >= weekStart && d <= weekEnd;
  });

  const list = tab === "hoy" ? todayTasks : weekTasks;
  const active = activeTaskId ? myTasks.find(t => t.id === activeTaskId) : null;

  const toggleCheck = (cid) => {
    if (!active) return;
    onUpdate({
      ...active,
      checklist: (active.checklist || []).map(c => c.id === cid ? { ...c, done: !c.done } : c),
    });
  };

  // If active task disappeared (e.g. marked terminada and filtered out), close detail
  React.useEffect(() => {
    if (activeTaskId && !active) setActiveTaskId(null);
  }, [activeTaskId, active]);

  return (
    <div className="cdc-phone__screen">
      {view === "compras" ? (
        <MobileCompras
          compras={compras}
          setCompras={setCompras}
          user={user}
          userTitle={userTitle}
          onTabSwitch={setView}
          hasCompras={hasCompras}
          hasYate={hasYate}
          role={role}
        />
      ) : view === "yate" ? (
        <MobileYate
          tasks={tasks}
          compras={compras}
          setCompras={setCompras}
          user={user}
          userTitle={userTitle}
          onTabSwitch={setView}
          onUpdateTask={onUpdate}
          hasCompras={hasCompras}
          hasYate={hasYate}
          role={role}
        />
      ) : view === "huespedes" ? (
        <MobileHuespedes
          guests={allGuests}
          activeGuestId={activeGuestId}
          setActiveGuestId={setActiveGuestId}
          onBackToTareas={() => setView("tareas")}
          user={user}
          userTitle={userTitle}
          onTabSwitch={setView}
          hasCompras={hasCompras}
          hasYate={hasYate}
        />
      ) : !active ? (
        <>
          {/* Top bar */}
          <div style={{ padding: "14px 16px 4px", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
              <Avatar id={user.id} size="lg" />
              <div>
                <div style={{ fontSize: 11.5, color: "var(--cdc-ink-3)" }}>{userTitle}</div>
                <div style={{ fontWeight: 700, fontSize: 15 }}>{user.name.split(" ")[0]}</div>
              </div>
            </div>
            <button className="cdc-top__bell" style={{ width: 36, height: 36 }}>
              <I.Bell size={16} />
              <span className="cdc-top__bell-dot">3</span>
            </button>
          </div>

          {/* Greeting / date */}
          <div style={{ padding: "6px 16px 14px" }}>
            <div style={{ fontFamily: "var(--cdc-display)", fontSize: 22, fontWeight: 500, lineHeight: 1.15 }}>
              {["Domingo","Lunes","Martes","Miércoles","Jueves","Viernes","Sábado"][TODAY.getDay()]}, {TODAY.getDate()} {MESES_LARGO[TODAY.getMonth()]}
            </div>
            <div style={{ fontSize: 12.5, color: "var(--cdc-ink-3)" }}>
              {todayTasks.length} tareas para hoy · {todayTasks.filter(t => t.priority === "alta").length} de alta prioridad
            </div>
          </div>

          {/* Segmented */}
          <div style={{ padding: "0 16px 12px", display: "flex", justifyContent: "center" }}>
            <div className="cdc-segmented" style={{ width: "100%" }}>
              <button className="cdc-segmented__btn" aria-pressed={tab === "hoy"} onClick={() => setTab("hoy")} style={{ flex: 1 }}>
                Hoy ({todayTasks.length})
              </button>
              <button className="cdc-segmented__btn" aria-pressed={tab === "semana"} onClick={() => setTab("semana")} style={{ flex: 1 }}>
                Esta semana ({weekTasks.length})
              </button>
            </div>
          </div>

          {/* Task list */}
          <div style={{ flex: 1, overflowY: "auto", padding: "0 12px 16px", display: "flex", flexDirection: "column", gap: 10, position: "relative" }}>
            {list.length === 0 && (
              <div className="cdc-empty" style={{ padding: 30 }}>
                <I.CheckCircle size={36} style={{ color: "var(--cdc-done)" }} />
                <div className="cdc-empty__title">¡Sin tareas!</div>
                <div style={{ fontSize: 13 }}>Disfruta el atardecer en Punta Mita.</div>
              </div>
            )}
            {list.map(t => {
              const done = t.checklist.filter(c => c.done).length;
              const total = t.checklist.length;
              const isOverdue = t.status === "vencida";
              return (
                <button
                  key={t.id}
                  onClick={() => setActiveTaskId(t.id)}
                  style={{
                    background: "white", border: "1px solid var(--cdc-border)", borderRadius: 14,
                    padding: "12px 14px", textAlign: "left", display: "flex", flexDirection: "column", gap: 6,
                    borderLeft: `4px solid ${
                      isOverdue ? "var(--cdc-overdue)" :
                      t.status === "urgente" || t.priority === "alta" ? "var(--cdc-coral)" :
                      "var(--cdc-cream-200)"
                    }`,
                  }}
                >
                  <div style={{ display: "flex", justifyContent: "space-between", gap: 8 }}>
                    <span style={{ fontWeight: 600, fontSize: 14.5, color: "var(--cdc-ink)", lineHeight: 1.3 }}>{t.title}</span>
                    <StatusBadge status={t.status} />
                  </div>
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", fontSize: 12, color: "var(--cdc-ink-3)" }}>
                    <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
                      <AreaIcon id={t.area} size={12} /> {AREA_BY_ID[t.area].label}
                      {t.location && <span style={{ color: "var(--cdc-ink-4)" }}>· {t.location}</span>}
                    </span>
                    <span style={{ display: "inline-flex", alignItems: "center", gap: 4 }}>
                      {total > 0 && <span style={{ fontVariantNumeric: "tabular-nums" }}>{done}/{total}</span>}
                      <I.ChevR size={14} />
                    </span>
                  </div>
                  {t.assignee && STAFF_BY_ID[t.assignee] && (
                    <div style={{ display: "flex", alignItems: "center", gap: 6, fontSize: 11.5, color: "var(--cdc-ink-3)", paddingTop: 4, borderTop: "1px dashed var(--cdc-border-soft)" }}>
                      <Avatar id={t.assignee} size="sm" />
                      <span style={{
                        fontWeight: t.assignee === user.id ? 700 : 500,
                        color: t.assignee === user.id ? "var(--cdc-coral-deep)" : "var(--cdc-ink-2)",
                      }}>
                        {STAFF_BY_ID[t.assignee].name}
                      </span>
                      {t.assignee === user.id && (
                        <span style={{ fontSize: 10, color: "var(--cdc-coral-deep)", fontWeight: 700, background: "var(--cdc-coral-soft)", padding: "1px 6px", borderRadius: 999 }}>
                          Tú
                        </span>
                      )}
                    </div>
                  )}
                </button>
              );
            })}

            {/* Floating Action Button for Jefe role */}
            {isJefe && onCreate && (
              <button
                onClick={() => onCreate(user.area)}
                aria-label="Crear tarea"
                style={{
                  position: "sticky", bottom: 10, alignSelf: "flex-end",
                  width: 54, height: 54, borderRadius: 999,
                  background: "var(--cdc-coral)", color: "white",
                  display: "flex", alignItems: "center", justifyContent: "center",
                  boxShadow: "0 6px 14px rgba(122, 154, 63, 0.4)",
                  border: "none", marginRight: 4, marginLeft: "auto",
                }}
              >
                <I.Plus size={26} stroke={2.4} />
              </button>
            )}
          </div>

          {/* Bottom nav */}
          <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", borderTop: "1px solid var(--cdc-border)", background: "white", padding: "8px 0 10px" }}>
            {[
              { id: "tareas",    icon: <I.List size={20} />,     label: "Tareas",    active: view === "tareas" },
              { id: "huespedes", icon: <I.Heart size={20} />,    label: "Huéspedes", active: view === "huespedes" },
              hasYate
                ? { id: "yate", icon: <I.Anchor size={20} />, label: "Máximo", active: view === "yate" }
                : hasCompras
                  ? { id: "compras", icon: <I.Cart size={20} />, label: "Compras", active: view === "compras" }
                  : { id: "agenda", icon: <I.Calendar size={20} />, label: "Agenda", disabled: true },
              hasYate && hasCompras
                ? { id: "compras", icon: <I.Cart size={20} />, label: "Compras", active: view === "compras" }
                : { id: "yo", icon: <I.User size={20} />, label: "Yo", disabled: true },
            ].map((b) => (
              <button
                key={b.id}
                onClick={() => { if (!b.disabled) setView(b.id); }}
                disabled={b.disabled}
                style={{
                  display: "flex", flexDirection: "column", alignItems: "center", gap: 3,
                  color: b.active ? "var(--cdc-coral-deep)" : b.disabled ? "var(--cdc-ink-4)" : "var(--cdc-ink-3)",
                  fontWeight: b.active ? 700 : 500, fontSize: 11,
                  opacity: b.disabled ? 0.5 : 1,
                  cursor: b.disabled ? "default" : "pointer",
                }}
              >
                {b.icon}
                <span>{b.label}</span>
              </button>
            ))}
          </div>
        </>
      ) : (
        <MobileTaskDetail
          task={active}
          onBack={() => setActiveTaskId(null)}
          toggleCheck={toggleCheck}
          onUpdate={onUpdate}
        />
      )}
    </div>
  );
};


const MobileTaskDetail = ({ task, onBack, toggleCheck, onUpdate }) => {
  if (!task) {
    return (
      <>
        <div style={{ display: "flex", alignItems: "center", gap: 6, padding: "14px 16px", borderBottom: "1px solid var(--cdc-border-soft)" }}>
          <button className="cdc-iconbtn" onClick={onBack}><I.ChevL size={18} /></button>
          <span style={{ fontSize: 13, color: "var(--cdc-ink-3)", fontWeight: 500 }}>Volver a tareas</span>
        </div>
        <div className="cdc-empty" style={{ padding: 40 }}>
          <I.CheckCircle size={36} style={{ color: "var(--cdc-done)" }} />
          <div className="cdc-empty__title">Tarea no disponible</div>
          <div style={{ fontSize: 13 }}>Esta tarea fue eliminada o ya no está visible.</div>
        </div>
      </>
    );
  }
  const checklist = task.checklist || [];
  const done = checklist.filter(c => c.done).length;
  const total = checklist.length;
  return (
    <>
      <div style={{ display: "flex", alignItems: "center", gap: 6, padding: "14px 16px", borderBottom: "1px solid var(--cdc-border-soft)" }}>
        <button className="cdc-iconbtn" onClick={onBack}><I.ChevL size={18} /></button>
        <span style={{ fontSize: 13, color: "var(--cdc-ink-3)", fontWeight: 500 }}>Volver a tareas</span>
      </div>
      <div style={{ flex: 1, overflowY: "auto", padding: "16px 18px 18px" }}>
        <StatusBadge status={task.status} />
        <h2 style={{ fontFamily: "var(--cdc-display)", fontSize: 22, fontWeight: 500, marginTop: 8, marginBottom: 10, lineHeight: 1.2 }}>{task.title}</h2>

        <div style={{ display: "grid", gridTemplateColumns: "auto 1fr", gap: "6px 12px", fontSize: 13, color: "var(--cdc-ink-2)", marginBottom: 14 }}>
          <span style={{ color: "var(--cdc-ink-3)" }}>Área</span>
          <span><AreaChip id={task.area} /></span>
          <span style={{ color: "var(--cdc-ink-3)" }}>Vence</span>
          <span>{fmtLongDate(task.due)}{task.dueTime ? ` · ${task.dueTime}` : ""}</span>
          {task.location && <>
            <span style={{ color: "var(--cdc-ink-3)" }}>Lugar</span>
            <span>{task.location}</span>
          </>}
          {task.assignee && STAFF_BY_ID[task.assignee] && <>
            <span style={{ color: "var(--cdc-ink-3)" }}>Asignado a</span>
            <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
              <Avatar id={task.assignee} size="sm" />
              {STAFF_BY_ID[task.assignee].name}
            </span>
          </>}
          <span style={{ color: "var(--cdc-ink-3)" }}>Prioridad</span>
          <span><Priority p={task.priority} /></span>
        </div>

        {task.description && (
          <>
            <div className="cdc-section-h">Descripción</div>
            <p className="cdc-p" style={{ marginBottom: 14 }}>{task.description}</p>
          </>
        )}

        {total > 0 && (
          <>
            <div className="cdc-section-h cdc-section-h--with-count">
              <span>Checklist</span>
              <span className="cdc-section-h__count">{done}/{total}</span>
            </div>
            <div className="cdc-checklist" style={{ marginBottom: 14 }}>
              {checklist.map(c => (
                <div key={c.id} className="cdc-checklist__item" data-done={c.done || undefined}
                  onClick={() => toggleCheck(c.id)} style={{ padding: "8px 0" }}>
                  <Circle checked={c.done} onClick={() => toggleCheck(c.id)} />
                  <span>{c.text}</span>
                </div>
              ))}
            </div>
          </>
        )}

        {task.notes && (
          <>
            <div className="cdc-section-h">Notas</div>
            <p className="cdc-p">{task.notes}</p>
          </>
        )}
      </div>

      <div style={{ padding: 14, borderTop: "1px solid var(--cdc-border-soft)", display: "flex", gap: 8, background: "white" }}>
        <button className="cdc-btn" style={{ flex: 1 }}><I.Hourglass size={14} /> Aplazar</button>
        <button
          className="cdc-btn cdc-btn--primary"
          style={{ flex: 2 }}
          onClick={() => {
            const next = task.status === "progreso" ? "terminada" : "progreso";
            onUpdate({ ...task, status: next });
          }}
        >
          <I.Play size={14} /> {task.status === "progreso" ? "Marcar terminada" : "Iniciar tarea"}
        </button>
      </div>
    </>
  );
};

Object.assign(window, { MobileApp });

const MobileHuespedes = ({ guests, activeGuestId, setActiveGuestId, onBackToTareas, user, userTitle, onTabSwitch, hasCompras, hasYate }) => {
  const active = activeGuestId ? guests.find(g => g.id === activeGuestId) : null;

  const BottomNav = () => (
    <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", borderTop: "1px solid var(--cdc-border)", background: "white", padding: "8px 0 10px" }}>
      {[
        { id: "tareas",    icon: <I.List size={20} />,     label: "Tareas",    active: false },
        { id: "huespedes", icon: <I.Heart size={20} />,    label: "Huéspedes", active: true },
        hasYate
          ? { id: "yate", icon: <I.Anchor size={20} />, label: "Máximo", active: false }
          : hasCompras
            ? { id: "compras", icon: <I.Cart size={20} />,     label: "Compras",   active: false }
            : { id: "agenda",  icon: <I.Calendar size={20} />, label: "Agenda",    disabled: true },
        hasYate && hasCompras
          ? { id: "compras", icon: <I.Cart size={20} />, label: "Compras", active: false }
          : { id: "yo", icon: <I.User size={20} />, label: "Yo", disabled: true },
      ].map((b) => (
        <button
          key={b.id}
          onClick={() => { if (!b.disabled) onTabSwitch && onTabSwitch(b.id); }}
          disabled={b.disabled}
          style={{
            display: "flex", flexDirection: "column", alignItems: "center", gap: 3,
            color: b.active ? "var(--cdc-coral-deep)" : b.disabled ? "var(--cdc-ink-4)" : "var(--cdc-ink-3)",
            fontWeight: b.active ? 700 : 500, fontSize: 11,
            opacity: b.disabled ? 0.5 : 1,
            cursor: b.disabled ? "default" : "pointer",
          }}
        >
          {b.icon}
          <span>{b.label}</span>
        </button>
      ))}
    </div>
  );

  if (active) {
    return (
      <>
        <div style={{ display: "flex", alignItems: "center", gap: 6, padding: "14px 16px", borderBottom: "1px solid var(--cdc-border-soft)" }}>
          <button className="cdc-iconbtn" onClick={() => setActiveGuestId(null)}><I.ChevL size={18} /></button>
          <span style={{ fontSize: 13, color: "var(--cdc-ink-3)", fontWeight: 500 }}>Volver a huéspedes</span>
        </div>
        <div style={{ flex: 1, overflowY: "auto", padding: "14px 18px 18px" }}>
          <div style={{ fontFamily: "var(--cdc-display)", fontSize: 22, fontWeight: 500, lineHeight: 1.2, marginBottom: 4 }}>{active.nombres}</div>
          <div style={{ fontSize: 12.5, color: "var(--cdc-ink-3)", marginBottom: 12, display: "flex", alignItems: "center", gap: 6, flexWrap: "wrap" }}>
            <I.Calendar size={12} />
            <span>{fmtShortDate(active.llegada)} → {fmtShortDate(active.salida)}</span>
            {active.llegada <= TODAY_ISO && active.salida >= TODAY_ISO && <span className="cdc-badge cdc-badge--progress">En casa</span>}
            {active.llegada > TODAY_ISO && <span className="cdc-badge cdc-badge--pending">Próximo</span>}
          </div>

          {(active.suites && active.suites.length > 0) && (
            <div style={{ marginBottom: 12 }}>
              <div style={{ fontSize: 10.5, letterSpacing: "0.12em", textTransform: "uppercase", color: "var(--cdc-ink-3)", fontWeight: 700, marginBottom: 4 }}>Suites</div>
              <div style={{ display: "flex", flexWrap: "wrap", gap: 4 }}>
                {active.suites.map(s => <span key={s} className="cdc-badge" style={{ background: "var(--cdc-coral-soft)", color: "var(--cdc-coral-deep)" }}><I.Bed size={10} /> {s}</span>)}
              </div>
            </div>
          )}

          {(active.personas && active.personas.length > 0) && (
            <div style={{ marginBottom: 14 }}>
              <div style={{ fontSize: 10.5, letterSpacing: "0.12em", textTransform: "uppercase", color: "var(--cdc-ink-3)", fontWeight: 700, marginBottom: 6 }}>Integrantes</div>
              <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                {active.personas.map(p => (
                  <div key={p.id} style={{ background: "var(--cdc-bg-soft)", border: "1px solid var(--cdc-border-soft)", borderRadius: 10, padding: 10 }}>
                    <div style={{ display: "flex", justifyContent: "space-between", gap: 6 }}>
                      <span style={{ fontWeight: 600, fontSize: 13.5 }}>{p.nombre}{p.edad && <span style={{ color: "var(--cdc-ink-3)", fontWeight: 500, marginLeft: 6 }}>· {p.edad} años</span>}</span>
                      {p.suite && <span style={{ fontSize: 11, color: "var(--cdc-coral-deep)" }}>{p.suite}</span>}
                    </div>
                    {p.alergias && <div style={{ fontSize: 12, color: "var(--cdc-overdue)", marginTop: 4 }}>⚠ Alergia: {p.alergias}</div>}
                    {p.restricciones && <div style={{ fontSize: 12, color: "var(--cdc-med)", marginTop: 2 }}>Restricción: {p.restricciones}</div>}
                    {p.preferencias && <div style={{ fontSize: 12, color: "var(--cdc-ink-3)", marginTop: 2 }}>{p.preferencias}</div>}
                  </div>
                ))}
              </div>
            </div>
          )}

          {active.preferenciasAlimentos && (
            <div style={{ marginBottom: 10 }}>
              <div style={{ fontSize: 10.5, letterSpacing: "0.12em", textTransform: "uppercase", color: "var(--cdc-ink-3)", fontWeight: 700, marginBottom: 4 }}>Preferencias de alimentos</div>
              <div style={{ fontSize: 13, color: "var(--cdc-ink-2)", lineHeight: 1.5 }}>{active.preferenciasAlimentos}</div>
            </div>
          )}
          {active.preferenciasVinos && (
            <div style={{ marginBottom: 10 }}>
              <div style={{ fontSize: 10.5, letterSpacing: "0.12em", textTransform: "uppercase", color: "var(--cdc-ink-3)", fontWeight: 700, marginBottom: 4 }}>Preferencias de vinos</div>
              <div style={{ fontSize: 13, color: "var(--cdc-ink-2)", lineHeight: 1.5 }}>{active.preferenciasVinos}</div>
            </div>
          )}
          {active.notas && (
            <div style={{ paddingLeft: 10, borderLeft: "2px solid var(--cdc-coral-deep)", marginTop: 12 }}>
              <div style={{ fontSize: 10.5, letterSpacing: "0.12em", textTransform: "uppercase", color: "var(--cdc-ink-3)", fontWeight: 700, marginBottom: 4 }}>Notas importantes</div>
              <div style={{ fontSize: 13, color: "var(--cdc-ink-2)", lineHeight: 1.5 }}>{active.notas}</div>
            </div>
          )}
        </div>
        <BottomNav />
      </>
    );
  }

  return (
    <>
      <div style={{ padding: "14px 16px 4px", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <Avatar id={user.id} size="lg" />
          <div>
            <div style={{ fontSize: 11.5, color: "var(--cdc-ink-3)" }}>{userTitle}</div>
            <div style={{ fontWeight: 700, fontSize: 15 }}>{user.name.split(" ")[0]}</div>
          </div>
        </div>
        <button className="cdc-top__bell" style={{ width: 36, height: 36 }}>
          <I.Bell size={16} />
        </button>
      </div>
      <div style={{ padding: "6px 16px 14px" }}>
        <div style={{ fontFamily: "var(--cdc-display)", fontSize: 22, fontWeight: 500, lineHeight: 1.15 }}>Huéspedes</div>
        <div style={{ fontSize: 12.5, color: "var(--cdc-ink-3)" }}>{guests.length} registro{guests.length === 1 ? "" : "s"}</div>
      </div>
      <div style={{ flex: 1, overflowY: "auto", padding: "0 12px 16px", display: "flex", flexDirection: "column", gap: 10 }}>
        {guests.length === 0 ? (
          <div className="cdc-empty" style={{ padding: 30 }}>
            <I.Heart size={36} />
            <div className="cdc-empty__title">Sin huéspedes</div>
          </div>
        ) : guests.map(g => {
          const isActive = g.llegada <= TODAY_ISO && g.salida >= TODAY_ISO;
          const isUpcoming = g.llegada > TODAY_ISO;
          return (
            <button
              key={g.id}
              onClick={() => setActiveGuestId(g.id)}
              style={{
                background: "white", border: "1px solid var(--cdc-border)", borderRadius: 14,
                padding: "12px 14px", textAlign: "left", display: "flex", flexDirection: "column", gap: 6,
                borderLeft: `4px solid ${isActive ? "var(--cdc-done)" : isUpcoming ? "var(--cdc-coral)" : "var(--cdc-cream-200)"}`,
              }}
            >
              <div style={{ display: "flex", justifyContent: "space-between", gap: 8 }}>
                <span style={{ fontWeight: 600, fontSize: 14.5, color: "var(--cdc-ink)", lineHeight: 1.3 }}>{g.nombres}</span>
                {isActive && <span className="cdc-badge cdc-badge--progress">En casa</span>}
                {isUpcoming && <span className="cdc-badge cdc-badge--pending">Próximo</span>}
              </div>
              <div style={{ fontSize: 12, color: "var(--cdc-ink-3)", display: "flex", alignItems: "center", gap: 6, flexWrap: "wrap" }}>
                <I.Calendar size={12} /> {fmtShortDate(g.llegada)} → {fmtShortDate(g.salida)}
                {g.suites && g.suites.length > 0 && (
                  <span style={{ color: "var(--cdc-coral-deep)" }}>· {g.suites.join(", ")}</span>
                )}
              </div>
              {g.personas && g.personas.length > 0 && (
                <div style={{ fontSize: 11, color: "var(--cdc-ink-4)" }}>
                  {g.personas.length} integrante{g.personas.length === 1 ? "" : "s"}
                  {g.personas.some(p => p.alergias) && <span style={{ color: "var(--cdc-overdue)", marginLeft: 6 }}>⚠ alergias</span>}
                </div>
              )}
            </button>
          );
        })}
      </div>
      <BottomNav />
    </>
  );
};

Object.assign(window, { MobileHuespedes });

const MobileCompras = ({ compras, setCompras, user, userTitle, onTabSwitch, hasCompras, hasYate, role }) => {
  const [activeList, setActiveList] = React.useState("todos");
  const [statusFilter, setStatusFilter] = React.useState("todos"); // "todos" | "pendiente" | "entregado" | "no_encontrado"
  const [dateFilter, setDateFilter] = React.useState("todas");     // "todas" | "hoy" | "ayer" | "semana"

  const LIST_META = {
    bar:       { label: "Bar",            icon: "Cocktail" },
    cocina:    { label: "Cocina",         icon: "Chef" },
    amallaves: { label: "Ama de llaves",  icon: "Bed" },
    yate:      { label: "Yate Máximo",    icon: "Anchor" },
  };

  // Only the Encargado de Compras (and admins/managers) can change status.
  // Everyone else (department staff/jefes) sees the registry as read-only.
  const canManageStatus = role === "admin" || role === "gerente" || role === "compras";

  // Visibility: encargado/admin/gerente see all departments. Department members
  // see only their own area + extras.
  const allowedAreas = canManageStatus
    ? Object.keys(compras || {})
    : [user.area, ...(user.extraAreas || []).map(e => e.area)].filter(Boolean);

  const all = Object.entries(compras || {})
    .filter(([area]) => allowedAreas.includes(area))
    .flatMap(([area, items]) => items.map(i => ({ ...i, _source: area })));

  // Filter chain
  const yesterday = fmtISO(addDays(TODAY, -1));
  const weekStart = fmtISO(addDays(TODAY, -7));

  const byList = activeList === "todos" ? all : all.filter(i => i._source === activeList);
  const byStatus = statusFilter === "todos" ? byList : byList.filter(i => i.status === statusFilter);
  const byDate = dateFilter === "todas" ? byStatus
    : dateFilter === "hoy"    ? byStatus.filter(i => i.addedOn === TODAY_ISO)
    : dateFilter === "ayer"   ? byStatus.filter(i => i.addedOn === yesterday)
    : dateFilter === "semana" ? byStatus.filter(i => i.addedOn >= weekStart)
    : byStatus;

  // Group items by date for daily registry view
  const grouped = {};
  byDate.forEach(i => {
    if (!grouped[i.addedOn]) grouped[i.addedOn] = [];
    grouped[i.addedOn].push(i);
  });
  const dates = Object.keys(grouped).sort().reverse();

  const updateStatus = (source, id, status) => {
    if (!setCompras || !canManageStatus) return;
    setCompras(prev => ({
      ...prev,
      [source]: prev[source].map(it => it.id === id ? { ...it, status } : it),
    }));
  };

  const STATUS_BADGE = {
    pendiente:     { label: "Compra pendiente", bg: "var(--cdc-pending-bg)",  fg: "var(--cdc-pending)" },
    entregado:     { label: "Comprado",         bg: "var(--cdc-done-bg)",     fg: "var(--cdc-done)" },
    no_encontrado: { label: "No encontrado",    bg: "var(--cdc-overdue-bg)",  fg: "var(--cdc-overdue)" },
  };

  const counts = {
    pendiente:     all.filter(i => i.status === "pendiente").length,
    entregado:     all.filter(i => i.status === "entregado").length,
    no_encontrado: all.filter(i => i.status === "no_encontrado").length,
  };

  const BottomNav = () => (
    <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", borderTop: "1px solid var(--cdc-border)", background: "white", padding: "8px 0 10px" }}>
      {[
        { id: "tareas",    icon: <I.List size={20} />,     label: "Tareas",    active: false },
        { id: "huespedes", icon: <I.Heart size={20} />,    label: "Huéspedes", active: false },
        hasYate
          ? { id: "yate", icon: <I.Anchor size={20} />, label: "Máximo", active: false }
          : hasCompras
            ? { id: "compras", icon: <I.Cart size={20} />, label: "Compras", active: true }
            : { id: "agenda", icon: <I.Calendar size={20} />, label: "Agenda", disabled: true },
        hasYate && hasCompras
          ? { id: "compras", icon: <I.Cart size={20} />, label: "Compras", active: true }
          : { id: "yo", icon: <I.User size={20} />, label: "Yo", disabled: true },
      ].map((b) => (
        <button
          key={b.id}
          onClick={() => { if (!b.disabled) onTabSwitch && onTabSwitch(b.id); }}
          disabled={b.disabled}
          style={{
            display: "flex", flexDirection: "column", alignItems: "center", gap: 3,
            color: b.active ? "var(--cdc-coral-deep)" : b.disabled ? "var(--cdc-ink-4)" : "var(--cdc-ink-3)",
            fontWeight: b.active ? 700 : 500, fontSize: 11,
            opacity: b.disabled ? 0.5 : 1,
            cursor: b.disabled ? "default" : "pointer",
          }}
        >
          {b.icon}
          <span>{b.label}</span>
        </button>
      ))}
    </div>
  );

  return (
    <>
      <div style={{ padding: "14px 16px 4px", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <Avatar id={user.id} size="lg" />
          <div>
            <div style={{ fontSize: 11.5, color: "var(--cdc-ink-3)" }}>{userTitle}</div>
            <div style={{ fontWeight: 700, fontSize: 15 }}>{user.name.split(" ")[0]}</div>
          </div>
        </div>
        <button className="cdc-top__bell" style={{ width: 36, height: 36 }}>
          <I.Bell size={16} />
        </button>
      </div>
      <div style={{ padding: "6px 16px 12px" }}>
        <div style={{ fontFamily: "var(--cdc-display)", fontSize: 22, fontWeight: 500, lineHeight: 1.15 }}>Compras</div>
        <div style={{ fontSize: 12.5, color: "var(--cdc-ink-3)" }}>
          {counts.pendiente} pendiente{counts.pendiente === 1 ? "" : "s"} · {counts.entregado} comprado{counts.entregado === 1 ? "" : "s"} · {counts.no_encontrado} no encontrado{counts.no_encontrado === 1 ? "" : "s"}
        </div>
      </div>

      {/* Departamento (solo si hay más de uno) */}
      {Object.keys(LIST_META).filter(k => all.some(i => i._source === k)).length > 1 && (
        <div style={{ padding: "0 14px 6px", display: "flex", gap: 4, overflowX: "auto" }}>
          <button className="cdc-chip" aria-pressed={activeList === "todos"} onClick={() => setActiveList("todos")}>
            Todas <span style={{ color: "var(--cdc-ink-4)", marginLeft: 4 }}>{all.length}</span>
          </button>
          {Object.keys(LIST_META).map(k => {
            const c = all.filter(i => i._source === k).length;
            if (c === 0) return null;
            return (
              <button key={k} className="cdc-chip" aria-pressed={activeList === k} onClick={() => setActiveList(k)}>
                {LIST_META[k].label} <span style={{ color: "var(--cdc-ink-4)", marginLeft: 4 }}>{c}</span>
              </button>
            );
          })}
        </div>
      )}

      {/* Estado */}
      <div style={{ padding: "0 14px 6px", display: "flex", gap: 4, overflowX: "auto" }}>
        {[
          ["todos",         "Todas"],
          ["pendiente",     "Pendientes"],
          ["entregado",     "Comprados"],
          ["no_encontrado", "No encontrados"],
        ].map(([k, lbl]) => (
          <button key={k} className="cdc-chip" aria-pressed={statusFilter === k} onClick={() => setStatusFilter(k)}>
            {lbl}
          </button>
        ))}
      </div>

      {/* Fecha (registro por día) */}
      <div style={{ padding: "0 14px 8px", display: "flex", gap: 4, overflowX: "auto" }}>
        {[
          ["todas",  "Todas las fechas"],
          ["hoy",    "Hoy"],
          ["ayer",   "Ayer"],
          ["semana", "Última semana"],
        ].map(([k, lbl]) => (
          <button key={k} className="cdc-chip" aria-pressed={dateFilter === k} onClick={() => setDateFilter(k)}>
            <I.Calendar size={11} /> {lbl}
          </button>
        ))}
      </div>

      <div style={{ flex: 1, overflowY: "auto", padding: "0 12px 16px", display: "flex", flexDirection: "column", gap: 14 }}>
        {byDate.length === 0 ? (
          <div className="cdc-empty" style={{ padding: 30 }}>
            <I.Cart size={36} style={{ color: "var(--cdc-done)" }} />
            <div className="cdc-empty__title">Sin registros</div>
            <div style={{ fontSize: 13 }}>No hay artículos en este filtro.</div>
          </div>
        ) : dates.map(date => (
          <div key={date} style={{ display: "flex", flexDirection: "column", gap: 8 }}>
            <div style={{ fontSize: 11, letterSpacing: "0.14em", color: "var(--cdc-ink-3)", textTransform: "uppercase", fontWeight: 700, padding: "4px 4px 0" }}>
              {date === TODAY_ISO ? "Hoy" : date === yesterday ? "Ayer" : fmtLongDate(date)}
            </div>
            {grouped[date].map(it => {
              const meta = LIST_META[it._source] || {};
              const IconCmp = I[meta.icon] || I.Cart;
              const sbadge = STATUS_BADGE[it.status] || STATUS_BADGE.pendiente;
              return (
                <div key={it.id} style={{
                  background: "white", border: "1px solid var(--cdc-border)", borderRadius: 14,
                  padding: "12px 14px", display: "flex", flexDirection: "column", gap: 10,
                  borderLeft: `4px solid ${it.priority === "alta" ? "var(--cdc-overdue)" : it.priority === "media" ? "var(--cdc-med)" : "var(--cdc-cream-300)"}`,
                  opacity: it.status === "entregado" || it.status === "no_encontrado" ? 0.85 : 1,
                }}>
                  <div style={{ display: "grid", gridTemplateColumns: "60px 1fr", gap: 12 }}>
                    <button
                      onClick={() => it.photo && window.open(it.photo, "_blank")}
                      style={{
                        width: 60, height: 60, borderRadius: 10, overflow: "hidden",
                        background: "var(--cdc-cream-100)", border: "1px solid var(--cdc-border-soft)",
                        display: "flex", alignItems: "center", justifyContent: "center", padding: 0,
                        cursor: it.photo ? "pointer" : "default",
                      }}
                    >
                      {it.photo
                        ? <img src={it.photo} alt={it.name} style={{ width: "100%", height: "100%", objectFit: "cover" }} />
                        : <I.Camera size={22} stroke={1.4} style={{ color: "var(--cdc-ink-4)" }} />}
                    </button>
                    <div style={{ minWidth: 0 }}>
                      <div style={{ display: "flex", justifyContent: "space-between", gap: 6, alignItems: "baseline" }}>
                        <div style={{ fontWeight: 600, fontSize: 13.5, color: "var(--cdc-ink)", lineHeight: 1.3 }}>{it.name}</div>
                        <div style={{ fontSize: 12, color: "var(--cdc-ink-2)", fontWeight: 600, whiteSpace: "nowrap" }}>{it.qty} {it.unit}</div>
                      </div>
                      <div style={{ fontSize: 11, color: "var(--cdc-ink-3)", display: "flex", alignItems: "center", gap: 6, marginTop: 4, flexWrap: "wrap" }}>
                        <span style={{ display: "inline-flex", alignItems: "center", gap: 4 }}>
                          <IconCmp size={11} /> {meta.label || it._source}
                        </span>
                        <span className="cdc-badge" style={{ background: sbadge.bg, color: sbadge.fg }}>{sbadge.label}</span>
                      </div>
                      {it.note && <div style={{ fontSize: 11.5, color: "var(--cdc-ink-3)", marginTop: 4, lineHeight: 1.4 }}>{it.note}</div>}
                      {it.supplier && <div style={{ fontSize: 11, color: "var(--cdc-ink-3)", marginTop: 3, display: "inline-flex", alignItems: "center", gap: 4 }}>
                        <I.MapPin2 size={10} /> {it.supplier}
                      </div>}
                    </div>
                  </div>

                  {/* Action buttons — only for Hector / admin / manager */}
                  {canManageStatus && setCompras && it.status === "pendiente" && (
                    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 6, paddingTop: 8, borderTop: "1px dashed var(--cdc-border-soft)" }}>
                      <button
                        onClick={() => updateStatus(it._source, it.id, "entregado")}
                        style={{
                          padding: "10px 8px", borderRadius: 10, border: 0,
                          background: "var(--cdc-done-bg)", color: "var(--cdc-done)",
                          fontWeight: 700, fontSize: 12.5, display: "inline-flex",
                          alignItems: "center", justifyContent: "center", gap: 6,
                        }}
                      >
                        <I.Check size={14} stroke={2.4} /> Comprado
                      </button>
                      <button
                        onClick={() => updateStatus(it._source, it.id, "no_encontrado")}
                        style={{
                          padding: "10px 8px", borderRadius: 10, border: 0,
                          background: "var(--cdc-overdue-bg)", color: "var(--cdc-overdue)",
                          fontWeight: 700, fontSize: 12.5, display: "inline-flex",
                          alignItems: "center", justifyContent: "center", gap: 6,
                        }}
                      >
                        <I.X size={14} stroke={2.4} /> No encontrado
                      </button>
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        ))}
      </div>

      <BottomNav />
    </>
  );
};

Object.assign(window, { MobileCompras });

/* === Mobile Yate view: tabs Reservaciones / Menús / Compras === */
const MobileYate = ({ tasks, compras, setCompras, user, userTitle, onTabSwitch, onUpdateTask, hasCompras, hasYate, role }) => {
  // Same logic as desktop YateView: hide Tareas for cocina chefs, show for yate/mant primary + admin/gerente
  const showTareas = role === "admin" || role === "gerente" || user.area === "yate" || user.area === "mant";
  const [section, setSection] = React.useState(showTareas ? "tareas" : "reservaciones");
  const [activeMenu, setActiveMenu] = React.useState(null);
  const [activeTaskId, setActiveTaskId] = React.useState(null);

  const yateTasks = (tasks || []).filter(t => t.area === "yate");
  const activeTask = activeTaskId ? yateTasks.find(t => t.id === activeTaskId) : null;
  const reservaciones = (typeof YATE_RESERVATIONS_INIT !== "undefined") ? YATE_RESERVATIONS_INIT : [];
  const menus = (typeof YATE_MENUS !== "undefined") ? YATE_MENUS : [];
  const yList = (compras && compras.yate) || [];
  const pending = yList.filter(i => i.status === "pendiente");

  const BottomNav = () => (
    <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", borderTop: "1px solid var(--cdc-border)", background: "white", padding: "8px 0 10px" }}>
      {[
        { id: "tareas",    icon: <I.List size={20} />,  label: "Tareas",    active: false },
        { id: "huespedes", icon: <I.Heart size={20} />, label: "Huéspedes", active: false },
        { id: "yate",      icon: <I.Anchor size={20} />, label: "Máximo",   active: true },
        hasCompras
          ? { id: "compras", icon: <I.Cart size={20} />, label: "Compras", active: false }
          : { id: "yo", icon: <I.User size={20} />, label: "Yo", disabled: true },
      ].map((b) => (
        <button
          key={b.id}
          onClick={() => { if (!b.disabled) onTabSwitch && onTabSwitch(b.id); }}
          disabled={b.disabled}
          style={{
            display: "flex", flexDirection: "column", alignItems: "center", gap: 3,
            color: b.active ? "var(--cdc-coral-deep)" : b.disabled ? "var(--cdc-ink-4)" : "var(--cdc-ink-3)",
            fontWeight: b.active ? 700 : 500, fontSize: 11,
            opacity: b.disabled ? 0.5 : 1,
            cursor: b.disabled ? "default" : "pointer",
          }}
        >
          {b.icon}
          <span>{b.label}</span>
        </button>
      ))}
    </div>
  );

  if (activeMenu) {
    const m = menus.find(x => x.id === activeMenu);
    const IconCmp = (m && I[m.icon]) || I.Chef;
    return (
      <>
        <div style={{ display: "flex", alignItems: "center", gap: 6, padding: "14px 16px", borderBottom: "1px solid var(--cdc-border-soft)" }}>
          <button className="cdc-iconbtn" onClick={() => setActiveMenu(null)}><I.ChevL size={18} /></button>
          <span style={{ fontSize: 13, color: "var(--cdc-ink-3)", fontWeight: 500 }}>Volver a menús</span>
        </div>
        <div style={{ flex: 1, overflowY: "auto", padding: "14px 18px" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 12 }}>
            <span style={{ display: "inline-flex", alignItems: "center", justifyContent: "center", width: 38, height: 38, borderRadius: 10, background: "var(--cdc-coral-soft)", color: "var(--cdc-coral-deep)" }}>
              <IconCmp size={20} />
            </span>
            <div>
              <div style={{ fontFamily: "var(--cdc-display)", fontSize: 18, fontWeight: 600, lineHeight: 1.2 }}>{m.name}</div>
              <div style={{ fontSize: 11.5, color: "var(--cdc-ink-3)" }}>{m.items.length} ítems</div>
            </div>
          </div>
          <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 4 }}>
            {m.items.map((it, i) => (
              <li key={i} style={{ display: "flex", gap: 8, padding: "8px 0", borderTop: i === 0 ? "none" : "1px solid var(--cdc-border-soft)", fontSize: 13, color: "var(--cdc-ink-2)", lineHeight: 1.4 }}>
                <span style={{ color: "var(--cdc-coral-deep)" }}>•</span>
                <span>{it}</span>
              </li>
            ))}
          </ul>
        </div>
        <BottomNav />
      </>
    );
  }

  return (
    <>
      <div style={{ padding: "14px 16px 4px", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <Avatar id={user.id} size="lg" />
          <div>
            <div style={{ fontSize: 11.5, color: "var(--cdc-ink-3)" }}>{userTitle}</div>
            <div style={{ fontWeight: 700, fontSize: 15 }}>{user.name.split(" ")[0]}</div>
          </div>
        </div>
        <button className="cdc-top__bell" style={{ width: 36, height: 36 }}>
          <I.Bell size={16} />
        </button>
      </div>
      <div style={{ padding: "6px 16px 12px" }}>
        <div style={{ fontFamily: "var(--cdc-display)", fontSize: 22, fontWeight: 500, lineHeight: 1.15 }}>Máximo · Yate</div>
      </div>

      <div style={{ padding: "0 14px 8px", display: "flex", gap: 4 }}>
        {[
          ...(showTareas ? [["tareas", `Tareas (${yateTasks.length})`]] : []),
          ["reservaciones", `Reservaciones (${reservaciones.length})`],
          ["menus",         `Menús (${menus.length})`],
          ["compras",       `Compras (${pending.length})`],
        ].map(([k, lbl]) => (
          <button key={k} className="cdc-chip" aria-pressed={section === k} onClick={() => setSection(k)} style={{ flex: 1, justifyContent: "center" }}>
            {lbl}
          </button>
        ))}
      </div>

      <div style={{ flex: 1, overflowY: "auto", padding: "0 12px 16px", display: "flex", flexDirection: "column", gap: 10 }}>
        {section === "tareas" && showTareas && (
          activeTask ? (
            <MobileTaskDetail
              task={activeTask}
              onBack={() => setActiveTaskId(null)}
              toggleCheck={(cid) => onUpdateTask({
                ...activeTask,
                checklist: (activeTask.checklist || []).map(c => c.id === cid ? { ...c, done: !c.done } : c),
              })}
              onUpdate={onUpdateTask}
            />
          ) : yateTasks.length === 0 ? (
            <div className="cdc-empty" style={{ padding: 30 }}>
              <I.Anchor size={36} />
              <div className="cdc-empty__title">Sin tareas a bordo</div>
            </div>
          ) : yateTasks.map(t => {
            const done = (t.checklist || []).filter(c => c.done).length;
            const total = (t.checklist || []).length;
            return (
              <button
                key={t.id}
                onClick={() => setActiveTaskId(t.id)}
                style={{
                  background: "white", border: "1px solid var(--cdc-border)", borderRadius: 14,
                  padding: "12px 14px", textAlign: "left", display: "flex", flexDirection: "column", gap: 6,
                  borderLeft: `4px solid ${
                    t.status === "vencida" ? "var(--cdc-overdue)" :
                    t.priority === "alta" ? "var(--cdc-coral)" : "var(--cdc-cream-200)"
                  }`,
                }}
              >
                <div style={{ display: "flex", justifyContent: "space-between", gap: 8 }}>
                  <span style={{ fontWeight: 600, fontSize: 14, color: "var(--cdc-ink)", lineHeight: 1.3 }}>{t.title}</span>
                  <StatusBadge status={t.status} />
                </div>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", fontSize: 12, color: "var(--cdc-ink-3)" }}>
                  <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
                    <I.Calendar size={11} /> {fmtShortDate(t.due)}
                    {t.location && <span style={{ color: "var(--cdc-ink-4)" }}>· {t.location}</span>}
                  </span>
                  <span style={{ display: "inline-flex", alignItems: "center", gap: 4 }}>
                    {total > 0 && <span style={{ fontVariantNumeric: "tabular-nums" }}>{done}/{total}</span>}
                    <I.ChevR size={14} />
                  </span>
                </div>
                {t.assignee && STAFF_BY_ID[t.assignee] && (
                  <div style={{ display: "flex", alignItems: "center", gap: 6, fontSize: 11.5, color: "var(--cdc-ink-3)", paddingTop: 4, borderTop: "1px dashed var(--cdc-border-soft)" }}>
                    <Avatar id={t.assignee} size="sm" />
                    <span style={{
                      fontWeight: t.assignee === user.id ? 700 : 500,
                      color: t.assignee === user.id ? "var(--cdc-coral-deep)" : "var(--cdc-ink-2)",
                    }}>
                      {STAFF_BY_ID[t.assignee].name}
                    </span>
                    {t.assignee === user.id && (
                      <span style={{ fontSize: 10, color: "var(--cdc-coral-deep)", fontWeight: 700, background: "var(--cdc-coral-soft)", padding: "1px 6px", borderRadius: 999 }}>
                        Tú
                      </span>
                    )}
                  </div>
                )}
              </button>
            );
          })
        )}

        {section === "reservaciones" && (
          reservaciones.length === 0 ? (
            <div className="cdc-empty" style={{ padding: 30 }}>
              <I.Calendar size={36} />
              <div className="cdc-empty__title">Sin reservaciones</div>
            </div>
          ) : [...reservaciones].sort((a, b) => a.fecha.localeCompare(b.fecha)).map(r => (
            <div key={r.id} style={{ background: "white", border: "1px solid var(--cdc-border)", borderRadius: 14, padding: "12px 14px", display: "flex", flexDirection: "column", gap: 6 }}>
              <div style={{ display: "flex", justifyContent: "space-between", gap: 8, alignItems: "flex-start" }}>
                <div style={{ fontFamily: "var(--cdc-display)", fontSize: 17, fontWeight: 600 }}>{r.actividad}</div>
                <span className="cdc-badge" style={{
                  background: r.pago === "100" ? "var(--cdc-done-bg)" : "var(--cdc-pending-bg)",
                  color: r.pago === "100" ? "var(--cdc-done)" : "var(--cdc-pending)",
                }}>
                  {r.pago === "100" ? "Pagado 100%" : "Anticipo 50%"}
                </span>
              </div>
              <div style={{ fontSize: 12, color: "var(--cdc-ink-3)", display: "inline-flex", alignItems: "center", gap: 6, flexWrap: "wrap" }}>
                <I.Calendar size={12} /> {fmtShortDate(r.fecha)}
                <span style={{ color: "var(--cdc-ink-4)" }}>·</span>
                <I.Clock size={12} /> {r.pickupTime}
                <span style={{ color: "var(--cdc-ink-4)" }}>·</span>
                <I.Users2 size={12} /> {r.pax} pax
              </div>
              <div style={{ fontSize: 12.5, color: "var(--cdc-ink-2)" }}>
                <strong>{r.cliente}</strong>
                {r.departurePoint && <div style={{ color: "var(--cdc-ink-3)", fontSize: 11.5, marginTop: 2 }}>📍 {r.departurePoint}</div>}
                {r.tripHours && <div style={{ color: "var(--cdc-ink-3)", fontSize: 11.5, marginTop: 2 }}>⏱ {r.tripHours} h</div>}
              </div>
              {r.notas && <div style={{ fontSize: 11.5, color: "var(--cdc-ink-3)", borderTop: "1px dashed var(--cdc-border-soft)", paddingTop: 6 }}>{r.notas}</div>}
            </div>
          ))
        )}

        {section === "menus" && (
          menus.map(m => {
            const IconCmp = I[m.icon] || I.Chef;
            return (
              <button
                key={m.id}
                onClick={() => setActiveMenu(m.id)}
                style={{ background: "white", border: "1px solid var(--cdc-border)", borderRadius: 14, padding: "12px 14px", textAlign: "left", display: "flex", alignItems: "center", gap: 12, cursor: "pointer" }}
              >
                <span style={{ display: "inline-flex", alignItems: "center", justifyContent: "center", width: 38, height: 38, borderRadius: 10, background: "var(--cdc-coral-soft)", color: "var(--cdc-coral-deep)", flexShrink: 0 }}>
                  <IconCmp size={18} />
                </span>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontWeight: 600, fontSize: 13.5, color: "var(--cdc-ink)", lineHeight: 1.3 }}>{m.name}</div>
                  <div style={{ fontSize: 11.5, color: "var(--cdc-ink-3)", marginTop: 2 }}>{m.items.length} ítems · ver detalle</div>
                </div>
                <I.ChevR size={14} style={{ color: "var(--cdc-ink-3)" }} />
              </button>
            );
          })
        )}

        {section === "compras" && (
          pending.length === 0 ? (
            <div className="cdc-empty" style={{ padding: 30 }}>
              <I.Cart size={36} style={{ color: "var(--cdc-done)" }} />
              <div className="cdc-empty__title">Sin compras pendientes</div>
            </div>
          ) : pending.map(it => (
            <div key={it.id} style={{
              background: "white", border: "1px solid var(--cdc-border)", borderRadius: 14,
              padding: "12px 14px", display: "flex", flexDirection: "column", gap: 8,
              borderLeft: `4px solid ${it.priority === "alta" ? "var(--cdc-overdue)" : it.priority === "media" ? "var(--cdc-med)" : "var(--cdc-cream-300)"}`,
            }}>
              <div style={{ display: "flex", justifyContent: "space-between", gap: 6, alignItems: "baseline" }}>
                <div style={{ fontWeight: 600, fontSize: 13.5, color: "var(--cdc-ink)" }}>{it.name}</div>
                <div style={{ fontSize: 12, color: "var(--cdc-ink-2)", fontWeight: 600, whiteSpace: "nowrap" }}>{it.qty} {it.unit}</div>
              </div>
              {it.note && <div style={{ fontSize: 11.5, color: "var(--cdc-ink-3)", lineHeight: 1.4 }}>{it.note}</div>}
              {setCompras && (
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 6, paddingTop: 6, borderTop: "1px dashed var(--cdc-border-soft)" }}>
                  <button
                    onClick={() => setCompras(prev => ({ ...prev, yate: prev.yate.map(x => x.id === it.id ? { ...x, status: "entregado" } : x) }))}
                    style={{ padding: "9px 8px", borderRadius: 10, border: 0, background: "var(--cdc-done-bg)", color: "var(--cdc-done)", fontWeight: 700, fontSize: 12, display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 6 }}
                  >
                    <I.Check size={13} stroke={2.4} /> Comprado
                  </button>
                  <button
                    onClick={() => setCompras(prev => ({ ...prev, yate: prev.yate.map(x => x.id === it.id ? { ...x, status: "no_encontrado" } : x) }))}
                    style={{ padding: "9px 8px", borderRadius: 10, border: 0, background: "var(--cdc-overdue-bg)", color: "var(--cdc-overdue)", fontWeight: 700, fontSize: 12, display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 6 }}
                  >
                    <I.X size={13} stroke={2.4} /> No encontrado
                  </button>
                </div>
              )}
            </div>
          ))
        )}
      </div>

      <BottomNav />
    </>
  );
};

Object.assign(window, { MobileYate });
